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

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

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

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

  1. import cv2
  2. import os
  3. import numpy as np
  4. imaPath = r"E:\hand\label"
  5. output = r"E:\hand\output"
  6. imaList = os.listdir(imaPath)
  7. for files in imaList:
  8. path_ima = os.path.join(imaPath, files)
  9. path_processed = os.path.join(output, files)
  10. img = cv2.imread(path_ima, 0)
  11. mask = np.zeros_like(img)
  12. print(np.shape(img))
  13. # 先利用二值化去除图片噪声
  14. ret, img = cv2.threshold(img, 127, 255, cv2.THRESH_BINARY)
  15. contours, _ = cv2.findContours(img, cv2.RETR_TREE, cv2.CHAIN_APPROX_SIMPLE)
  16. n = len(contours) # 轮廓的个数
  17. cv_contours = []
  18. for contour in contours:
  19. area = cv2.contourArea(contour)
  20. if area <= 80000:
  21. cv_contours.append(contour)
  22. # x, y, w, h = cv2.boundingRect(contour)
  23. # img[y:y + h, x:x + w] = 255
  24. else:
  25. continue
  26. cv2.fillPoly(img, cv_contours, (255, 255, 255))
  27. cv2.imwrite(path_processed, img)

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

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

相关文章