Embedded_game/polygon/003.py

41 lines
1.0 KiB
Python
Raw Normal View History

2025-01-02 12:48:11 +08:00
# -*- coding:utf-8 -*-
# @Author len
# @Create 2023/10/28 20:35
import cv2
import numpy as np
# 读取图片
image = cv2.imread('exp6/crops/polygon/022.jpg')
# 将图片从BGR转换到HSV色彩空间
hsv = cv2.cvtColor(image, cv2.COLOR_BGR2HSV)
# 为蓝色定义HSV范围
lower_blue = np.array([100, 50, 50])
upper_blue = np.array([140, 255, 255])
# 使用HSV范围来创建一个蓝色的mask
mask = cv2.inRange(hsv, lower_blue, upper_blue)
# 使用高斯模糊减少噪声
blurred = cv2.GaussianBlur(mask, (5, 5), 0)
# 使用Canny边缘检测
edges = cv2.Canny(blurred, 50, 150)
# 在边缘图像上找到轮廓
contours, _ = cv2.findContours(edges, cv2.RETR_EXTERNAL, cv2.CHAIN_APPROX_SIMPLE)
for contour in contours:
# 过滤轮廓,例如根据轮廓的大小或形状
if cv2.contourArea(contour) > 100: # 根据需要调整阈值
x, y, w, h = cv2.boundingRect(contour)
cv2.rectangle(image, (x, y), (x+w, y+h), (0, 255, 0), 2)
# 显示结果
cv2.imshow('Detected Blue Square', image)
cv2.waitKey(0)
cv2.destroyAllWindows()