识别效果如图所示,尽量排除了蓝色背景的干扰,hsv可用滑块进行调节,更加方便
import cv2
import numpy as np# 创建一个命名窗口,用于显示滑块
cv2.namedWindow("TrackBar")def nothing(x):pass# 创建滑块控件
cv2.createTrackbar("Hue Min", "TrackBar", 0, 179, nothing)
cv2.createTrackbar("Hue Max", "TrackBar", 179, 179, nothing)
cv2.createTrackbar("Sat Min", "TrackBar", 99, 255, nothing)
cv2.createTrackbar("Sat Max", "TrackBar", 255, 255, nothing)
cv2.createTrackbar("Val Min", "TrackBar", 114, 255, nothing)
cv2.createTrackbar("Val Max", "TrackBar", 255, 255, nothing)# 初始化滑块值
cv2.setTrackbarPos("Hue Min", "TrackBar", 0)
cv2.setTrackbarPos("Hue Max", "TrackBar", 88)
cv2.setTrackbarPos("Sat Min", "TrackBar", 147)
cv2.setTrackbarPos("Sat Max", "TrackBar", 255)
cv2.setTrackbarPos("Val Min", "TrackBar", 114)
cv2.setTrackbarPos("Val Max", "TrackBar", 255)# 打开摄像头
cap = cv2.VideoCapture(0)if not cap.isOpened():print("Error: Could not open camera.")exit()while True:# 读取一帧视频ret, frame = cap.read()if not ret:print("Error: Could not read frame.")break# 转换图像颜色空间为HSVimgHSV = cv2.cvtColor(frame, cv2.COLOR_BGR2HSV)# 获取滑块的当前值hueLow = cv2.getTrackbarPos("Hue Min", "TrackBar")hueHigh = cv2.getTrackbarPos("Hue Max", "TrackBar")satLow = cv2.getTrackbarPos("Sat Min", "TrackBar")satHigh = cv2.getTrackbarPos("Sat Max", "TrackBar")valLow = cv2.getTrackbarPos("Val Min", "TrackBar")valHigh = cv2.getTrackbarPos("Val Max", "TrackBar")# 创建掩膜lower_red = np.array([hueLow, satLow, valLow])upper_red = np.array([hueHigh, satHigh, valHigh])mask = cv2.inRange(imgHSV, lower_red, upper_red)# 应用中值模糊来减少噪声mask = cv2.medianBlur(mask, 7)# 使用掩膜提取图像的特定部分imageResult = cv2.bitwise_and(frame, frame, mask=mask)# 查找轮廓contours, _ = cv2.findContours(mask, cv2.RETR_EXTERNAL, cv2.CHAIN_APPROX_SIMPLE)# 查找最大轮廓max_contour = Nonemax_area = 0for contour in contours:area = cv2.contourArea(contour)if area > max_area:max_area = areamax_contour = contour# 在原始图像上绘制矩形框if max_contour is not None and max_area > 500: # 忽略小区域x, y, w, h = cv2.boundingRect(max_contour)cv2.rectangle(frame, (x, y), (x+w, y+h), (0, 255, 0), 2)# 显示原始图像和掩膜效果cv2.imshow('Original', frame)cv2.imshow('HSV', imgHSV)cv2.imshow('Mask Result', imageResult)# 按'q'键退出if cv2.waitKey(1) == ord('q'):break# 释放摄像头并销毁所有窗口
cap.release()
cv2.destroyAllWindows()