You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何用Python OpenCV稳定检测图像中的灰色矩形框

灰色矩形框稳定检测问题求助

本人刚接触Python与OpenCV,对相关技术了解尚浅。目前尝试检测一批图像中的灰色矩形框,现有代码整体效果尚可,但仍存在检测失效的情况。希望有经验的开发者能协助实现对灰色矩形框的稳定检测,同时请教当前方案是否为最优解,有无更适配CPU环境的替代方案。

现有代码

import cv2
import matplotlib.pyplot as plt
import os

def process_and_save_images(input_dir, save_subdir='processed_7'):
    # Ensure the output directory exists
    save_dir = os.path.join(input_dir, save_subdir)
    if not os.path.exists(save_dir):
        os.makedirs(save_dir)

    # List all files in the input directory
    files = [f for f in os.listdir(input_dir) if os.path.isfile(os.path.join(input_dir, f))]

    # Filter out only the PNG files (you can add other formats if needed)
    image_paths = [os.path.join(input_dir, f) for f in files if f.lower().endswith('.png')]

    for image_path in image_paths:
        # Load image, grayscale, adaptive threshold
        image = cv2.imread(image_path)
        
        # Crop the bottom third of the image
        height, width, _ = image.shape
        cropped = image[int(2*height/3):, :]
        result_cropped = cropped.copy()

        gray = cv2.cvtColor(cropped, cv2.COLOR_BGR2GRAY)
        thresh = cv2.adaptiveThreshold(gray, 255, cv2.ADAPTIVE_THRESH_GAUSSIAN_C, cv2.THRESH_BINARY_INV, 51, 9)

        # Fill rectangular contours
        cnts = cv2.findContours(thresh, cv2.RETR_EXTERNAL, cv2.CHAIN_APPROX_SIMPLE)
        cnts = cnts[0] if len(cnts) == 2 else cnts[1]
        for c in cnts:
            cv2.drawContours(thresh, [c], -1, (255,255,255), -1)

        # Morph open
        kernel = cv2.getStructuringElement(cv2.MORPH_RECT, (9,9))
        opening = cv2.morphologyEx(thresh, cv2.MORPH_OPEN, kernel, iterations=2)

        # Closing operation
        closing = cv2.morphologyEx(opening, cv2.MORPH_CLOSE, kernel, iterations=2)

        # Find the contour with the largest area
        cnts = cv2.findContours(closing, cv2.RETR_EXTERNAL, cv2.CHAIN_APPROX_SIMPLE)
        cnts = cnts[0] if len(cnts) == 2 else cnts[1]

        
        if cnts:
            largest_contour = max(cnts, key=cv2.contourArea)
            
            # Draw the bounding rectangle of the largest contour
            x, y, w, h = cv2.boundingRect(largest_contour)
            cv2.rectangle(result_cropped, (x, y), (x + w, y + h), (36, 255, 12), 3)
        else:
            print(f"No contours found in {image_path}. Skipping...")

        # Use matplotlib to display the images and save them
        plt.figure(figsize=(20, 10))

        plt.subplot(1, 4, 1)
        plt.imshow(thresh, cmap='gray')
        plt.title('Thresholded Image')

        plt.subplot(1, 4, 2)
        plt.imshow(opening, cmap='gray')
        plt.title('Morphological Opening')

        plt.subplot(1, 4, 3)
        plt.imshow(closing, cmap='gray')
        plt.title('Morphological Closing')        

        plt.subplot(1, 4, 4)
        plt.imshow(cv2.cvtColor(result_cropped, cv2.COLOR_BGR2RGB))
        plt.title('Image with Largest Rectangle')

        plt.tight_layout()

        # Save the figure
        filename = os.path.basename(image_path).replace('.png', '_processed.png')
        output_path = os.path.join(save_dir, filename)
        plt.savefig(output_path)
        plt.close()  # Close the current figure to release memory

    print("Processing and saving completed.")

# Example usage:
process_and_save_images('./temporal')

相关图像说明

  • 代码处理结果图:展示阈值化图像、形态学开运算图像、形态学闭运算图像及最终检测结果的对比组合图
  • 原始图像:一批包含待检测灰色矩形框的PNG格式原图
  • 检测失效案例:三张未能正确识别出目标灰色矩形框的图像

内容的提问来源于stack exchange,提问作者Salexes

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.08 15:14:57