python-opencv 利用trackbar找到理想的阈值(gray&HSV)

利用trackbar找到理想的阈值(gray&HSV)

环境:python opencv , jupyter notebook
有时候想要进行图片阈值处理,但是不能一下就找准想要的阈值。这时候,可以利用cv2.createTrackbar()函数。
拖动bar改变阈值,观察图片的分割效果,当分割到理想效果时,看bar的值,即为最合适的阈值。gray和HSV都可以处理。效果图:

python-opencv 利用trackbar找到理想的阈值(gray&HSV)_第1张图片
HSV空间分割浅绿色:

python-opencv 利用trackbar找到理想的阈值(gray&HSV)_第2张图片gray:

import cv2
import numpy as np
def nothing(x):
    pass
img = cv2.imread('Album.jpg',0)
cv2.namedWindow("tracking")
cv2.createTrackbar("l_T","tracking",220,255,nothing) # 220 起始值; 255 bar长度
cv2.createTrackbar("u_T","tracking",255,255,nothing)

while True:
    l_T=cv2.getTrackbarPos("l_T","tracking") # lower threshold
    u_T=cv2.getTrackbarPos("u_T","tracking") # upper threshold
    _,mask = cv2.threshold(img,l_T,u_T,cv2.THRESH_BINARY_INV) # 阈值处理
    cv2.imshow('img',img)
    cv2.imshow('mask',mask)
    key = cv2.waitKey(1) # Esc键
    if key == 27:
        break
cv2.destroyAllWindows()

HSV:
createTrackbar中的startValue是绿色的HSV范围,随便设置也可,反正可调:

绿色的HSV:
l_g = np.array([35, 43, 46]) # lower green value
u_g = np.array([77,255,255]) # upper green

import cv2
import numpy as np


def nothing(x):
    pass
    
# use track bar to perfectly define (1/2)
# the lower and upper values for HSV color space(2/2)
cv2.namedWindow("Tracking")
#参数:1 Lower/Upper HSV 3 startValue 4 endValue
cv2.createTrackbar("LH","Tracking",35,255,nothing)
cv2.createTrackbar("LS","Tracking",43,255,nothing)
cv2.createTrackbar("LV","Tracking",46,255,nothing)
cv2.createTrackbar("UH","Tracking",77,255,nothing)
cv2.createTrackbar("US","Tracking",255,255,nothing)
cv2.createTrackbar("UV","Tracking",255,255,nothing)


while True:
    frame = cv2.imread('color.jpg')
    hsv = cv2.cvtColor(frame,cv2.COLOR_BGR2HSV)
    
    l_h = cv2.getTrackbarPos("LH","Tracking")
    l_s = cv2.getTrackbarPos("LS","Tracking")
    l_v = cv2.getTrackbarPos("LV","Tracking")
    
    u_h = cv2.getTrackbarPos("UH","Tracking")
    u_s = cv2.getTrackbarPos("US","Tracking")
    u_v = cv2.getTrackbarPos("UV","Tracking")
    
    
    l_g = np.array([l_h, l_s, l_v]) # lower green value
    u_g = np.array([u_h,u_s,u_v])

    mask = cv2.inRange(hsv,l_g,u_g)
    
    res=cv2.bitwise_and(frame,frame,mask=mask) # src1,src2
     
    cv2.imshow("frame", frame)
    cv2.imshow("mask", mask)
    cv2.imshow("res", res)
    key = cv2.waitKey(1)
    if key == 27: # Esc
        break

cv2.destroyAllWindows()

你可能感兴趣的:(OpenCV,opencv)