大致流程:
- 新建一个全是一的掩膜;
- 减去多边形的边界,得到两个块状物;
- 判断块状物是否在边界,在边界的块状物去掉,得到填充后的效果
def segmentation_pipe(img ,cfg):
gray = cv.cvtColor(img, cv.COLOR_BGR2GRAY)
ret, thresh = cv.threshold(gray, 240, 255, cv.THRESH_BINARY)
thresh[thresh > 0] = 1
out = dilation(thresh, square(20))
out = erosion(out, square(10))
# remove small objects
labels = ndi.label(out, output=np.uint32)[0]
unique, counts = np.unique(labels, return_counts=True)
for (k, v) in dict(zip(unique, counts)).items():
if v < cfg.remove_area:
out[labels == k] = 0
# fill the hole
out[out > 0] = 1
temp = np.ones_like(out) - out
labels = ndi.label(temp, output=np.uint32)[0]
unique, counts = np.unique(labels, return_counts=True)
for (k, v) in dict(zip(unique, counts)).items():
temp_ = np.zeros_like(out)
temp_[labels == k] = 1
if temp_[0, 0] == 1:
temp[labels == k] = 0
return temp