OpenCV BGR color palette with trackbarsPython (original) (raw)

OpenCV BGR color palette with trackbars-Python

Last Updated : 11 Aug, 2025

Creating a color palette helps in exploring and visualizing colors interactively. Using **OpenCV in Python, we can add trackbars for Blue, Green and Red (BGR) channels. Adjusting these trackbars changes the values (0–255) in real time, making it easy to identify and use the corresponding RGB colors.

**Prerequisites:

Install them using pip if not already installed:

pip install opencv-python numpy

Approach

  1. Create a black window of size 512 x 512 with three color channels.
  2. Use **cv2.createTrackbar() to add three trackbars named Blue, Green, and Red.
  3. Each trackbar value ranges from 0 to 255.
  4. Continuously fetch the current positions of the trackbars using **cv2.getTrackbarPos().
  5. Update the window background color based on the trackbar positions.
  6. Exit when the ESC key is pressed.

Python implementation

Python `

import cv2 import numpy as np

def emptyFunction(): pass

def main(): image = np.zeros((512, 512, 3), np.uint8) windowName = "OpenCV Color Palette" cv2.namedWindow(windowName) cv2.createTrackbar('Blue', windowName, 0, 255, emptyFunction) cv2.createTrackbar('Green', windowName, 0, 255, emptyFunction) cv2.createTrackbar('Red', windowName, 0, 255, emptyFunction)

while True:
    cv2.imshow(windowName, image)
    if cv2.waitKey(1) == 27:
        break
    blue = cv2.getTrackbarPos('Blue', windowName)
    green = cv2.getTrackbarPos('Green', windowName)
    red = cv2.getTrackbarPos('Red', windowName)
    image[:] = [blue, green, red]
    print("BGR:", blue, green, red)
     
cv2.destroyAllWindows()

if name == "main": main()

`

**Output:

**Note: Above programs will not run on online IDE.

**Explanation: