#!/usr/bin/env python # -*- coding: utf-8 -*- import cv2 import numpy as np import rospy from sensor_msgs.msg import Image from cv_bridge import CvBridge, CvBridgeError # 定义要识别的颜色范围 lower_color = np.array([19, 78, 44]) upper_color = np.array([74, 202, 129]) # 初始化cv_bridge bridge = CvBridge() # 定义回调函数,处理订阅到的图像 def image_callback(msg): # 将ROS图像格式转换为OpenCV图像格式 try: cv_image = bridge.imgmsg_to_cv2(msg, 'bgr8') except CvBridgeError as e: print(e) return # 转换颜色空间 hsv = cv2.cvtColor(cv_image, cv2.COLOR_BGR2HSV) # 根据颜色范围进行二值化 mask = cv2.inRange(hsv, lower_color, upper_color) # 寻找轮廓 _, contours, _ = cv2.findContours(mask, cv2.RETR_TREE, cv2.CHAIN_APPROX_SIMPLE) # 遍历轮廓 for contour in contours: # 计算轮廓面积 area = cv2.contourArea(contour) # 忽略面积较小的轮廓 if area < 100: continue # 计算轮廓的外接矩形 x, y, w, h = cv2.boundingRect(contour) # 在原图上绘制外接矩形 cv2.rectangle(cv_image, (x, y), (x + w, y + h), (0, 255, 0), 2) # 显示图像 cv2.imshow('frame', cv_image) cv2.waitKey(1) # 初始化节点 rospy.init_node('color_detection') # 订阅摄像头图像 image_sub = rospy.Subscriber('/usb_cam/image_raw', Image, image_callback) # 进入循环 rospy.spin() # 关闭窗口 cv2.destroyAllWindows() 帮我改成检测多种色值的
时间: 2024-01-03 13:06:03 浏览: 115
USR-WIFI232-X-V4
好的,以下是修改后的代码:
```python
#!/usr/bin/env python
# -*- coding: utf-8 -*-
import cv2
import numpy as np
import rospy
from sensor_msgs.msg import Image
from cv_bridge import CvBridge, CvBridgeError
# 定义要识别的颜色范围
colors = {
'red': ([0, 50, 50], [10, 255, 255]),
'green': ([36, 25, 25], [86, 255, 255]),
'blue': ([100, 50, 50], [130, 255, 255])
}
# 初始化cv_bridge
bridge = CvBridge()
# 定义回调函数,处理订阅到的图像
def image_callback(msg):
# 将ROS图像格式转换为OpenCV图像格式
try:
cv_image = bridge.imgmsg_to_cv2(msg, 'bgr8')
except CvBridgeError as e:
print(e)
return
# 转换颜色空间
hsv = cv2.cvtColor(cv_image, cv2.COLOR_BGR2HSV)
# 遍历所有颜色范围,进行二值化和轮廓检测
for color_name, color_range in colors.items():
lower_color = np.array(color_range[0])
upper_color = np.array(color_range[1])
mask = cv2.inRange(hsv, lower_color, upper_color)
_, contours, _ = cv2.findContours(mask, cv2.RETR_TREE, cv2.CHAIN_APPROX_SIMPLE)
# 遍历轮廓,绘制外接矩形
for contour in contours:
area = cv2.contourArea(contour)
if area < 100:
continue
x, y, w, h = cv2.boundingRect(contour)
cv2.rectangle(cv_image, (x, y), (x + w, y + h), (0, 255, 0), 2)
# 显示图像
cv2.imshow('frame', cv_image)
cv2.waitKey(1)
# 初始化节点
rospy.init_node('color_detection')
# 订阅摄像头图像
image_sub = rospy.Subscriber('/usb_cam/image_raw', Image, image_callback)
# 进入循环
rospy.spin()
# 关闭窗口
cv2.destroyAllWindows()
```
在上述代码中,我们定义了一个字典 `colors`,其中包含要识别的多种颜色的范围。然后我们遍历所有颜色范围,进行二值化和轮廓检测,并在原图上绘制外接矩形。
阅读全文