上图左为原始图像,右图为填充后的图像。
因为左边的图片存在很多噪声点,直接根据阈值去填充会存在问题,所以我就先对图片进行了一次二值化处理,然后调用了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的各种滤波接口函数:
img = cv2.blur(img,(3,5))#模板大小3*5
#normalize为True时与blur相同
#normalize为Flase是可能发生越界
img =cv2.boxFilter(img,-1,(3,3),normalize=True)
img = cv2.GaussianBlur(img,(21,21),1)
img = cv2.medianBlur(img,5)
img = cv2.bilateralFilter(img,9,75,75)
版权说明 : 本文为转载文章, 版权归原作者所有 版权申明
原文链接 : https://blog.csdn.net/luanfenlian0992/article/details/110529737
内容来源于网络,如有侵权,请联系作者删除!