OpenCV  3.1.0
Open Source Computer Vision
Trackbar as the Color Palette

Goal

Code Demo

Here we will create a simple application which shows the color you specify. You have a window which shows the color and three trackbars to specify each of B,G,R colors. You slide the trackbar and correspondingly window color changes. By default, initial color will be set to Black.

For cv2.getTrackbarPos() function, first argument is the trackbar name, second one is the window name to which it is attached, third argument is the default value, fourth one is the maximum value and fifth one is the callback function which is executed everytime trackbar value changes. The callback function always has a default argument which is the trackbar position. In our case, function does nothing, so we simply pass.

Another important application of trackbar is to use it as a button or switch. OpenCV, by default, doesn't have button functionality. So you can use trackbar to get such functionality. In our application, we have created one switch in which application works only if switch is ON, otherwise screen is always black.

1 import cv2
2 import numpy as np
3 
4 def nothing(x):
5  pass
6 
7 # Create a black image, a window
8 img = np.zeros((300,512,3), np.uint8)
9 cv2.namedWindow('image')
10 
11 # create trackbars for color change
12 cv2.createTrackbar('R','image',0,255,nothing)
13 cv2.createTrackbar('G','image',0,255,nothing)
14 cv2.createTrackbar('B','image',0,255,nothing)
15 
16 # create switch for ON/OFF functionality
17 switch = '0 : OFF \n1 : ON'
18 cv2.createTrackbar(switch, 'image',0,1,nothing)
19 
20 while(1):
21  cv2.imshow('image',img)
22  k = cv2.waitKey(1) & 0xFF
23  if k == 27:
24  break
25 
26  # get current positions of four trackbars
27  r = cv2.getTrackbarPos('R','image')
28  g = cv2.getTrackbarPos('G','image')
29  b = cv2.getTrackbarPos('B','image')
30  s = cv2.getTrackbarPos(switch,'image')
31 
32  if s == 0:
33  img[:] = 0
34  else:
35  img[:] = [b,g,r]
36 
37 cv2.destroyAllWindows()

The screenshot of the application looks like below :

trackbar_screenshot.jpg
image

Exercises

  1. Create a Paint application with adjustable colors and brush radius using trackbars. For drawing, refer previous tutorial on mouse handling.