以下是一个 Python 程序,用于统计 RGB 图像中所有轮廓的大小,并计算所有轮廓的平均值,然后根据该平均值去除原图中轮廓小于平均值的图像部分,只保留轮廓大于平均值的部分。

import cv2
import numpy as np

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

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

# 阈值化处理
_, threshold = cv2.threshold(gray, 127, 255, cv2.THRESH_BINARY)

# 查找轮廓
contours, _ = cv2.findContours(threshold, cv2.RETR_EXTERNAL, cv2.CHAIN_APPROX_SIMPLE)

# 统计轮廓大小并计算平均值
total_size = 0
for contour in contours:
    total_size += cv2.contourArea(contour)
average_size = total_size / len(contours)

# 去除小于平均值的轮廓部分
result = np.zeros_like(image)
for contour in contours:
    if cv2.contourArea(contour) >= average_size:
        cv2.drawContours(result, [contour], -1, (255, 255, 255), cv2.FILLED)

# 显示结果图像
cv2.imshow('Original Image', image)
cv2.imshow('Result', result)
cv2.waitKey(0)
cv2.destroyAllWindows()

请将程序中的'image.jpg'替换为你要处理的图像文件的路径。程序将显示原始图像和处理后的结果图像。

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

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

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