确保你的电脑上已经安装了 OpenCV 库,可以使用pip install opencv-python
进行安装。 import cv2
import numpy as np
# 打开摄像头
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, (9, 9), 2)
# 使用霍夫圆变换检测圆形
circles = cv2.HoughCircles(blurred, cv2.HOUGH_GRADIENT, 1, 20,
param1=50, param2=30, minRadius=10, maxRadius=0)
# 如果检测到圆形
if circles is not None:
circles = np.round(circles[0, :]).astype("int")
for (x, y, r) in circles:
# 用黄线绘制圆形边缘
cv2.circle(frame, (x, y), r, (0, 255, 255), 2)
# 用红线绘制圆心
cv2.circle(frame, (x, y), 2, (0, 0, 255), 3)
# 显示处理后的图像
cv2.imshow('Circle Detection', frame)
# 按 'q' 键退出循环
if cv2.waitKey(1) & 0xFF == ord('q'):
break
# 释放摄像头并关闭所有窗口
cap.release()
cv2.destroyAllWindows()