To accomplish the task of detecting and saving black objects on a white background as separate images or combining overlapping ones into a single image, we can use Python and the OpenCV library. Here's an outline of how you could approach this:
- Import the required libraries:
import cv2
import numpy as np
- Read the image with black objects on a white background:
image = cv2.imread('path_to_image.png') # Replace 'path_to_image.png' with the actual path to your image
- Convert the image to grayscale and apply thresholding to obtain a binary image:
gray = cv2.cvtColor(image, cv2.COLOR_BGR2GRAY)
_, binary = cv2.threshold(gray, 10, 255, cv2.THRESH_BINARY)
Note: Modify the threshold value (10 in this example) to suit your image's intensity levels.
- Find contours of the objects:
contours, _ = cv2.findContours(binary, cv2.RETR_EXTERNAL, cv2.CHAIN_APPROX_SIMPLE)
- Iterate through the contours and create separate images for each object:
for i, contour in enumerate(contours):
# Create a bounding rectangle around the object
x, y, w, h = cv2.boundingRect(contour)
# Crop the object from the original image
object_image = image[y:y+h, x:x+w]
# Save the cropped image
cv2.imwrite(f'object_{i+1}.png', object_image)
- Check if any objects overlap vertically and combine them:
combined_images = []
previous_bottom = 0
for i, contour in enumerate(sorted(contours, key=lambda cnt: cv2.boundingRect(cnt)[1])):
x, y, w, h = cv2.boundingRect(contour)
if y > previous_bottom:
# No overlap, save previous combined image and start a new one
if combined_images:
combined_image = np.concatenate(combined_images, axis=0)
cv2.imwrite(f'combined_{i}.png', combined_image)
combined_images = [image[y:y+h, x:x+w]]
else:
# Overlapping, append to current combined image
combined_images.append(image[y:y+h, x:x+w])
previous_bottom = y + h
# Save the last combined image
if combined_images:
combined_image = np.concatenate(combined_images, axis=0)
cv2.imwrite(f'combined_{len(contours)}.png', combined_image)
Make sure to replace 'path_to_image.png' with the actual path to your image file. The script will save each object as a separate image with filenames like object_1.png, object_2.png, etc. If there are overlapping objects vertically, they will be combined and saved as combined_1.png, combined_2.png, etc.
Remember to install the OpenCV library (pip install opencv-python) if you haven't already.