如何使用opencv-python中的摄像头分别对红 蓝 黄三种物体进行识别 并对识别到的物体进行形状与颜色标注并进行展示
时间: 2023-06-18 17:02:31 浏览: 101
基于dilb库+opencv实现摄像头实时人脸识别python源码+超详细注释+项目说明(易运行、操作简单).zip
可以按照以下步骤来实现:
1. 导入所需库
```python
import cv2
import numpy as np
```
2. 定义颜色范围
```python
# 定义颜色范围
lower_red = np.array([0, 50, 50])
upper_red = np.array([10, 255, 255])
lower_blue = np.array([110, 50, 50])
upper_blue = np.array([130, 255, 255])
lower_yellow = np.array([20, 50, 50])
upper_yellow = np.array([30, 255, 255])
```
3. 打开摄像头并进行物体识别
```python
# 打开摄像头
cap = cv2.VideoCapture(0)
while True:
# 读取摄像头中的图像
ret, frame = cap.read()
# 将图像转换为HSV格式
hsv = cv2.cvtColor(frame, cv2.COLOR_BGR2HSV)
# 对红色物体进行识别
mask_red = cv2.inRange(hsv, lower_red, upper_red)
contours_red, _ = cv2.findContours(mask_red, cv2.RETR_TREE, cv2.CHAIN_APPROX_SIMPLE)
for contour in contours_red:
area = cv2.contourArea(contour)
if area > 500:
# 绘制物体的轮廓
cv2.drawContours(frame, contour, -1, (0, 0, 255), 2)
# 获取物体的形状
approx = cv2.approxPolyDP(contour, 0.015 * cv2.arcLength(contour, True), True)
corners = len(approx)
if corners == 3:
shape = "三角形"
elif corners == 4:
shape = "矩形"
else:
shape = "圆形"
# 在物体上方标注形状和颜色
x, y, w, h = cv2.boundingRect(contour)
cv2.putText(frame, "Red " + shape, (x, y - 10), cv2.FONT_HERSHEY_SIMPLEX, 0.5, (0, 0, 255), 2)
# 对蓝色物体进行识别
mask_blue = cv2.inRange(hsv, lower_blue, upper_blue)
contours_blue, _ = cv2.findContours(mask_blue, cv2.RETR_TREE, cv2.CHAIN_APPROX_SIMPLE)
for contour in contours_blue:
area = cv2.contourArea(contour)
if area > 500:
cv2.drawContours(frame, contour, -1, (255, 0, 0), 2)
approx = cv2.approxPolyDP(contour, 0.015 * cv2.arcLength(contour, True), True)
corners = len(approx)
if corners == 3:
shape = "三角形"
elif corners == 4:
shape = "矩形"
else:
shape = "圆形"
x, y, w, h = cv2.boundingRect(contour)
cv2.putText(frame, "Blue " + shape, (x, y - 10), cv2.FONT_HERSHEY_SIMPLEX, 0.5, (255, 0, 0), 2)
# 对黄色物体进行识别
mask_yellow = cv2.inRange(hsv, lower_yellow, upper_yellow)
contours_yellow, _ = cv2.findContours(mask_yellow, cv2.RETR_TREE, cv2.CHAIN_APPROX_SIMPLE)
for contour in contours_yellow:
area = cv2.contourArea(contour)
if area > 500:
cv2.drawContours(frame, contour, -1, (0, 255, 255), 2)
approx = cv2.approxPolyDP(contour, 0.015 * cv2.arcLength(contour, True), True)
corners = len(approx)
if corners == 3:
shape = "三角形"
elif corners == 4:
shape = "矩形"
else:
shape = "圆形"
x, y, w, h = cv2.boundingRect(contour)
cv2.putText(frame, "Yellow " + shape, (x, y - 10), cv2.FONT_HERSHEY_SIMPLEX, 0.5, (0, 255, 255), 2)
# 显示识别后的图像
cv2.imshow("Object Detection", frame)
# 按下q键退出程序
if cv2.waitKey(1) & 0xFF == ord('q'):
break
# 释放摄像头并关闭窗口
cap.release()
cv2.destroyAllWindows()
```
在程序中,首先打开摄像头,然后将读取到的图像转换为HSV格式,接着分别对红色、蓝色和黄色物体进行识别,获取它们的轮廓、形状和颜色,并在物体上方标注出来,最后将识别后的图像展示在窗口中。当按下q键时,程序退出,释放摄像头并关闭窗口。
阅读全文