Programming, Python, Tutorials

RGB Trackbar in OpenCV python

Trackbars are helpful to instantaneously test and experiment with different parameters and values and observe the output in real time which out re-running the program again and again.

Read tutorial on How to add trackbar in your application.

Computer graphics are made of pixels [Read more on Anatomy of a digital image.]

Any color you seen on your screen has 3 component Red, green and blue.

The value of Red, Green and Blue can range from 0 -255 and by mixing different values of red, green and blue a new color is formed.

To Visualize this Mixing of R,G,B values we can create a python script.

The below python script contains 3 trackbars to control the concentration of Red, Green, and Blue color in the image.

RGB Trackbar
  • R – Red
  • G – Green
  • B – Blue

Each trackbas has fixed lower bound of 0 and upper bound of 255.

RGB Trackbar python code

#import opencv and numpy
import cv2  
import numpy as np

#trackbar callback fucntion does nothing but required for trackbar
def nothing(x):

#create a seperate window named 'controls' for trackbar
cv2.resizeWindow("controls", 550,10);

#create trackbar in 'controls' window with name 'r''

	#create a black image 
	img = np.zeros((512,512,3), np.uint8)
	#returns current position/value of trackbar 
	r= int(cv2.getTrackbarPos('r','controls'))

	#assign trackbar value to r,g,b channel of the image

	#waitfor the user to press escape and break the while loop 
	k = cv2.waitKey(1) & 0xFF
	if k == 27:
#destroys all window

By sliding the trackbar you can change the value of Red, Green, and Blue components and observe how the color in the explore window changes.

RGB trackbar output

More Trackbar Example:

Thank you for reading, Happy Learning, drop your suggestion in the comments.

Feel free to follow us on Youtube, Linked In , Instagram