Python代码,用于在从左到右方向读取图像时选择图像的第一个封闭轮

问题描述 投票:0回答:1

input image

在这里,我使用了这样的字符图像。当尝试仅选择输入图像的第一个闭合圆形部分,同时使用 open_cv 从左到右扫描它时,我得到了字符的整个外边缘部分。 如何只获得投资回报率?

import cv2
import numpy as np
import matplotlib.pyplot as plt

def find_closed_round_areas(image_path):
    # Load the image
    image = cv2.imread(image_path, cv2.IMREAD_GRAYSCALE)

    # Apply binary thresholding
    _, thresh = cv2.threshold(image, 127, 255, cv2.THRESH_BINARY_INV)

    # Find contours
    contours, _ = cv2.findContours(thresh, cv2.RETR_EXTERNAL, cv2.CHAIN_APPROX_SIMPLE)

    # Create a color version of the original image
    color_image = cv2.cvtColor(image, cv2.COLOR_GRAY2BGR)

    # Filter and highlight closed round contours
    highlighted_image = color_image.copy()
    for contour in contours:
        if cv2.contourArea(contour) > 100:  # Filter out small contours
            perimeter = cv2.arcLength(contour, True)
            circularity = 4 * np.pi * cv2.contourArea(contour) / (perimeter ** 2)
            if circularity > 0.7:  # Filter based on circularity
                cv2.drawContours(highlighted_image, [contour], -1, (0, 255, 0), thickness=2)  # Green color in BGR

    # Display the original and highlighted images
    plt.figure(figsize=(10, 5))
    plt.subplot(1, 2, 1)
    plt.title('Original Image')
    plt.imshow(cv2.cvtColor(color_image, cv2.COLOR_BGR2RGB))
    plt.subplot(1, 2, 2)
    plt.title('Highlighted Closed Round Areas')
    plt.imshow(cv2.cvtColor(highlighted_image, cv2.COLOR_BGR2RGB))
    plt.show()

# Path to the image
image_path = '/mnt/data/ROI_65.png'

# Find and highlight the closed round areas
find_closed_round_areas(image_path)
  
This is the code....But it select the outer box of the picture not the ROI    
python opencv contour roi
1个回答
0
投票

因为外边缘是算法返回的第一个闭环,因为它是包含所有其他闭环的循环。

更改自

 contours, _ = cv2.findContours(thresh, cv2.RETR_EXTERNAL, cv2.CHAIN_APPROX_SIMPLE)

contours, hierarchy = cv2.findContours(thresh, cv2.RETR_LIST, cv2.CHAIN_APPROX_SIMPLE)

然后您可以过滤掉太大的循环

image_area = image.shape[0] * image.shape1

# Filter out contours that are larger than 95% of the image area
filtered_contours = [contour for contour in contours if cv2.contourArea(contour) <= 0.95 * image_area]

来自文档

RETR_EXTERNAL Python:cv.RETR_EXTERNAL

仅检索最外轮廓。它设置 对于所有轮廓,hierarchy[i][2]=hierarchy[i][3]=-1。 RETR_列表 Python:cv.RETR_LIST

检索所有轮廓而不建立任何层次结构 关系

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