use opencv when , You must have encountered the scene of manual parameter adjustment , Is it too much trouble ?
I feel in trouble , use opencv Inside comes the sliding bar dynamic control parameter , It's not very fragrant ?
1. Create a slider
cv2.createTrackbar('Threshold', 'image', 0, 255, updateThreshold)
function :
Bind sliders and windows , Defines the value of the scroll bar .
The first parameter is the name of the slider ,
The second parameter is the name of the window where the slider is placed ,
The third parameter is the slider default value ,
The fourth parameter is the maximum value of the slider ,
The fifth parameter is the callback function , Each slide will call the callback function
2. Set slider defaults ( Actually, it's chicken ribs , Because you can set the default value when creating the slider )
cv2.setTrackbarPos('Threshold', 'image', 80)
The first parameter is the name of the slider ,
The second parameter is the name of the window where the slider is placed ,
The third parameter is the slider default value ;
3. Get the value of the slider
threshold = cv2.getTrackbarPos('Threshold', 'image')
The first parameter is the name of the slider ,
The second parameter is the name of the window where the slider is placed ,
4. Design callback function
Every time you change the value of the slider , It will trigger the execution of the callback function .
The callback function is the soul , Not much said , Look at my example .
5. Complete example
import cv2
threshold = 80
img_path = r"C:\Users\admin\Desktop\1.jpg"
img = cv2.imread(img_path)
img1 = cv2.cvtColor(img, cv2.COLOR_RGB2GRAY)
img2 = img1.copy()
# Create callback function
def updateThreshold(x):
# global There must be , In this way, the global variables can be modified
global threshold, img1, img2
# Get the threshold
threshold = cv2.getTrackbarPos('Threshold', 'image')
ret, img1 = cv2.threshold(img2, threshold, 255, 0)
print("threshold:",threshold)
# Create windows and sliders
cv2.namedWindow('image',cv2.WINDOW_NORMAL)
cv2.createTrackbar('Threshold', 'image', 0, 255, updateThreshold)
# Set slider defaults
cv2.setTrackbarPos('Threshold', 'image', 80)
# Constantly refresh the display
while (True):
cv2.imshow('image', img1)
if cv2.waitKey(1) == ord('q'):
break
cv2.destroyAllWindows()