程序師世界是廣大編程愛好者互助、分享、學習的平台,程序師世界有你更精彩!
首頁
編程語言
C語言|JAVA編程
Python編程
網頁編程
ASP編程|PHP編程
JSP編程
數據庫知識
MYSQL數據庫|SqlServer數據庫
Oracle數據庫|DB2數據庫
您现在的位置: 程式師世界 >> 編程語言 >  >> 更多編程語言 >> Python

Python opencv use slider to dynamically control parameters

編輯:Python

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()

  1. 上一篇文章:
  2. 下一篇文章:
Copyright © 程式師世界 All Rights Reserved