因为OPENCV在对图像处理时,所使用的颜色阈值多是HSV,所以常常需要准确调整程序内所定义的颜色阈值。在此给出一个方便调用摄像头来快速调节HSV阈值的代码。
使用方法:
1.运行程序
2.将摄像头对准所需要调节阈值的物体
3.按下回车键,此时就会保留按下回车键时的那一帧图像。
4.调节阈值
5.调节完毕后,连续按两次ESC来结束程序。
import cv2
import numpy as np
#该函数用于返回各个滑条的数值
def empty(a):
h_min = cv2.getTrackbarPos("H Min", "TrackBars")
h_max = cv2.getTrackbarPos("H Max", "TrackBars")
s_min = cv2.getTrackbarPos("S Min", "TrackBars")
s_max = cv2.getTrackbarPos("S Max", "TrackBars")
v_min = cv2.getTrackbarPos("V Min", "TrackBars")
v_max = cv2.getTrackbarPos("V Max", "TrackBars")
return h_min, h_max, s_min, s_max, v_min, v_max
# 创建一个窗口,放置6个滑动条
cv2.namedWindow("TrackBars")
cv2.resizeWindow("TrackBars",640,320)
cv2.createTrackbar("H Min","TrackBars",0,179,empty)
cv2.createTrackbar("H Max","TrackBars",0,179,empty)
cv2.createTrackbar("S Min","TrackBars",0,255,empty)
cv2.createTrackbar("S Max","TrackBars",0,255,empty)
cv2.createTrackbar("V Min","TrackBars",0,255,empty)
cv2.createTrackbar("V Max","TrackBars",0,255,empty)
# 使用摄像头
cap = cv2.VideoCapture(1)
Key = 0
while cap.isOpened():
ret, image = cap.read()
cv2.imshow('Cap',image)
if cv2.waitKey(1) == 0xD:
Key = 1
while Key ==1 :
imgHSV = cv2.cvtColor(image, cv2.COLOR_BGR2HSV)
# 调用回调函数,获取滑动条的值
h_min, h_max, s_min, s_max, v_min, v_max = empty(0)
lower = np.array([h_min, s_min, v_min])
upper = np.array([h_max, s_max, v_max])
# 获得指定颜色范围内的掩码
mask = cv2.inRange(imgHSV, lower, upper)
# 对原图图像进行按位与的操作,掩码区域保留
imgResult = cv2.bitwise_and(image, image, mask=mask)
cv2.imshow("Mask", mask)
cv2.imshow("Result", imgResult)
if cv2.waitKey(1) == 27: # ESC键
Key =0
break
if cv2.waitKey(1) == 27: # ESC
break键
Key = 0
cv2.destroyAllWindows()