以下是一个Python程序示例,用于根据RGB图像中所有轮廓大小的平均值,筛选原图中轮廓大于平均值的图像部分,并根据筛选后轮廓坐标,提取原图中位于轮廓内的图像并保存。

import cv2
import numpy as np

def extract_contour_regions(image_path):
    # 读取图像
    image = cv2.imread(image_path)
    
    # 转换为灰度图像
    gray = cv2.cvtColor(image, cv2.COLOR_BGR2GRAY)
    
    # 使用Canny边缘检测算法提取轮廓
    edges = cv2.Canny(gray, 50, 150)
    
    # 查找轮廓
    contours, _ = cv2.findContours(edges.copy(), cv2.RETR_EXTERNAL, cv2.CHAIN_APPROX_SIMPLE)
    
    # 计算所有轮廓大小的平均值
    contour_sizes = [cv2.contourArea(contour) for contour in contours]
    average_size = np.mean(contour_sizes)
    
    # 筛选大于平均值的轮廓
    large_contours = [contour for contour in contours if cv2.contourArea(contour) > average_size]
    
    # 创建一个掩膜图像
    mask = np.zeros_like(gray)
    
    # 在掩膜图像上绘制轮廓
    cv2.drawContours(mask, large_contours, -1, (255), thickness=cv2.FILLED)
    
    # 提取图像中位于轮廓内的部分
    result = cv2.bitwise_and(image, image, mask=mask)
    
    # 保存提取的图像
    cv2.imwrite('extracted_regions.jpg', result)

# 测试程序
image_path = 'input_image.jpg'
extract_contour_regions(image_path)

请注意,此程序假定您已经将OpenCV库安装在您的Python环境中。您可以使用pip install opencv-python命令安装OpenCV库。另外,您需要将image_path变量更改为实际的图像文件路径。程序将提取的图像保存为extracted_regions.jpg文件。

Python OpenCV: 使用轮廓大小筛选图像并提取区域

原文地址: https://www.cveoy.top/t/topic/qiKl 著作权归作者所有。请勿转载和采集!

免费AI点我,无需注册和登录