Python OpenCV – setTrackbarPos()函数
setTrackbarPos()函数设置指定轨迹条在指定窗口中的位置。它不返回任何东西。 setTrackbarPos() 接受三个参数。第一个是轨迹栏名称,第二个是作为轨迹栏父级的窗口名称,第三个是要设置到轨迹栏的位置的新值。它返回无。
Syntax:
cv.setTrackbarPos( trackbarname, winname, pos)
Parameters:
- trackbarname – Name of trackbar.
- winname – Name of the window that is the parent of the trackbar.
- pos – New position.
Return:
None
要创建轨道栏,首先导入所有必需的库并创建一个窗口。现在创建轨迹栏并添加代码以根据它们的移动进行更改或工作。
当我们移动任何轨迹栏的滑块时,其对应的 getTrackbarPos() 值会发生变化,并返回特定滑块的位置。通过它我们相应地改变行为。
示例:使用 setTrackbarPos()函数更改窗口中的颜色
Python3
# Demo Trackbar
# importing cv2 and numpy
import cv2
import numpy
def nothing(x):
pass
# Creating a window with black image
img = numpy.zeros((300, 512, 3), numpy.uint8)
cv2.namedWindow('image')
# creating trackbars for red color change
cv2.createTrackbar('R', 'image', 0, 255, nothing)
# creating trackbars for Green color change
cv2.createTrackbar('G', 'image', 0, 255, nothing)
# creating trackbars for Blue color change
cv2.createTrackbar('B', 'image', 0, 255, nothing)
# setting position of 'G' trackbar to 100
cv2.setTrackbarPos('G', 'image', 100)
while(True):
# show image
cv2.imshow('image', img)
# for button pressing and changing
k = cv2.waitKey(1) & 0xFF
if k == 27:
break
# get current positions of all Three trackbars
r = cv2.getTrackbarPos('R', 'image')
g = cv2.getTrackbarPos('G', 'image')
b = cv2.getTrackbarPos('B', 'image')
# display color mixture
img[:] = [b, g, r]
# close the window
cv2.destroyAllWindows()
输出: