我有一张带有绘制轮廓的图像。如何沿着绘制的轮廓线裁剪图像?参考上传的图片
我尝试使用以下脚本来执行任务,但结果不是我所期望的:
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.")
使用
cv2.boundingRect()
获取线条的坐标,然后使用这些坐标来裁剪图像。
x, y, w, h = cv2.boundingRect(contour)