Numpy使二进制矩阵轮廓连续并用1s填充

问题描述

我这里有一个包含 0 和 1 的文件https://easyupload.io/wvoryj。 如何用 1s 填充这些结构的形状?我认为 binary_fill_holes 不起作用,因为轮廓不连续。

plot showing structures

import numpy as np
import matplotlib.pyplot as plt
from scipy import ndimage

mask = np.loadtxt('mask.txt',dtype=int)
mask = ndimage.binary_fill_holes(mask).astype(int)

fig,ax = plt.subplots()
plt.imshow(mask)
plt.show()

解决方法

这将是我的方法:

  • 首先用 2D 卷积填补空白
  • 对所有行运行 cumsum 以填充轮廓
  • 除以行的最后(或最高)数字
  • 将大于 1 的所有内容都设置回 1

希望有帮助

import numpy as np
import matplotlib.pyplot as plt
from scipy.signal import convolve2d

mask = np.loadtxt('mask.txt',dtype=int)

# run a convolution over the mask to fill out the empty spaces
conv_mat = np.array(3*[[0,1,0]])
mask_continuous = convolve2d(mask,conv_mat)

# add up all numbers from left to right...
# ...and divide by the last value of the row
mask_filled = np.array([np.cumsum(i) / np.cumsum(i)[-1] for i in mask_continuous])

# reset everything larger than 1 to 1
mask_filled[mask_filled>1] = 1

fig,ax = plt.subplots()
plt.imshow(mask_filled)
plt.show()