Home > database >  Python: Fill out edges of binary array
Python: Fill out edges of binary array

Time:07-16

I'm using the following code to generate an array based on coordinates of edges:

verts = np.array(list(itertools.product((0,2), (0,2))))
arr = np.zeros((5, 5))
arr[tuple(verts.T)] = 1
plt.imshow(arr)

which gives me

array

or, as a numeric array:

[[1., 0., 1., 0., 0.],
       [0., 0., 0., 0., 0.],
       [1., 0., 1., 0., 0.],
       [0., 0., 0., 0., 0.],
       [0., 0., 0., 0., 0.]]

Now, I would like to fill out the spaces in between the corners (ie. yellow squares):

filledout

so that I get the following array:

[[1., 1., 1., 0., 0.],
       [1., 1., 1., 0., 0.],
       [1., 1., 1., 0., 0.],
       [0., 0., 0., 0., 0.],
       [0., 0., 0., 0., 0.]]

CodePudding user response:

Replace (0,2) using range(0,3) (3 as ranges are inclusive-exclusive) that is

import itertools
import numpy as np
verts = np.array(list(itertools.product(range(0,3), range(0,3))))
arr = np.zeros((5, 5))
arr[tuple(verts.T)] = 1
print(arr)

output

[[1. 1. 1. 0. 0.]
 [1. 1. 1. 0. 0.]
 [1. 1. 1. 0. 0.]
 [0. 0. 0. 0. 0.]
 [0. 0. 0. 0. 0.]]
  • Related