alex_bn_lee

导航

【644】二值图去掉面积小的部分 cv2.threshold

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

  具体实现:

1. 读取并显示原始图像

import cv2
import os 
import numpy as np 
from PIL import Image 

img_path = "seg_smooth.png"
img = cv2.imread(img_path, 0)
mask = np.zeros_like(img)

display(Image.fromarray(img)) 

 

 

2. 设置阈值获取轮廓线集合

ret, img = cv2.threshold(img, 127, 255, cv2.THRESH_BINARY)
contours, _ = cv2.findContours(img, cv2.RETR_TREE, cv2.CHAIN_APPROX_SIMPLE)
n = len(contours)

img_line = np.zeros_like(img)

cv2.polylines(img_line, contours, isClosed=True, color=(255,255,255), thickness=2)  
display(Image.fromarray(img_line))

 

 

3. 剔除掉面积较小的,保留面积较大的,并填充颜色

cv_contours = [] 

for contour in contours: 
    area = cv2.contourArea(contour)
    if area >= 300:
        cv_contours.append(contour)

img_poly = np.zeros_like(img)
cv2.fillPoly(img_poly, cv_contours, (255,255,255))
display(Image.fromarray(img_poly)) 

 

 

posted on 2021-08-12 17:20  McDelfino  阅读(1446)  评论(0编辑  收藏  举报