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

OpenCV-Python] Creation and use of slider Trackbar (createTrackbar())

編輯:Python

OpenCV-Python】滑動條Trackbar的創建和使用(createTrackbar())

一、前言

滑動條(Trackbar)It is a tool that can dynamically adjust parameters,它依附於窗口而存在.The interaction can be clearly felt,動態調參,針對尋找,rgb區間,hsv區間,etc. Algorithms where you can adjust parameters and see the effect,Scroll bars are a very useful tool

二、核心函數解析

There are two core functionscreateTrackbar(),getTrackbarPos()

函數名功能createTrackbar()創建滾動條getTrackbarPos()Get the current value of the scroll bar

1、createTrackbar() 參數解析

createTrackbar() This function is used to create a slider with adjustable values,並將滑動條附加到指定的窗口上.

該函數的參數有:
createTrackbar(const String& trackbarname, const String& winname, int *value, int count, TrackbarCallback onChange = 0, void *userdata = 0),具體含義為:

trackbarname:跟蹤欄名稱,The name of the created trackbar.
Winname:窗口的名字,表示這個軌跡條會依附到哪個窗口上,即對應namedWindow()The window name filled in when creating the window.
value:指向整數變量的可選指針,The value of this variable reflects the initial position of the slider.
count:表示滑塊可以達到的最大位置的值,The minimum position is always 0.
onChange:指向每次滑塊更改位置時要調用的函數的指針,有默認值0.此函數的原型應為void XXX (int, void *); ,The first parameter is the trackbar position,第二個參數是用戶數據(請參閱下一個參數).如果回調是NULL指針,then no callback is called,and only update the value.
userdata:User data passed to the callback,有默認值0.It can be used to handle trackbar events,而無需使用全局變量.

注:如果使用的第三個參數valueArguments are global variables or constants,完全可以不去管這個userdata參數.
Only the first four are required

2、getTrackbarPos() 參數解析

對於 getTrackbarPos() 函數,It also takes multiple parameters:

第一個參數是Tarckbar 名稱;
第二個參數是它附加到的窗口名稱;
第三個參數是默認值;
第四個參數是最大值;
The fifth is a callback function that executes every time the track bar value changes.回調函數始終具有默認參數,即軌跡欄位置.

注:In general, it is only necessary to have the former2個即可

三、Simple practical code

在這裡,我們將創建一個簡單的應用程序,to display the assignment by sliding the track barR,G,G的顏色.默認情況下,初始顏色將設置為黑色,代碼如下:

import cv2 as cv
import numpy as np
cv.namedWindow('image',256)
#滾動條事件,默認為無,No need to move it to change anything
def task():
pass
def demo():
cv.createTrackbar('R','image',0,255,task)
cv.createTrackbar('G','image',0,255,task)
cv.createTrackbar('B','image',0,255,task)
img=np.zeros((640,480,3),np.uint8)
while True:
r=cv.getTrackbarPos('R','image')
g=cv.getTrackbarPos('G','image')
b=cv.getTrackbarPos('B','image')
img[:]=[r,g,b]
cv.imshow('image',img)
if cv.waitKey(1) &0xFF==27:
break
cv.destrayAllWindows()
if __name__=='__main__':
demo()

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