Python OpenCV – setTrackbarPos() Function
setTrackbarPos() function sets the position of the specified trackbar in the specified window. It does not return anything. setTrackbarPos() takes three arguments. The first is for the trackbar name and the second one is the window name which is the parent of the trackbar and the third one is for the new value of the position that is to be set to the trackbar. It returns None.
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
To create Track bars first import all the required libraries and create a window. Now create track bar(s) and add code to change or work as per their movement.
When we move the slider of any of the trackbar its corresponding getTrackbarPos() values changes and it returns the position of the specific slider. Through which we change the behavior accordingly.
Example: Using setTrackbarPos() function to change colors in a window
Python3
# Demo Trackbar# importing cv2 and numpyimport cv2import numpydef nothing(x): pass# Creating a window with black imageimg = numpy.zeros((300, 512, 3), numpy.uint8)cv2.namedWindow('image')# creating trackbars for red color changecv2.createTrackbar('R', 'image', 0, 255, nothing)# creating trackbars for Green color changecv2.createTrackbar('G', 'image', 0, 255, nothing)# creating trackbars for Blue color changecv2.createTrackbar('B', 'image', 0, 255, nothing)# setting position of 'G' trackbar to 100cv2.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 windowcv2.destroyAllWindows() |
Output:





