python opencv 使用电脑摄像头检测识别白色小球,利用相似三角形计算小球的距离的代码
时间: 2024-04-10 20:31:41 浏览: 18
import cv2
import numpy as np
def calculate_distance(focal_length, known_radius, perceived_radius):
distance = (known_radius * focal_length) / perceived_radius
return distance
def detect_ball():
# 定义相机内参
focal_length = 500 # 焦距
known_radius = 5 # 已知球的半径
# 打开摄像头
cap = cv2.VideoCapture(0)
while True:
ret, frame = cap.read()
if not ret:
break
# 转换颜色空间为HSV
hsv_frame = cv2.cvtColor(frame, cv2.COLOR_BGR2HSV)
# 设置白色小球的颜色范围
lower_white = np.array([0, 0, 200])
upper_white = np.array([180, 30, 255])
# 根据颜色范围创建掩膜
mask = cv2.inRange(hsv_frame, lower_white, upper_white)
# 对掩膜进行形态学操作,去除噪声
kernel = np.ones((5, 5), np.uint8)
mask = cv2.morphologyEx(mask, cv2.MORPH_OPEN, kernel)
# 查找轮廓
contours, _ = cv2.findContours(mask, cv2.RETR_EXTERNAL, cv2.CHAIN_APPROX_SIMPLE)
for contour in contours:
# 计算轮廓的面积和周长
area = cv2.contourArea(contour)
perimeter = cv2.arcLength(contour, True)
# 计算圆度,用来判断是否为圆形轮廓
circularity = 4 * np.pi * (area / (perimeter * perimeter))
if circularity > 0.8:
# 计算轮廓的外接圆半径
(x, y), radius = cv2.minEnclosingCircle(contour)
radius = int(radius)
# 计算小球的距离
distance = calculate_distance(focal_length, known_radius, radius)
# 在图像上绘制圆和距离
cv2.circle(frame, (int(x), int(y)), radius, (0, 255, 0), 2)
cv2.putText(frame, f"Distance: {distance} cm", (int(x) - radius, int(y) - 10),
cv2.FONT_HERSHEY_SIMPLEX, 0.5, (0, 255, 0), 2)
# 显示结果图像
cv2.imshow("Ball Detection", frame)
if cv2.waitKey(1) & 0xFF == ord('q'):
break
# 释放摄像头和销毁窗口
cap.release()
cv2.destroyAllWindows()
# 运行检测小球代码
detect_ball()