64 lines
1.9 KiB
Python
64 lines
1.9 KiB
Python
|
# -*- coding:utf-8 -*-
|
||
|
# @Author len
|
||
|
# @Create 2023/10/28 9:28
|
||
|
|
||
|
|
||
|
import cv2
|
||
|
import numpy as np
|
||
|
|
||
|
def detect_shape(contour):
|
||
|
epsilon = 0.04 * cv2.arcLength(contour, True)
|
||
|
approx = cv2.approxPolyDP(contour, epsilon, True)
|
||
|
|
||
|
# 根据角点数量判断形状
|
||
|
if len(approx) == 3:
|
||
|
return "三角形"
|
||
|
elif len(approx) == 4:
|
||
|
return "四边形"
|
||
|
elif len(approx) == 10:
|
||
|
return "五角星"
|
||
|
else:
|
||
|
# 使用周长与面积的比值来判断圆形
|
||
|
area = cv2.contourArea(contour)
|
||
|
perimeter = cv2.arcLength(contour, True)
|
||
|
radius = perimeter / (2 * np.pi)
|
||
|
circle_area = np.pi * (radius ** 2)
|
||
|
|
||
|
# 这里0.2只是一个近似值,可能需要根据你的需求进行调整
|
||
|
if abs(circle_area - area) < area * 0.2:
|
||
|
return "圆形"
|
||
|
else:
|
||
|
return "未知形状"
|
||
|
|
||
|
|
||
|
|
||
|
# 读取图像并获取其大小
|
||
|
img = cv2.imread('./data/img.png')
|
||
|
h, w, _ = img.shape
|
||
|
|
||
|
# 获取图像的中心点颜色
|
||
|
center_color = img[h // 2, w // 2]
|
||
|
|
||
|
# 将中心点的颜色转换为HSV格式
|
||
|
hsv = cv2.cvtColor(img, cv2.COLOR_BGR2HSV)
|
||
|
center_color_hsv = cv2.cvtColor(np.uint8([[center_color]]), cv2.COLOR_BGR2HSV)[0][0]
|
||
|
# print(center_color_hsv[0])
|
||
|
# 根据中心点的颜色创建一个颜色掩码
|
||
|
lower_bound = np.array([(center_color_hsv[0] - 10) % 180, 50, 50])
|
||
|
upper_bound = np.array([(center_color_hsv[0] + 10) % 180, 255, 255])
|
||
|
mask = cv2.inRange(hsv, lower_bound, upper_bound)
|
||
|
|
||
|
# 寻找掩码中的轮廓
|
||
|
contours, _ = cv2.findContours(mask, cv2.RETR_EXTERNAL, cv2.CHAIN_APPROX_SIMPLE)
|
||
|
|
||
|
# 我们假设最大的轮廓是我们想要的
|
||
|
largest_contour = max(contours, key=cv2.contourArea)
|
||
|
|
||
|
shape = detect_shape(largest_contour)
|
||
|
print(f"识别到的形状是:{shape}")
|
||
|
|
||
|
# 显示结果
|
||
|
cv2.drawContours(img, [largest_contour], -1, (0, 255, 0), 2)
|
||
|
cv2.imshow('Detected Shape', img)
|
||
|
cv2.waitKey(0)
|
||
|
cv2.destroyAllWindows()
|