I have an image with drawn contour. How to crop the image along the drawn contour line? This is the picture with contour drawn on it
I want to crop along the contour line:
I tried to use the following script to perform the task, but the results are not what I expected:
import cv2
import numpy as np
import os
# Load the image
image_path = 'cropped_drawcontourtest.png' # Change to your image path
image = cv2.imread(image_path)
# Convert to grayscale
gray = cv2.cvtColor(image, cv2.COLOR_BGR2GRAY)
# Apply thresholding to get a binary image
_, binary = cv2.threshold(gray, 127, 255, cv2.THRESH_BINARY_INV)
# Find contours
contours, _ = cv2.findContours(binary, cv2.RETR_EXTERNAL, cv2.CHAIN_APPROX_SIMPLE)
# Create a directory for cropped images if it doesn't exist
output_dir = 'cropped_images'
os.makedirs(output_dir, exist_ok=True)
# Crop along the contours and save
for i, contour in enumerate(contours):
# Create a mask for the current contour
mask = np.zeros_like(image)
cv2.drawContours(mask, [contour], -1, (255, 255, 255), thickness=cv2.FILLED)
# Apply the mask to the original image
cropped = cv2.bitwise_and(image, mask)
# Save the cropped image
cv2.imwrite(os.path.join(output_dir, f'cropped_{i}.png'), cropped)
print("Cropping complete! Check the 'cropped_images' directory.")
use cv2.boundingRect()
to get the coordinates of the line, and then use those coordinates to crop the image.
x, y, w, h = cv2.boundingRect(contour)
1