import cv2 import numpy as np # 视频源设置为电脑摄像头,0通常代表默认摄像头 cap = cv2.VideoCapture(0) # 定义要追踪的颜色范围 # 注意:根据实际情况调整HSV值以精确匹配想要追踪的颜色 greenLower = np.array([(35, 46, 120)]) greenUpper = np.array([60, 255, 255]) while True: # 从摄像头读取一帧 ret, frame = cap.read() if not ret: break # 将BGR图像转换为HSV,因为HSV在颜色分割上更为直观 hsv = cv2.cvtColor(frame, cv2.COLOR_BGR2HSV) # 根据定义的HSV范围创建掩码 mask = cv2.inRange(hsv, greenLower, greenUpper) # 对原图像和掩码应用位运算,提取出指定颜色部分 result = cv2.bitwise_and(frame, frame, mask=mask) # 使用开运算和闭运算去除噪声 kernel = np.ones((5, 5), np.uint8) mask = cv2.morphologyEx(mask, cv2.MORPH_OPEN, kernel) mask = cv2.morphologyEx(mask, cv2.MORPH_CLOSE, kernel) # 查找轮廓 contours, _ = cv2.findContours(mask.copy(), cv2.RETR_EXTERNAL, cv2.CHAIN_APPROX_SIMPLE) # 遍历轮廓,画出边界框 for contour in contours: if cv2.contourArea(contour) > 100: # 过滤小面积噪点 x, y, w, h = cv2.boundingRect(contour) cv2.rectangle(frame, (x, y), (x+w, y+h), (0, 255, 0), 2) # 显示原图、掩码和结果图像 cv2.imshow('Original', frame) cv2.imshow('Mask', mask) cv2.imshow('Result', result) # 按'q'键退出循环 if cv2.waitKey(1) & 0xFF == ord('q'): break # 释放资源并关闭所有窗口 cap.release() cv2.destroyAllWindows()