我是 CV2 的新手,我正在为应用程序寻找一些高级指导。我正在开发一个程序,可以检测相机画面中的红色和蓝色 bean 袋。我尝试使用 openCV 提供的示例代码来检测蓝色,并稍微修改它以检测红色。
import cv2
import numpy as np
import matplotlib.pyplot as plt
import matplotlib.image as mpimg
cap = cv2.VideoCapture(0)
while(1):
# Take each frame
_, frame = cap.read()
# Convert BGR to HSV
hsv = cv2.cvtColor(frame, cv2.COLOR_BGR2HSV)
# define range of blue color in HSV
lower_blue = np.array([110,50,50])
upper_blue = np.array([130,255,255])
lower_red = np.array([-20, 100, 100])
upper_red = np.array([13, 255, 255])
# Threshold the HSV image to get only blue colors
mask = cv2.inRange(hsv, lower_red, upper_red)
# Bitwise-AND mask and original image
res = cv2.bitwise_and(frame,frame, mask= mask)
cv2.imshow('frame',frame)
cv2.imshow('mask',mask)
cv2.imshow('res',res)
k = cv2.waitKey(5) & 0xFF
if k == 27:
break
cv2.destroyAllWindows()
这是(稍作修改)从 OpenCV 站点复制和粘贴的代码。我正在寻找分析 res
的正确方法维度的 numpy 数组 <460, 640, 3>
为了检测到
- 我的屏幕上有红色/蓝色物体
- 使用此信息做一些事情,例如
print(1 red and 2 blue squares detected)
最佳答案
您需要获得两个面具,一个用于红色,另一个用于蓝色:
mask_red = cv2.inRange(hsv, lower_red, upper_red)
mask_blue = cv2.inRange(hsv, lower_blue, upper_blue)
现在让我们定义一个函数来检测掩码中的给定区域是否超过阈值以决定是否存在 bean 袋,为此我们将使用cv2.findContours
。 .
def is_object_present(mask, threshold):
im, contours, hierarchy = cv2.findContours(mask.copy(), cv2.RETR_EXTERNAL, cv2.CHAIN_APPROX_NONE)
# Find the largest contour
largest_contour = max(contours, key=lambda x:cv2.contourArea(x))
if cv2.contourArea(largest_contour) > threshold:
return True
return False
现在,如果存在红 bean 袋或蓝 bean 袋,则在两个掩码上调用此方法以获取各自的值:
# Adjust this manually as per your needs
bean_bag_area_threshold = 5000
is_red_bean_bag_present = is_object_present(mask_red, bean_bag_area_threshold)
is_blue_bean_bag_present = is_object_present(mask_blue, bean_bag_area_threshold)
if is_red_bean_bag_present and is_blue_bean_bag_present:
print "Both bean bags are present."
关于python - 使用 Python 和 CV2 检测红色和蓝色方 block ( bean 袋),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44073156/