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 "Triangle"
elif len(approx) == 4:
# 判断是否是矩形或正方形
x, y, w, h = cv2.boundingRect(approx)
aspect_ratio = w / float(h)
if 0.95 < aspect_ratio < 1.05:
return "Square"
else:
return "Rectangle"
elif len(approx) > 4:
return "Circle"
return "Unknown"
# 打开摄像头
cap = cv2.VideoCapture(0)
while True:
# 读取一帧图像
ret, frame = cap.read()
if not ret:
break
# 转为灰度图像
gray = cv2.cvtColor(frame, cv2.COLOR_BGR2GRAY)
# 对图像进行模糊处理,减少噪声
blurred = cv2.GaussianBlur(gray, (5, 5), 0)
# 使用Canny边缘检测
edges = cv2.Canny(blurred, 50, 150)
# 找到轮廓
contours, _ = cv2.findContours(edges.copy(), cv2.RETR_EXTERNAL, cv2.CHAIN_APPROX_SIMPLE)
# 在原图上绘制轮廓和形状
for contour in contours:
if cv2.contourArea(contour) > 500: # 忽略小轮廓
# 获取形状名称
shape_name = detect_shape(contour)
# 获取轮廓的边界框
x, y, w, h = cv2.boundingRect(contour)
# 绘制轮廓和形状名称
cv2.rectangle(frame, (x, y), (x + w, y + h), (0, 255, 0), 2)
cv2.putText(frame, shape_name, (x, y - 10), cv2.FONT_HERSHEY_SIMPLEX, 0.9, (0, 255, 0), 2)
# 显示图像
cv2.imshow("Shape Detection", frame)
# 按 'q' 键退出
if cv2.waitKey(1) & 0xFF == ord('q'):
break
# 释放摄像头
cap.release()
cv2.destroyAllWindows()
Python程序:调用电脑摄像头识别摄像头中存在的物体的形状
最新推荐文章于 2025-03-23 22:49:44 发布