以下是一个Python程序示例,用于遍历图像中的所有轮廓,并将轮廓小于平均值的部分去除,只保留轮廓大于平均值的图像部分并保存为新图。

import cv2
import numpy as np

# 读取图像
image = cv2.imread('image.jpg')

# 转换为灰度图像
gray = cv2.cvtColor(image, cv2.COLOR_BGR2GRAY)

# 二值化处理
ret, thresh = cv2.threshold(gray, 127, 255, cv2.THRESH_BINARY)

# 查找轮廓
contours, hierarchy = cv2.findContours(thresh, cv2.RETR_EXTERNAL, cv2.CHAIN_APPROX_SIMPLE)

# 计算轮廓面积
contour_areas = [cv2.contourArea(contour) for contour in contours]

# 计算轮廓平均值
average_area = np.mean(contour_areas)

# 创建空白图像
result = np.zeros_like(image)

# 保留大于平均值的轮廓部分
for contour in contours:
    if cv2.contourArea(contour) > average_area:
        cv2.drawContours(result, [contour], -1, (255, 255, 255), cv2.FILLED)

# 保存新图像
cv2.imwrite('result.jpg', result)

请确保安装了OpenCV库,并将图像文件命名为'image.jpg',程序将生成一个名为'result.jpg'的新图像文件,其中只包含大于平均值的轮廓部分。

Python图像处理:去除小轮廓,保留大轮廓图像

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

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