python-opencv去除小面积区域/孔洞填充(二值图像)

x33g5p2x  于2021-12-06 转载在 Python  
字(1.1k)|赞(0)|评价(0)|浏览(743)

上图左为原始图像,右图为填充后的图像。

因为左边的图片存在很多噪声点,直接根据阈值去填充会存在问题,所以我就先对图片进行了一次二值化处理,然后调用了opencv的fillPoly函数完成孔洞的填充。

import cv2
import os
import numpy as np

imaPath = r"E:\hand\label"
output = r"E:\hand\output"

imaList = os.listdir(imaPath)
for files in imaList:
    path_ima = os.path.join(imaPath, files)
    path_processed = os.path.join(output, files)
    img = cv2.imread(path_ima, 0)

    mask = np.zeros_like(img)
    print(np.shape(img))

    # 先利用二值化去除图片噪声
    ret, img = cv2.threshold(img, 127, 255, cv2.THRESH_BINARY)

    contours, _ = cv2.findContours(img, cv2.RETR_TREE, cv2.CHAIN_APPROX_SIMPLE)
    n = len(contours)  # 轮廓的个数
    cv_contours = []
    for contour in contours:
        area = cv2.contourArea(contour)
        if area <= 80000:
            cv_contours.append(contour)
            # x, y, w, h = cv2.boundingRect(contour)
            # img[y:y + h, x:x + w] = 255
        else:
            continue
            
    cv2.fillPoly(img, cv_contours, (255, 255, 255))
    cv2.imwrite(path_processed, img)

备注:
opencv-python的各种滤波接口函数:

  1. 均值滤波
img = cv2.blur(img,(3,5))#模板大小3*5
  1. 方框滤波(比均值滤波多一个参数)
#normalize为True时与blur相同
#normalize为Flase是可能发生越界
img =cv2.boxFilter(img,-1,(3,3),normalize=True)
  1. 高斯滤波
img = cv2.GaussianBlur(img,(21,21),1)
  1. 中值滤波
img = cv2.medianBlur(img,5)
  1. 双边滤波
img = cv2.bilateralFilter(img,9,75,75)

相关文章