首页 > 编程语言 >Python OpenCV4趣味应用系列(四)---颜色物体实时检测

Python OpenCV4趣味应用系列(四)---颜色物体实时检测

时间:2022-10-18 22:31:54浏览次数:39  
标签:阈值 Python mask cv2 --- green OpenCV4 red 255


今天,我们来实现一个视频实时检测颜色物体的小实例,视频中主要有三个颜色物体,我们只检测红色和绿色的球状物体,如下图所示:

Python OpenCV4趣味应用系列(四)---颜色物体实时检测_ide

第一步需要打开视频(或者摄像头):

cap = cv2.VideoCapture('1.mp4')  # 打开视频文件
# cap = cv2.VideoCapture(0) # 打开USB摄像头

然后需要循环取帧,进行颜色物体检测。检测颜色物体使用的是HSV阈值来筛选颜色,所以HSV阈值的设定是关键,下面是常用颜色的HSV表:

Python OpenCV4趣味应用系列(四)---颜色物体实时检测_usb摄像头_02

但是针对具体图片还需要自己写个小工具去提取图片上的目标的HSV值,然后手动设定阈值,比如在上面图片中我们使用的红色和绿色的HSV阈值分别如下:

lower_green = np.array([35, 110, 106])  # 绿色范围低阈值
upper_green = np.array([77, 255, 255]) # 绿色范围高阈值

lower_red = np.array([0, 127, 128]) # 红色范围低阈值
upper_red = np.array([10, 255, 255]) # 红色范围高阈值

接下来就是滤波处理,轮廓提取以及最终结果的标示了,用矩形框标注检测的物体,同时用putText函数标注颜色,完整代码和最终效果如下:

完整代码:


# -*- coding: cp936 -*-
import numpy as np

import cv2

font = cv2.FONT_HERSHEY_SIMPLEX

lower_green = np.array([35, 110, 106]) # 绿色范围低阈值
upper_green = np.array([77, 255, 255]) # 绿色范围高阈值

lower_red = np.array([0, 127, 128]) # 红色范围低阈值
upper_red = np.array([10, 255, 255]) # 红色范围高阈值

cap = cv2.VideoCapture('1.mp4') # 打开视频文件
# cap = cv2.VideoCapture(0)#打开USB摄像头


if (cap.isOpened()): # 视频打开成功
flag = 1
else:
flag = 0

num = 0
if (flag):
while (True):
ret, frame = cap.read() # 读取一帧
# if(frame is None):
if ret == False: # 读取帧失败
break
hsv_img = cv2.cvtColor(frame, cv2.COLOR_BGR2HSV)
mask_green = cv2.inRange(hsv_img, lower_green, upper_green) # 根据颜色范围删选
mask_red = cv2.inRange(hsv_img, lower_red, upper_red) # 根据颜色范围删选
mask_green = cv2.medianBlur(mask_green, 7) # 中值滤波
mask_red = cv2.medianBlur(mask_red, 7) # 中值滤波
mask = cv2.bitwise_or(mask_green, mask_red)
cv2.imshow('mask_green', mask_green)
cv2.imshow('mask_red', mask_red)
cv2.imshow('mask', mask)
mask_green, contours, hierarchy = cv2.findContours(mask_green, cv2.RETR_EXTERNAL, cv2.CHAIN_APPROX_NONE)
mask_red, contours2, hierarchy2 = cv2.findContours(mask_red, cv2.RETR_EXTERNAL, cv2.CHAIN_APPROX_NONE)

for cnt in contours:
(x, y, w, h) = cv2.boundingRect(cnt)
cv2.rectangle(frame, (x, y), (x + w, y + h), (0, 255, 255), 2)
cv2.putText(frame, "green", (x, y - 5), font, 0.7, (0, 255, 0), 2)

for cnt2 in contours2:
(x2, y2, w2, h2) = cv2.boundingRect(cnt2)
cv2.rectangle(frame, (x2, y2), (x2 + w2, y2 + h2), (0, 255, 255), 2)
cv2.putText(frame, "red", (x2, y2 - 5), font, 0.7, (0, 0, 255), 2)
num = num + 1
cv2.imshow("result", frame)
cv2.imwrite("imgs/%d.jpg"%num, frame)

if cv2.waitKey(20) & 0xFF == 27: # 按下Esc键退出
break

cv2.waitKey(0)

cv2.destroyAllWindows()

最终效果动画:

Python OpenCV4趣味应用系列(四)---颜色物体实时检测_中值滤波_03

Python OpenCV4趣味应用系列(四)---颜色物体实时检测_中值滤波_04

标签:阈值,Python,mask,cv2,---,green,OpenCV4,red,255
From: https://blog.51cto.com/stq054188/5768299

相关文章