python - OpenCV python,如何以python方式将操作应用于单个 channel ?

标签 python opencv image-processing

假设我有一个尺寸为 1000x1000x3 的 OpenCV 图像

假设我想应用每像素操作

if pixel == (255, 255, 255): 
     pixel = (0, 255, 0)

很明显,我可以只写 2 个 for 循环,然后那样做。然而,在 python 中访问像素的 for 循环非常慢。

有人告诉我有一种 pythonic 方法可以做这样的事情,例如 img = cv2.min(img, 255) 会有效地找到垫子像素值和 255 的最小值限制单个 channel 图像上的值范围。

但是,我不确定如何以类似的方式将每像素 if 条件应用于每个像素。

最佳答案

您可以使用 numpy 条件:

例如,将 5x5 矩阵中的偶数替换为 42:

import numpy as np

a = np.arange(5*5).reshape((5,5))
print(a)

输出:

array([[ 0,  1,  2,  3,  4],
   [ 5,  6,  7,  8,  9],
   [10, 11, 12, 13, 14],
   [15, 16, 17, 18, 19],
   [20, 21, 22, 23, 24]])

a[a%2==0] = 42
print(a)

这会产生:

array([[42,  1, 42,  3, 42],
   [ 5, 42,  7, 42,  9],
   [42, 11, 42, 13, 42],
   [15, 42, 17, 42, 19],
   [42, 21, 42, 23, 42]])

对于您的图像,您需要更多操作。它会是这样的:

myImg = np.arange(1000*1000*3).reshape((1000,1000,3)) # replace with your image
colorVecs = np.reshape(myImg,(-1,3)) #so that each array element is a 1x3 vector
colorVecs[colorVecs == [255,255,255]] = [0,255,0]  #perform your operation

filteredImg = np.reshape(colorVecs,(1000,1000,3)) #back to a normal image

有关 numpy bool 掩码的更多信息 here

关于python - OpenCV python,如何以python方式将操作应用于单个 channel ?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55927472/

相关文章:

algorithm - opencv中的canny和contour有什么区别?

ios - 在 ios 中使用 opencv 用网格变换图像的特定区域

opencv - 找到眼睛的白色区域

algorithm - 在粉末衍射图像中寻找椭圆的算法比 MultiRANSAC 更好?

Python: List of sublists,写子列表不带括号

python - 从字节中将视频保存在python中

python - 如何在每次系统启动时使用 crontab 正确运行 Python 脚本

python - 使用直方图的图像python opencv中的颜色百分比

python - 如何使用 pd.Timestamp 函数将数据列更改为时间戳格式

python csv阅读器不处理引号