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 Lab color space, detects areas within a specific color range in the Lab space, and draws the detected color areas on the original image.
Technology Stack : opencv-python, numpy, skimage
Code Type : Image processing
Code Difficulty : Intermediate
def random_color_detection(image_path):
import cv2
import numpy as np
from skimage.color import rgb2lab
# Read the image
image = cv2.imread(image_path)
# Convert the image to Lab color space
lab_image = rgb2lab(image)
# Define the range for the color we want to detect
lower_color = np.array([20, 100, 100])
upper_color = np.array([30, 255, 255])
# Create a mask for the color range
mask = cv2.inRange(lab_image, lower_color, upper_color)
# Find contours in the mask
contours, _ = cv2.findContours(mask, cv2.RETR_EXTERNAL, cv2.CHAIN_APPROX_SIMPLE)
# Draw contours on the original image
cv2.drawContours(image, contours, -1, (0, 255, 0), 3)
# Display the image
cv2.imshow('Detected Color', image)
cv2.waitKey(0)
cv2.destroyAllWindows()
return image