About Lesson
In this Python OpenCV lesson we are going to learn about Python OpenCV Creating Color Trackbar, let’s create our example.
This is the complete source code for this lesson.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 |
import cv2 import numpy as np def nothing(x): pass # Create a black image, a window img = np.zeros((300,512,3), np.uint8) cv2.namedWindow('image') # create trackbars for color change cv2.createTrackbar('R','image',0,255,nothing) cv2.createTrackbar('G','image',0,255,nothing) cv2.createTrackbar('B','image',0,255,nothing) # create switch for ON/OFF functionality switch = '0 : OFF \n1 : ON' cv2.createTrackbar(switch, 'image',0,1,nothing) while(1): cv2.imshow('image',img) k = cv2.waitKey(1) & 0xFF if k == 27: break # get current positions of four trackbars r = cv2.getTrackbarPos('R','image') g = cv2.getTrackbarPos('G','image') b = cv2.getTrackbarPos('B','image') s = cv2.getTrackbarPos(switch,'image') if s == 0: img[:] = 0 else: img[:] = [b,g,r] cv2.destroyAllWindows() |
Using this code we are going to create an empty image.
1 |
img = np.zeros((300,512,3), np.uint8) |
We need too create track bars with different colors, for that we can use cv2.createTrackbar(), you need to pass parameters.
1 2 3 |
cv2.createTrackbar('R','image',0,255,nothing) cv2.createTrackbar('G','image',0,255,nothing) cv2.createTrackbar('B','image',0,255,nothing) |
Using this code we can get the position of the track bars.
1 2 3 4 |
r = cv2.getTrackbarPos('R','image') g = cv2.getTrackbarPos('G','image') b = cv2.getTrackbarPos('B','image') s = cv2.getTrackbarPos(switch,'image') |
Run the complete code and this will be the result.