python - 迭代所有像素,如果在范围内,则将像素更改为黑色,否则更改为白色

标签 python opencv pixel mask

所以基本上,我想迭代所有像素,如果它们在范围内,则将它们的 RGB 值更改为白色,否则更改为黑色。

我见过几个使用掩码的示例,但我对如何使用掩码来比较 RGB 值有点困惑。 我的范围是这样的

min_YCrCb = np.array([0,133,77],np.uint8) 
max_YCrCb = np.array([255,173,127],np.uint8)

所以首先我在 YCrCb 中有我的图像,img。我如何创建一个蒙版,以便它可以查看 RGB 是否在范围内,完成后,如何将它们设置为黑色和白色?

最佳答案

我认为inRange方法就是您所需要的。

因此,在您的示例中您可以使用:

# Keep in mind that OpenCV stores things in BGR order, not RGB
lowerBound = cv.Scalar(0, 133, 770)
upperBound = cv.Scalar(255, 173, 127)

# this gives you the mask for those in the ranges you specified
cv.InRange(cv_input, lowerBound, upperBound, cv_output);

对于cv_input中的每个像素,如果其值在给定范围内,则将其设置为255(全1),否则设置为0。如果您想要反转,可以使用Not方法。

# This will set all bits in cv_input 
cv.Not(cv_output, cv_inverse)

关于python - 迭代所有像素,如果在范围内,则将像素更改为黑色,否则更改为白色,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38337872/

相关文章:

python - 值错误 : number of input channels does not match corresponding dimension of filter, 512 != 3

python - opencv导入导致python崩溃

opencv - 使用OpenCV固定网络摄像头视频中的位置

java - x 无法解析为变量

python - 通过套接字发送图像时遇到问题

python - 如何在Python中使用beautifulsoup查找字符串的第二次出现

c++ - 根据内核/掩码有效地迭代相关的相邻像素

python - 获取单个像素的值

python - 多个字典/字符串使其通过不应通过的 if 语句

c++ - 头部姿势估计opencv