1.创造窗口,创造轨迹条
cv2.namedWindow("TrackBars")
cv2.resizeWindow("TrackBars",640,240)
cv2.createTrackbar("Hue Min","TrackBars",0,179,empty)
cv2.createTrackbar("Hue Max","TrackBars",179,179,empty)
cv2.createTrackbar("Sat Min","TrackBars",0,255,empty)
cv2.createTrackbar("Sat Max","TrackBars",255,255,empty)
cv2.createTrackbar("Val Min","TrackBars",85,255,empty)
cv2.createTrackbar("Val Max","TrackBars",255,255,empty)
2.把轨迹条的参数改变和图片关联起来
h_min = cv2.getTrackbarPos("Hue Min", "TrackBars")
h_max = cv2.getTrackbarPos("Hue Max", "TrackBars")
s_min = cv2.getTrackbarPos("Sat Min", "TrackBars")
s_max = cv2.getTrackbarPos("Sat Max", "TrackBars")
v_min = cv2.getTrackbarPos("Val Min", "TrackBars")
v_max = cv2.getTrackbarPos("Val Max", "TrackBars")
3.运用于图片
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(img,img,mask=mask)
4.完整代码
import cv2
import numpy as np
def empty(a):
pass
path="D:/shijue/bij.jpg"
#创建轨迹条
cv2.namedWindow("TrackBars")
cv2.resizeWindow("TrackBars",640,240)
cv2.createTrackbar("Hue Min","TrackBars",0,179,empty)
cv2.createTrackbar("Hue Max","TrackBars",179,179,empty)
cv2.createTrackbar("Sat Min","TrackBars",0,255,empty)
cv2.createTrackbar("Sat Max","TrackBars",255,255,empty)
cv2.createTrackbar("Val Min","TrackBars",85,255,empty)
cv2.createTrackbar("Val Max","TrackBars",255,255,empty)
while True:
img=cv2.imread(path)
imgHSV=cv2.cvtColor(img,cv2.COLOR_BGR2HSV)
#应用于图片
h_min = cv2.getTrackbarPos("Hue Min", "TrackBars")
h_max = cv2.getTrackbarPos("Hue Max", "TrackBars")
s_min = cv2.getTrackbarPos("Sat Min", "TrackBars")
s_max = cv2.getTrackbarPos("Sat Max", "TrackBars")
v_min = cv2.getTrackbarPos("Val Min", "TrackBars")
v_max = cv2.getTrackbarPos("Val Max", "TrackBars")
print(h_max,h_min,s_min,s_max,v_max,v_min)
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(img,img,mask=mask)
cv2.namedWindow("Orginal",0)
cv2.resizeWindow("Orginal",600,400)
cv2.namedWindow("rest",0)
cv2.resizeWindow("rest",600,400)
cv2.imshow("Orginal", img)
cv2.imshow("rest",imgResult)
if cv2.waitKey(1)&0xFF==ord('p'): #按任意键停止
break