
I хотите использовать красный прямоугольник для обрезки вдоль контурной линии:

Я попытался использовать следующий скрипт для выполнения задачи, но результаты оказались не такими, как я ожидал:
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.")
Подробнее здесь: https://stackoverflow.com/questions/789 ... -by-opencv