Random Shape Color Detection with OpenCV

  • Share this:

Code introduction


This code defines a function that detects random colored shapes in an image and uses OpenCV library features such as color space conversion, mask operations, and contour detection.


Technology Stack : The code uses the OpenCV library and its features such as color space conversion, mask operations, and contour detection.

Code Type : The type of code

Code Difficulty :


                
                    
def random_shape_color_detection(image_path):
    import cv2
    import numpy as np
    
    # 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
    lower_color_bound = np.array([0, 50, 50])
    upper_color_bound = np.array([10, 255, 255])
    mask1 = cv2.inRange(hsv_image, lower_color_bound, upper_color_bound)
    
    lower_color_bound = np.array([170, 50, 50])
    upper_color_bound = np.array([180, 255, 255])
    mask2 = cv2.inRange(hsv_image, lower_color_bound, upper_color_bound)
    
    # Combine masks
    combined_mask = cv2.bitwise_or(mask1, mask2)
    
    # Find contours
    contours, _ = cv2.findContours(combined_mask, 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 image
    cv2.imshow('Detected Shapes', image)
    cv2.waitKey(0)
    cv2.destroyAllWindows()