Random Color Detection in Images

  • Share this:

Code introduction


This code defines a function that detects and displays the contours of a specific color in an image. It first converts the image from the BGR color space to the HSV color space, then defines HSV ranges for the randomly selected color. Next, a mask is created for the selected color, and contours of that color in the image are found. Finally, the contours are drawn on the original image, and the result is displayed.


Technology Stack : opencv-python, numpy

Code Type : The type of code

Code Difficulty : Intermediate


                
                    
import cv2
import numpy as np
import random

def random_color_detection(image_path):
    # Load the image
    image = cv2.imread(image_path)
    
    # Convert the image to HSV color space
    hsv = cv2.cvtColor(image, cv2.COLOR_BGR2HSV)
    
    # Define range of colors to detect (randomly selected)
    colors = {
        'red': [(0, 120, 70), (10, 255, 255)],
        'green': [(36, 25, 25), (86, 255, 255)],
        'blue': [(100, 150, 0), (140, 255, 255)],
        'yellow': [(15, 100, 100), (35, 255, 255)],
        'purple': [(120, 50, 50), (150, 255, 255)],
        'cyan': [(75, 100, 100), (135, 255, 255)],
        'white': [(0, 0, 0], [180, 255, 255])
    }
    
    # Randomly select a color to detect
    color_to_detect = random.choice(list(colors.keys()))
    lower_bound, upper_bound = colors[color_to_detect]
    
    # Create a mask for the selected color
    mask = cv2.inRange(hsv, lower_bound, upper_bound)
    
    # Find contours of the color
    contours, _ = cv2.findContours(mask.copy(), cv2.RETR_EXTERNAL, cv2.CHAIN_APPROX_SIMPLE)
    
    # Draw contours on the original image
    for contour in contours:
        cv2.drawContours(image, [contour], -1, (0, 255, 0), 2)
    
    # Display the result
    cv2.imshow('Detected Color', image)
    cv2.waitKey(0)
    cv2.destroyAllWindows()