I'm looking for a way to fill a numpy matrix in a diamond shape.
I know you can fill one in a circle shape like this:
radius = 1
y,x = np.ogrid[-radius: radius + 1, -radius: radius + 1]
matrix = x**2 + y**2 <= radius**2
Which give me this correct output:
[[False True False]
[ True True True]
[False True False]]
But obviously a circle is not a diamond and as the radius increases, the shape stops looking like a diamond.
Diamond mask with given matrix-length
Here's one leveraging broadcasting -
def diamond(n):
a = np.arange(n)
b = np.minimum(a,a[::-1])
return (b[:,None]+b)>=(n-1)//2
Sample runs -
In [73]: diamond(3)
Out[73]:
array([[False, True, False],
[ True, True, True],
[False, True, False]])
In [74]: diamond(4)
Out[74]:
array([[False, True, True, False],
[ True, True, True, True],
[ True, True, True, True],
[False, True, True, False]])
In [75]: diamond(5)
Out[75]:
array([[False, False, True, False, False],
[False, True, True, True, False],
[ True, True, True, True, True],
[False, True, True, True, False],
[False, False, True, False, False]])
Diamond mask with given radius
For given radius, simplifies further -
def diamond2(r):
b = np.r_[:r,r:-1:-1]
return (b[:,None]+b)>=r
And that could be further simplified to a one-liner -
def diamond2(r):
return np.add.outer(*[np.r_[:r,r:-1:-1]]*2)>=r
Sample runs -
In [19]: diamond2(1)
Out[19]:
array([[False, True, False],
[ True, True, True],
[False, True, False]])
In [20]: diamond2(2)
Out[20]:
array([[False, False, True, False, False],
[False, True, True, True, False],
[ True, True, True, True, True],
[False, True, True, True, False],
[False, False, True, False, False]])
In [21]: diamond2(3)
Out[21]:
array([[False, False, False, True, False, False, False],
[False, False, True, True, True, False, False],
[False, True, True, True, True, True, False],
[ True, True, True, True, True, True, True],
[False, True, True, True, True, True, False],
[False, False, True, True, True, False, False],
[False, False, False, True, False, False, False]])
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With