i have an image with different geometrical figures with different colors on white…
- User
i have an image with different geometrical figures with different colors on white background. write a python script that extracts those objects based on color and saves them as different images
- Assistant
Sure! Here's a Python script that extracts objects based on color from an image and saves them as separate images.
import cv2 import numpy as np def extract_objects(image_path): # Load the image image = cv2.imread(image_path) # Convert the image to HSV color space hsv = cv2.cvtColor(image, cv2.COLOR_BGR2HSV) # Define color ranges for different objects color_ranges = { 'red': ([0, 50, 50], [10, 255, 255]), 'green': ([50, 50, 50], [70, 255, 255]), 'blue': ([110, 50, 50], [130, 255, 255]), } # Extract objects based on color for color, (lower, upper) in color_ranges.items(): lower = np.array(lower, dtype=np.uint8) upper = np.array(upper, dtype=np.uint8) mask = cv2.inRange(hsv, lower, upper) contours, _ = cv2.findContours(mask, cv2.RETR_EXTERNAL, cv2.CHAIN_APPROX_SIMPLE) # Save extracted objects as separate images for i, contour in enumerate(contours): x, y, w, h = cv2.boundingRect(contour) object_image = image[y:y+h, x:x+w] cv2.imwrite(f'{color}_object_{i+1}.png', object_image) print('Objects extracted and saved as separate images.') # Provide the path to the image image_path = 'path_to_your_image.png' # Call the function to extract objects based on color extract_objects(image_path)Make sure to replace
'path_to_your_image.png'with the actual path to your image file. The script extracts three different colors, red, green, and blue, by specifying their respective color ranges in thecolor_rangesdictionary.When you run the script, it will extract objects of each color, save them as separate images with appropriate names (
color_object_{number}.png), and print a message indicating that the objects have been extracted and saved.