简体   繁体   中英

Numpy make binary matrix outline continuous and fill it with 1s

I have a file containing 0 and 1s here: https://easyupload.io/wvoryj . How can I fill the shape of these structures with 1s? I think binary_fill_holes is not working because the outline is not continuous.

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()

This would be my approach:

  • First fill up the gaps with a 2D convolution
  • run a cumsum over all rows to fill the outlines
  • divide by the last (or highest) number of the row
  • set everything larger than 1 back to 1

I hope that helped

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()

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM