To detect if a specific region of a picture is a certain solid color using OpenCV, you can follow these general steps:
Read the Image:
Use OpenCV to read the image
import cv2 image = cv2.imread('your_image.jpg')
Define the Region of Interest (ROI):
Define the specific region of the image where you want to check for the solid color.
# Define the coordinates of the region (x, y, width, height) roi_coordinates = (x, y, width, height) roi = image[y:y+height, x:x+width]
Convert the ROI to HSV color space:
Convert the ROI to the HSV (Hue, Saturation, Value) color space for better color representation.
roi_hsv = cv2.cvtColor(roi, cv2.COLOR_BGR2HSV)
Define the Range for the Solid Color:
Specify the range of HSV values that correspond to the solid color you are looking for.
# Example: Define a range for the color red lower_red = np.array([0, 100, 100]) upper_red = np.array([10, 255, 255])
Create a Mask:
Create a binary mask based on the specified color range.
mask = cv2.inRange(roi_hsv, lower_red, upper_red)
Check if the Region is the Solid Color:
Check if the majority of pixels in the mask belong to the solid color.
percentage_solid_color = (cv2.countNonZero(mask) / (width * height)) * 100 # Set a threshold percentage for considering it as a solid color threshold_percentage = 90 if percentage_solid_color >= threshold_percentage: print("The region is a solid color.") else: print("The region is not a solid color.")
import cv2 import numpy as np def is_solid_color_region(image_path, roi_coordinates, color_lower, color_upper, threshold_percentage=90): # Step 1: Read the image image = cv2.imread(image_path) # Step 2: Define the Region of Interest (ROI) x, y, width, height = roi_coordinates roi = image[y:y+height, x:x+width] # Step 3: Convert the ROI to HSV color space roi_hsv = cv2.cvtColor(roi, cv2.COLOR_BGR2HSV) # Step 4: Define the Range for the Solid Color lower_color = np.array(color_lower) upper_color = np.array(color_upper) # Step 5: Create a Mask mask = cv2.inRange(roi_hsv, lower_color, upper_color) # Step 6: Check if the Region is the Solid Color percentage_solid_color = (cv2.countNonZero(mask) / (width * height)) * 100 # Display the result cv2.imshow('Original Image', image) cv2.imshow('ROI', roi) cv2.imshow('Mask', mask) cv2.waitKey(0) cv2.destroyAllWindows() # Check if the percentage of solid color exceeds the threshold return percentage_solid_color >= threshold_percentage # Example Usage image_path = 'your_image.jpg' roi_coordinates = (100, 100, 50, 50) # Example coordinates (x, y, width, height) color_lower = [0, 100, 100] # Example lower HSV values for the color color_upper = [10, 255, 255] # Example upper HSV values for the color result = is_solid_color_region(image_path, roi_coordinates, color_lower, color_upper) if result: print("The region is a solid color.") else: print("The region is not a solid color.")