import cv2
import os
def crop_images(input_path, output_dir):
image = cv2.imread(input_path)
gray = cv2.cvtColor(image, cv2.COLOR_BGR2GRAY)
blur = cv2.GaussianBlur(gray, (5, 5), 0)
_, thresh = cv2.threshold(blur, 0, 255, cv2.THRESH_BINARY_INV + cv2.THRESH_OTSU)
kernel = cv2.getStructuringElement(cv2.MORPH_RECT, (11, 11))
dilate = cv2.dilate(thresh, kernel, iterations=1)
cnts, _ = cv2.findContours(dilate, cv2.RETR_EXTERNAL, cv2.CHAIN_APPROX_SIMPLE)
image_with_rectangles = image.copy()
image_number = 0
min_roi_size = 7000
max_roi_size = 30000
for c in cnts:
x, y, w, h = cv2.boundingRect(c)
if max_roi_size > w * h > min_roi_size:
cv2.rectangle(image_with_rectangles, (x, y), (x + w, y + h), (0, 255, 0), 2)
ROI = image[y:y + h, x:x + w]
output_path = os.path.join(output_dir, f"ROI_{image_number}.jpg")
cv2.imwrite(output_path, ROI)
image_number += 1
cv2.imwrite(("image_with_rectangles.jpg"), image_with_rectangles)
原始图像的左下部分经常被忽略,缺少一些细节,但我无法调整它。