我是CV2的新手,我正在为应用程序寻找一些高级指导。我正在开发一个程序,可以检测相机框架中的红色和蓝色豆袋。我玩了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
的{{1}} numpy数组的正确方法,以便检测
<460, 640, 3>
答案 0 :(得分:1)
你需要获得两个面具,一个用于红色,另一个用于蓝色:
mask_red = cv2.inRange(hsv, lower_red, upper_red)
mask_blue = cv2.inRange(hsv, lower_blue, upper_blue)
现在让我们定义一个函数,该函数检测掩码中的给定区域是否超过阈值以便在豆袋存在时作出决定,为此我们将使用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
现在你在两个面具上调用这个方法,以获得红豆袋或蓝豆袋时的单个值:
# 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."