Detect and Highlight Red Objects in Images

  • Share this:

Code introduction


This function detects red objects in an image using the OpenCV library, marks the red objects with red contours on the original image, and displays the result.


Technology Stack : OpenCV, NumPy

Code Type : Image processing

Code Difficulty : Intermediate


                
                    
def detect_red_objects(image_path):
    import cv2
    import numpy as np

    # Load the image
    image = cv2.imread(image_path)
    if image is None:
        print("Error: Image not found or unable to read.")
        return

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

    # Define the range for red color in HSV
    lower_red = np.array([0, 120, 70])
    upper_red = np.array([10, 255, 255])
    mask1 = cv2.inRange(hsv_image, lower_red, upper_red)

    lower_red = np.array([170, 120, 70])
    upper_red = np.array([180, 255, 255])
    mask2 = cv2.inRange(hsv_image, lower_red, upper_red)

    # Combine the masks to get the final mask for red color
    red_mask = cv2.bitwise_or(mask1, mask2)

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

    # Draw contours on the original image
    for contour in contours:
        cv2.drawContours(image, [contour], -1, (0, 0, 255), 2)

    # Display the image with red objects highlighted
    cv2.imshow('Red Objects', image)
    cv2.waitKey(0)
    cv2.destroyAllWindows()

    return image                
              
Tags: