我需要捕获图像中的对象,但我缺少需要查找的对象

问题描述 投票:0回答:1
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)

原始图像的左下部分经常被忽略,缺少一些细节,但我无法调整它。

python opencv computer-vision object-detection roi
1个回答
0
投票

你不需要

max_roi_size
,没有任何其他物体比你感兴趣的物体更大,或者至少应该非常大。因此,快速解决方法是将 max_roi_size 设置为更大的数字,假设为 40000:
max_roi_size = 40000
enter image description here

© www.soinside.com 2019 - 2024. All rights reserved.