def detect_shapes(frame): # 将图像转换为HSV颜色空间 hsv = cv2.cvtColor(frame, cv2.COLOR_BGR2HSV) # 红色范围 lower_red = np.array([0, 100, 100]) upper_red = np.array([10, 255, 255]) red_mask1 = cv2.inRange(hsv, lower_red, upper_red) lower_red = np.array([160, 100, 100]) upper_red = np.array([179, 255, 255]) red_mask2 = cv2.inRange(hsv, lower_red, upper_red) red_mask = red_mask1 + red_mask2 # 蓝色范围 lower_blue = np.array([90, 100, 100]) upper_blue = np.array([130, 255, 255]) blue_mask = cv2.inRange(hsv, lower_blue, upper_blue) # 查找轮廓 contours, _ = cv2.findContours(red_mask + blue_mask, cv2.RETR_EXTERNAL, cv2.CHAIN_APPROX_SIMPLE) for contour in contours: # 计算轮廓的近似形状 epsilon = 0.02 * cv2.arcLength(contour, True) approx = cv2.approxPolyDP(contour, epsilon, True) # 获取轮廓的外接矩形 x, y, w, h = cv2.boundingRect(approx) # 根据轮廓的顶点数和颜色进行分类 if len(approx) == 3: if np.any(red_mask[y:y+h, x:x+w]): shape_label = "Red Triangle" else: shape_label = "Blue Triangle" elif len(approx) == 4: if np.any(red_mask[y:y+h, x:x+w]): shape_label = "Red Square" else: shape_label = "Blue Square" elif len(approx) > 4: if np.any(red_mask[y:y+h, x:x+w]): shape_label = "Red Circle" else: shape_label = "Blue Circle" else: shape_label = "Unknown" # 在图像上绘制边界框和标签https://cdn-static-devbit.csdn.net/ai100/chat/imgs/icon-send-active.png cv2.rectangle(frame, (x, y), (x+w, y+h), (0, 255, 0), 2) cv2.putText(frame, shape_label, (x, y-10), cv2.FONT_HERSHEY_SIMPLEX, 0.9, (0, 255, 0),
时间: 2024-04-15 09:24:21 浏览: 12
这段代码是一个用于检测图像中形状函数。它首先将图像转换为HSV颜色空间,然后定义了红色和蓝色的颜色范围,并通过调用`cv2.inRange()`函数创建了红色和蓝色的掩膜。
接下来,它通过调用`cv2.findContours()`函数查找图像中的轮廓。对于每个轮廓,它计算轮廓的近似形状并获取轮廓的外接矩形。然后,根据轮廓的顶点数和颜色进行分类,并为每个形状赋予相应的标签。
最后,它使用`cv2.rectangle()`函数在图像上绘制边界框,并使用`cv2.putText()`函数在边界框上方绘制形状的标签。
请注意,在最后一行代码中,函数调用被截断了,可能缺少了一些参数。您需要提供完整的函数调用才能使代码运行正确。
相关问题
import cv2 import time # 设置检测区域 region_of_interest = (0, 0, 100, 200) # 左上角位置和矩形宽高 # 延迟 daley = 1.5 def detect_colors(frame, region): # 转换颜色空间为HSV hsv = cv2.cvtColor(frame, cv2.COLOR_BGR2HSV) # # 设定红色的阈值范围 # lower_red = (0, 100, 100) # upper_red = (10, 255, 255) # 设定绿色的阈值范围 lower_while=(200,100,100) upper_while=(255,255,255) # 设定蓝色的阈值范围 lower_blue = (100, 100, 100) upper_blue = (130, 255, 255) # 提取感兴趣区域 roi = hsv[region[1]:region[1]+region[3], region[0]:region[0]+region[2]] # 对图像进行颜色过滤 # mask_red = cv2.inRange(roi, lower_red, upper_red) mask_green = cv2.inRange(roi, lower_while, upper_while) mask_blue = cv2.inRange(roi, lower_blue, upper_blue) # 检测红色并打印颜色信息 # if cv2.countNonZero(mask_red) > 0: # print("检测到红色") # time.sleep(daley) # return frame # 检测绿色并打印颜色信息 if cv2.countNonZero(mask_green) > 0: print("检测到绿色") time.sleep(daley) return frame # 检测蓝色并打印颜色信息 if cv2.countNonZero(mask_blue) > 0: print("检测到蓝色") time.sleep(daley) return frame return frame # 打开摄像头 cap = cv2.VideoCapture(0) while True: # 读取帧 ret, frame = cap.read() if ret: # 检测颜色并显示结果 result = detect_colors(frame, region_of_interest) cv2.imshow('Color Detection', result) # 按下ESC键退出循环 if cv2.waitKey(1) == 27: break # 释放摄像头和关闭窗口 cap.release() cv2.destroyAllWindows()
这段代码是一个简单的颜色检测程序,使用OpenCV来检测摄像头捕获的视频帧中的绿色和蓝色区域。
在代码中,您定义了一个名为`detect_colors`的函数,它接受一个视频帧和一个感兴趣区域作为输入。函数首先将帧转换为HSV颜色空间,然后设定了绿色和蓝色的阈值范围。接下来,函数提取感兴趣区域,并使用`cv2.inRange`函数将阈值应用于该区域,得到颜色的二值掩码。最后,函数通过计算二值掩码中非零像素的数量来判断是否检测到绿色或蓝色,并在检测到时打印相应的信息。
在主循环中,程序从摄像头读取帧,并调用`detect_colors`函数进行颜色检测。检测到绿色或蓝色时,会打印相应的信息并等待一段时间。检测结果会显示在名为"Color Detection"的窗口中。
按下ESC键时,程序会退出循环,并释放摄像头资源和关闭窗口。
请注意,根据您的实际需求,您可以根据`lower_while`和`upper_while`的值来调整绿色的阈值范围,以便更准确地检测您所需的颜色。
修改此代码使其可重复运行import pygame import sys from pygame.locals import * from robomaster import * import cv2 import numpy as np focal_length = 750 # 焦距 known_radius = 2 # 已知球的半径 def calculate_distance(focal_length, known_radius, perceived_radius): distance = (known_radius * focal_length) / perceived_radius return distance def show_video(ep_robot, screen): 获取机器人第一视角图像帧 img = ep_robot.camera.read_cv2_image(strategy="newest") 转换图像格式,转换为pygame的surface对象 img = cv2.cvtColor(img, cv2.COLOR_BGR2RGB) img = cv2.transpose(img) # 行列互换 img = pygame.surfarray.make_surface(img) screen.blit(img, (0, 0)) # 绘制图像 def detect_white_circle(ep_robot): 获取机器人第一视角图像帧 img = ep_robot.camera.read_cv2_image(strategy="newest") 转换为灰度图像 gray = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY) 进行中值滤波处理 gray = cv2.medianBlur(gray, 5) 检测圆形轮廓 circles = cv2.HoughCircles(gray, cv2.HOUGH_GRADIENT, 1, 50, param1=160, param2=40, minRadius=5, maxRadius=60) if circles is not None: circles = np.uint16(np.around(circles)) for circle in circles[0, :]: center = (circle[0], circle[1]) known_radius = circle 在图像上绘制圆形轮廓 cv2.circle(img, center, known_radius, (0, 255, 0), 2) 显示图像 distance = calculate_distance(focal_length, known_radius, known_radius) 在图像上绘制圆和距离 cv2.circle(img, center, known_radius, (0, 255, 0), 2) cv2.putText(img, f"Distance: {distance:.2f} cm", (center[0] - known_radius, center[1] - 10), cv2.FONT_HERSHEY_SIMPLEX, 0.5, (0, 255, 0), 2) cv2.imshow("White Circle Detection", img) cv2.waitKey(1) def main(): pygame.init() screen_size = width, height = 1280, 720 screen = pygame.display.set_mode(screen_size) ep_robot = robot.Robot() ep_robot.initialize(conn_type='ap') version = ep_robot.get_version() print("Robot version: {0}".format(version)) ep_robot.camera.start_video_stream(display=False) pygame.time.wait(100) clock = pygame.time.Clock() while True: clock.tick(5) # 将帧数设置为25帧 for event in pygame.event.get(): if event.type == QUIT: ep_robot.close() pygame.quit() sys.exit() show_video(ep_robot, screen) detect_white_circle(ep_robot) if name == 'main': main()
修改后的代码如下所示:
```python
import pygame
import sys
from pygame.locals import *
import robomaster
import cv2
import numpy as np
focal_length = 750 # 焦距
known_radius = 2 # 已知球的半径
def calculate_distance(focal_length, known_radius, perceived_radius):
distance = (known_radius * focal_length) / perceived_radius
return distance
def show_video(ep_robot, screen):
# 获取机器人第一视角图像帧
img = ep_robot.camera.read_cv2_image(strategy="newest")
# 转换图像格式,转换为pygame的surface对象
img = cv2.cvtColor(img, cv2.COLOR_BGR2RGB)
img = cv2.transpose(img) # 行列互换
img = pygame.surfarray.make_surface(img)
screen.blit(img, (0, 0)) # 绘制图像
def detect_white_circle(ep_robot):
# 获取机器人第一视角图像帧
img = ep_robot.camera.read_cv2_image(strategy="newest")
# 转换为灰度图像
gray = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)
# 进行中值滤波处理
gray = cv2.medianBlur(gray, 5)
# 检测圆形轮廓
circles = cv2.HoughCircles(gray, cv2.HOUGH_GRADIENT, 1, 50, param1=160, param2=40, minRadius=5, maxRadius=60)
if circles is not None:
circles = np.uint16(np.around(circles