网络编程
位置:首页>> 网络编程>> Python编程>> Python-opencv实现红绿两色识别操作

Python-opencv实现红绿两色识别操作

作者:faith003  发布时间:2021-05-04 18:35:51 

标签:Python,opencv,红绿

1.颜色空间转换(RGB转HSV)

为了较准确的调红色和绿色的HSV,我使用cv2.createTrackbar()函数创建了六个滚动条


#创建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)

Python-opencv实现红绿两色识别操作

实际效果如图

Python-opencv实现红绿两色识别操作

Python-opencv实现红绿两色识别操作

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)

为了凸显出颜色的差距,我使用绿色的矩形框,画红色的物体,用红色的矩形框画绿色物体

Python-opencv实现红绿两色识别操作

来源:https://blog.csdn.net/faith003/article/details/97610992

0
投稿

猜你喜欢

手机版 网络编程 asp之家 www.aspxhome.com