OpenCV Image Color Detection and Visualization

  • Share this:

Code introduction


This function uses the OpenCV library to detect red, green, and blue regions in an image and draws corresponding rectangles on the original image.


Technology Stack : OpenCV, NumPy, Python

Code Type : Image processing

Code Difficulty : Intermediate


                
                    
def random_color_detection(image_path):
    import cv2
    import numpy as np
    import random

    # Load the image
    image = cv2.imread(image_path)

    # Convert the image to HSV color space
    hsv_image = cv2.cvtColor(image, cv2.COLOR_BGR2HSV)

    # Define range of colors to detect
    colors = {
        'red': ([0, 120, 70], [10, 255, 255]),
        'green': ([36, 25, 25], [86, 255, 255]),
        'blue': ([100, 150, 0], [140, 255, 255])
    }

    # Initialize list to store the detected colors
    detected_colors = []

    # Loop through each color and detect it
    for color, (lower, upper) in colors.items():
        # Create a mask for the current color
        mask = cv2.inRange(hsv_image, lower, upper)

        # Find contours in the mask
        contours, _ = cv2.findContours(mask.copy(), cv2.RETR_EXTERNAL, cv2.CHAIN_APPROX_SIMPLE)

        # Loop through each contour and draw it on the original image
        for contour in contours:
            if cv2.contourArea(contour) > 100:  # Filter out small contours
                (x, y, w, h) = cv2.boundingRect(contour)
                cv2.rectangle(image, (x, y), (x + w, y + h), (0, 255, 0), 2)
                detected_colors.append(color)

    # Display the image with detected colors
    cv2.imshow('Detected Colors', image)
    cv2.waitKey(0)
    cv2.destroyAllWindows()

    return detected_colors