59 lines
1.6 KiB
Python
59 lines
1.6 KiB
Python
|
# -*- coding:utf-8 -*-
|
||
|
# @Author len
|
||
|
# @Create 2023/10/28 12:18
|
||
|
|
||
|
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)
|
||
|
if abs(circle_area - area) < area * 0.2:
|
||
|
return "圆形"
|
||
|
else:
|
||
|
return "未知形状"
|
||
|
|
||
|
img = cv2.imread('exp4/crops/polygon/new_36.jpg')
|
||
|
|
||
|
# 转换为灰度图像
|
||
|
gray = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)
|
||
|
|
||
|
# 使用高斯模糊减少噪声
|
||
|
blurred = cv2.GaussianBlur(gray, (5, 5), 0)
|
||
|
|
||
|
# Canny边缘检测
|
||
|
edges = cv2.Canny(blurred, 50, 150)
|
||
|
|
||
|
# 寻找轮廓
|
||
|
contours, _ = cv2.findContours(edges, cv2.RETR_EXTERNAL, cv2.CHAIN_APPROX_SIMPLE)
|
||
|
|
||
|
# 删除面积小于阈值的轮廓
|
||
|
filtered_contours = [c for c in contours if cv2.contourArea(c) > 500]
|
||
|
|
||
|
# 检查是否有有效的轮廓
|
||
|
if len(filtered_contours) == 0:
|
||
|
print("没有找到有效的轮廓")
|
||
|
else:
|
||
|
# 找到面积最大的轮廓
|
||
|
largest_contour = max(filtered_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()
|