我正在尝试根据网络摄像头帧中颜色的检测来打开和关闭中继。由于它需要实时完成,我选择使用numpy切片。问题是numpy总是检测到我输入的颜色,除非我完全覆盖相机,我只是没有看到原因。
以下是相关的代码段:
import numpy as np
import cv2
import video
while True:
ret,frame = cam.read()
img = frame.copy()
sens = 20
b = 0
#roughly neon green
img1B = 20
img1G = 230
img1R = 50
if np.any(np.logical_and(img[:,:,0]>=img1B-sens, img[:,:,0]<=img1B+sens)):
b = True
else:
b = False
if np.any(np.logical_and(img[:,:,1]>=img1G-sens, img[:,:,1]<=img1G+sens)):
g = True
else:
g = False
if np.any(np.logical_and(img[:,:,2]>=img1R-sens, img[:,:,2]<=img1R+sens)):
r = True
else:
r = False
print b,g,r
除非凸轮看到霓虹绿色像素,否则B,G,R不应该一直是真的,所以我不确定发生了什么。
答案 0 :(得分:1)
您不需要使用numpy
操作三次来使问题过于复杂。您只需使用cv2.inRange()
和cv2.countNonZero()
即可完成工作。上述步骤可以调制为一种方法,您可以通过while
循环调用该方法来处理每个网络摄像头帧。
import cv2
def detect_color_blob(img_BGR, blob_color_BGR, tolerance, threshold):
blob_color_lower = [blob_color_BGR[0] - tolerance, blob_color_BGR[1] - tolerance, blob_color_BGR[2] - tolerance]
blob_color_upper = [blob_color_BGR[0] + tolerance, blob_color_BGR[1] + tolerance, blob_color_BGR[2] + tolerance]
# Get a Binary Mask, where 255 => blob color found and 0=> blob color NOT found
mask = cv2.inRange(img_BGR, blob_color_lower, blob_color_upper)
# Check if the detected number of pixels is greater than threshold.
return cv2.countNonZero(mask) > threshold