#创建HSV最低滚动条
cv2.createTrackbar('H_min','image',35,180,nothing)
cv2.createTrackbar('S_min','image',43,255,nothing)
cv2.createTrackbar('V_min','image',46,255,nothing)
#创建HSV最高滚动条
cv2.createTrackbar('H_max','image',0,180,nothing)
cv2.createTrackbar('S_max','image',255,255,nothing)
cv2.createTrackbar('V_max','image',255,255,nothing)
实际效果如图
2.识别颜色并画矩形框
颜色阈值已经确定了,这就可以进行颜色识别了。
为了让识别更稳定,在代码中加入自适应阈值。
th_img = cv2.adaptiveThreshold(mask,255,cv2.ADAPTIVE_THRESH_MEAN_C,cv2.THRESH_BINARY_INV,5,2)
3.画矩形框
使用函数cv2.findContours()来检测物体轮框
再使用函数cv2.boundingRect()查找最小矩形框
使用函数cv2.rectangle()画出
contours_green,hierarchy = cv2.findContours(th_green,cv2.RETR_EXTERNAL,cv2.CHAIN_APPROX_SIMPLE)
contours_red,hierarchy = cv2.findContours(th_red,cv2.RETR_EXTERNAL,cv2.CHAIN_APPROX_SIMPLE)
for red in contours_red:
x_red,y_red,w_red,h_red = cv2.boundingRect(red)
if w_red>width|h_red>height:
cv2.rectangle(img,(x_red,y_red),((x_red+h_red),(y_red+w_red)),(0,255,0),1)
for red in contours_red:
x_red,y_red,w_red,h_red = cv2.boundingRect(red)
if w_red>width|h_red>height:
cv2.rectangle(img,(x_red,y_red),((x_red+h_red),(y_red+w_red)),(0,255,0),1)