i have a bunch of dark object on white background. write a python script that cuts off…
- User
i have a bunch of dark object on white background. write a python script that cuts off each one of them and saves as different images. dont cut them right from pixel to pixel, leave a little white space around each object
- Assistant
To achieve this task, you can use the OpenCV library in Python. Here's an example script that separates dark objects from a white background, crops them with a little white space around each object, and saves them as different images:
import cv2 import numpy as np def crop_objects(image_path, output_dir): # Load the image image = cv2.imread(image_path) # Convert the image to grayscale gray = cv2.cvtColor(image, cv2.COLOR_BGR2GRAY) # Apply thresholding to separate dark objects from the white background _, threshold = cv2.threshold(gray, 50, 255, cv2.THRESH_BINARY_INV) # Find contours of objects contours, _ = cv2.findContours(threshold, cv2.RETR_EXTERNAL, cv2.CHAIN_APPROX_SIMPLE) # Create a directory for saving the cropped images os.makedirs(output_dir, exist_ok=True) # Extract and save each object as a separate image for i, contour in enumerate(contours): # Get the bounding rectangle coordinates x, y, w, h = cv2.boundingRect(contour) # Add some white space around the object padding = 10 x -= padding y -= padding w += padding * 2 h += padding * 2 # Crop the object from the original image cropped = image[y:y+h, x:x+w] # Save the cropped image output_path = os.path.join(output_dir, f"object{i+1}.png") cv2.imwrite(output_path, cropped) # Provide the path to your input image and output directory image_path = "path/to/input/image.png" output_dir = "path/to/output/directory" crop_objects(image_path, output_dir)