[英]Opencv: How to detect pixel color change
我成功地为使用创建的给定图片着色了我想要的区域
numpy (`img = np.zeros((512,512,3), np.uint8)`).
我使用OpenCV显示图片
cv2.imshow()
使用鼠标光标着色后,保存图片。
如何检测图像给定像素的颜色已被修改?
通常,可以使用常用的==
, <
, !=
等运算符比较两个数组。 比较返回一个布尔(真/假)数组:
import numpy as np
x = np.array([0, 1, 2, 3, 4])
y = np.array([9, 1, 2, 3, 7])
arrays_equal = x == y
arrays_equal
将是一个布尔数组,相等时为True
,不相等时为False
:
array([False, True, True, True, False], dtype=bool)
但是,还有一个警告,因为您正在处理图像数据。 最后,您可能想要获得的是一个2D数组 ,其中任何颜色都发生了变化,但是您正在比较两个3D数组 ,因此您将获得一个3D布尔数组作为输出。
例如:
im = np.zeros((5,5,3), dtype=np.uint8)
im2 = im.copy()
# Change a pixel in the blue band:
im2[0,0,2] = 255
# The transpose here is just so that the bands are printed individually
print (im == im2).T
这将产生:
[[[ True True True True True]
[ True True True True True]
[ True True True True True]
[ True True True True True]
[ True True True True True]]
[[ True True True True True]
[ True True True True True]
[ True True True True True]
[ True True True True True]
[ True True True True True]]
[[False True True True True]
[ True True True True True]
[ True True True True True]
[ True True True True True]
[ True True True True True]]]
当然,您可能想要的更像是最后一支乐队。
在这种情况下,您想使用np.all
来“减少”事物并获得2D数组,其中任何像素中的任何颜色都不同。
为此,我们将axis
kwarg用作np.all
来指定应沿最后一个轴进行比较(在这种情况下, -1
或2
是等效的: -1
表示“ last”):
np.all(im == im2, axis=-1)
产生:
array([[False, True, True, True, True],
[ True, True, True, True, True],
[ True, True, True, True, True],
[ True, True, True, True, True],
[ True, True, True, True, True]], dtype=bool)
还要注意,如果需要“翻转”此数组,则可以将!=
运算符与np.any
而不是np.all
或者可以使用~
(逻辑运算符不为numpy)取反。 例如opposite = ~boolean_array
。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.