You can download this code by clicking the button below.
This code is now available for download.
This function reads an image from a specified path, converts the image to the HSV color space, defines the HSV range for red color, creates a mask for red color, finds contours of red objects in the image, and draws the contours on the original image.
Technology Stack : OpenCV, NumPy
Code Type : Image processing
Code Difficulty : Intermediate
def detect_red_objects(image_path):
import cv2
import numpy as np
# Read the image
image = cv2.imread(image_path)
# Convert the image to HSV color space
hsv = 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])
lower_red2 = np.array([170, 120, 70])
upper_red2 = np.array([180, 255, 255])
# Create masks for red color
mask1 = cv2.inRange(hsv, lower_red, upper_red)
mask2 = cv2.inRange(hsv, lower_red2, upper_red2)
# Combine the masks
mask = cv2.add(mask1, mask2)
# Bitwise-AND the original image and mask
res = cv2.bitwise_and(image, image, mask=mask)
# Find contours
contours, _ = cv2.findContours(mask, cv2.RETR_TREE, cv2.CHAIN_APPROX_SIMPLE)
# Draw contours on the image
cv2.drawContours(image, contours, -1, (0, 255, 0), 3)
# Return the image with red objects highlighted
return image