BGR Color Palette with Trackbars Using Python and OpenCV

BGR Color Palette with Trackbars Using Python and OpenCV. OpenCV (Open Source Computer Vision Library) is a popular library designed for real-time computer vision tasks. It offers various functions to work with images and videos, making it an essential tool in computer vision applications.

In this tutorial, we will create an interactive RGB color palette with trackbars using OpenCV in Python. By adjusting these trackbars, the RGB values will change dynamically between 0 and 255, allowing you to experiment and find the exact color represented by those RGB values.

Required Libraries:

To build this RGB color palette, we will need the following libraries:

  1. OpenCV: For creating the window, trackbars, and capturing RGB values.
  2. NumPy: For handling arrays and creating a blank image (black window) where the colors will be displayed.

Approach:

We will create a blank black window with a resolution of 512×512 pixels and three color channels (Blue, Green, and Red). Using OpenCV’s built-in functions, we will set up trackbars to control the intensity of each color channel (BGR).

The range for these trackbars will be from 0 to 255, allowing for the full spectrum of color values. As we move the trackbars, the RGB values will update in real-time, and the black window will change to reflect the new color.

Steps:

  1. Create a Blank Black Window: Using NumPy, we will initialize a black window of 512×512 pixels, where each pixel has three channels for B, G, and R.
  2. Set Up Trackbars: With OpenCV’s createTrackbar() function, we will create three trackbars to control the Blue, Green, and Red color channels. These trackbars will allow the user to adjust the intensity of each color component.
  3. Update the Window in Real-Time: The values from the trackbars will be captured using getTrackbarPos() and used to modify the color displayed in the black window. Each time a trackbar is moved, the window will update to display the corresponding color based on the RGB values.

Here’s the full Python code for this project:

# Importing required libraries
import cv2
import numpy as np

# Define an empty function to handle trackbar events
def emptyFunction():
    pass

def main():
    # Create a blank black image of size 512x512 pixels with 3 color channels (B, G, R)
    image = np.zeros((512, 512, 3), np.uint8)  
    windowName = "OpenCV Color Palette"
    
    # Create a window with the specified name
    cv2.namedWindow(windowName)
    
    # Create trackbars for Blue, Green, and Red colors
    # The trackbars range from 0 to 255, representing the color intensity
    cv2.createTrackbar('Blue', windowName, 0, 255, emptyFunction)
    cv2.createTrackbar('Green', windowName, 0, 255, emptyFunction)
    cv2.createTrackbar('Red', windowName, 0, 255, emptyFunction)
    
    # Infinite loop to keep the window open until the ESC key is pressed
    while True:
        # Display the current image in the window
        cv2.imshow(windowName, image)
        
        # Exit the loop when the ESC key is pressed (ASCII value 27)
        if cv2.waitKey(1) == 27:
            break
        
        # Get the current positions of the trackbars
        blue = cv2.getTrackbarPos('Blue', windowName)
        green = cv2.getTrackbarPos('Green', windowName)
        red = cv2.getTrackbarPos('Red', windowName)
        
        # Update the image by filling it with the new color values from the trackbars
        image[:] = [blue, green, red]
        
        # Print the current RGB values to the console
        print(blue, green, red)
    
    # Close all windows when the loop is terminated
    cv2.destroyAllWindows()

# Calling the main function
if __name__ == "__main__":
    main()

Output:

Code Explanation:

  1. Importing Libraries: We start by importing the cv2 module from OpenCV and numpy as np. OpenCV helps with creating the window, trackbars, and managing image operations, while NumPy is used to create and manipulate the image array.
  2. emptyFunction(): This function is a placeholder and is required by the createTrackbar() method. Even though it doesn’t do anything here, it is essential for handling trackbar events.
  3. Main Function (main()):
    • A black image of size 512×512 pixels is created using NumPy. This image has three channels (representing Blue, Green, and Red).
    • The window is initialized using the cv2.namedWindow() method.
    • Three trackbars are created for Blue, Green, and Red color channels. The trackbars allow the user to adjust the intensity of these color channels, ranging from 0 (no color) to 255 (full intensity).
  4. Event Loop:
    • Inside the infinite loop, the program waits for user input, continuously displaying the updated image in the window.
    • The current positions of the Blue, Green, and Red trackbars are retrieved using the cv2.getTrackbarPos() function, and these values are used to update the image.
    • The image is updated in real-time with the RGB values provided by the trackbars, and the current values are printed to the console.
  5. Exit Condition: The loop breaks and the window closes when the user presses the ESC key.

Conclusion:

This tutorial demonstrates how to create an interactive RGB color palette using OpenCV in Python. By adjusting the trackbars, you can dynamically modify the intensity of the Blue, Green, and Red channels, instantly seeing the result in the window. This simple yet powerful example provides an intuitive way to explore and understand how RGB color values work in a practical setting.

Author

Sona Avatar

Written by

Leave a Reply

Trending

CodeMagnet

Your Magnetic Resource, For Coding Brilliance

Programming Languages

Web Development

Data Science and Visualization

Career Section

<script async src="https://pagead2.googlesyndication.com/pagead/js/adsbygoogle.js?client=ca-pub-4205364944170772"
     crossorigin="anonymous"></script>