opencv摄像头识别圆形三角形和矩形的代码
时间: 2023-06-06 17:06:35 浏览: 312
以下是一个实现圆形、三角形和矩形识别的 OpenCV 代码示例:
```python
import cv2
# 定义识别函数
def detect_shape(c):
shape = "unknown"
peri = cv2.arcLength(c, True)
approx = cv2.approxPolyDP(c, 0.04 * peri, True)
# 当逼近形状的顶点数为 3 时,判定为三角形
if len(approx) == 3:
shape = "triangle"
# 当逼近形状的顶点数为 4 时,计算宽高比来判定为矩形
elif len(approx) == 4:
(x, y, w, h) = cv2.boundingRect(approx)
ar = w / float(h)
shape = "rectangle" if ar >= 0.95 and ar <= 1.05 else "square"
# 当逼近形状的顶点数为大于 4 时,判定为圆形
else:
shape = "circle"
return shape
# 读取摄像头视频流
cap = cv2.VideoCapture(0)
while True:
# 读取视频帧
ret, frame = cap.read()
# 转换为灰度图像并进行边缘检测
gray = cv2.cvtColor(frame, cv2.COLOR_BGR2GRAY)
blurred = cv2.GaussianBlur(gray, (5, 5), 0)
edged = cv2.Canny(blurred, 50, 150)
# 寻找轮廓并进行形状识别
cnts, _ = cv2.findContours(edged.copy(), cv2.RETR_EXTERNAL, cv2.CHAIN_APPROX_SIMPLE)
for c in cnts:
# 忽略过小的轮廓
if cv2.contourArea(c) < 100:
continue
# 计算轮廓重心并在图像上标注识别结果
M = cv2.moments(c)
center = (int(M["m10"] / M["m00"]), int(M["m01"] / M["m00"]))
shape = detect_shape(c)
cv2.drawContours(frame, [c], -1, (0, 255, 0), 2)
cv2.putText(frame, shape, center, cv2.FONT_HERSHEY_SIMPLEX, 0.5, (255, 0, 0), 2)
# 显示图像
cv2.imshow("Frame", frame)
# 按 'q' 退出循环
if cv2.waitKey(1) & 0xFF == ord('q'):
break
# 释放资源
cap.release()
cv2.destroyAllWindows()
```
该代码通过边缘检测和轮廓找到图像中的形状,再根据形状的顶点数和宽高比来判断其为圆形、三角形或矩形。在运行代码前,需要确保已安装 OpenCV 库并连接了可用的摄像头设备。
阅读全文