Code introduction
This code defines a function that detects and displays the red regions in an image. It first converts the image from BGR color space to HSV color space, then defines the HSV range for red color and finds these colors through mask operations. Finally, it finds and draws the contours of these red regions.
Technology Stack : The code uses the OpenCV and NumPy libraries. OpenCV is used for image processing tasks such as color conversion, mask creation, and contour detection. NumPy is used for numerical operations.
Code Type : The type of code
Code Difficulty : Advanced
def random_color_detection(image_path):
import cv2
import numpy as np
# Load the image
image = cv2.imread(image_path)
if image is None:
print("Image not found or path is incorrect")
return None
# 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, 50, 50])
upper_red = np.array([10, 255, 255])
mask1 = cv2.inRange(hsv_image, lower_red, upper_red)
lower_red = np.array([170, 50, 50])
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 of red color
contours, _ = cv2.findContours(red_mask, cv2.RETR_EXTERNAL, cv2.CHAIN_APPROX_SIMPLE)
# Draw contours on the original image
red_color_image = cv2.drawContours(image, contours, -1, (0, 0, 255), 2)
return red_color_image