I have an array like this:
>>> np.ones((8,8)) array([[ 1., 1., 1., 1., 1., 1., 1., 1.], [ 1., 1., 1., 1., 1., 1., 1., 1.], [ 1., 1., 1., 1., 1., 1., 1., 1.], [ 1., 1., 1., 1., 1., 1., 1., 1.], [ 1., 1., 1., 1., 1., 1., 1., 1.], [ 1., 1., 1., 1., 1., 1., 1., 1.], [ 1., 1., 1., 1., 1., 1., 1., 1.], [ 1., 1., 1., 1., 1., 1., 1., 1.]])
I'm creating a disc shaped mask with radius 3 thus:
y,x = np.ogrid[-3: 3+1, -3: 3+1] mask = x**2+y**2 <= 3**2
This gives:
>> mask array([[False, False, False, True, False, False, False], [False, True, True, True, True, True, False], [False, True, True, True, True, True, False], [ True, True, True, True, True, True, True], [False, True, True, True, True, True, False], [False, True, True, True, True, True, False], [False, False, False, True, False, False, False]], dtype=bool)
Now, I want to be able to apply this mask to my array, using any element as a center point. So, for example, with center point at (1,1), I want to get an array like:
>>> new_arr array([[ True, True, True, True, 1., 1., 1., 1.], [ True, True, True, True, True, 1., 1., 1.], [ True, True, True, True, 1., 1., 1., 1.], [ True, True, True, True, 1., 1., 1., 1.], [ 1., True, 1., 1., 1., 1., 1., 1.], [ 1., 1., 1., 1., 1., 1., 1., 1.], [ 1., 1., 1., 1., 1., 1., 1., 1.], [ 1., 1., 1., 1., 1., 1., 1., 1.]])
Is there an easy way to apply this mask?
Edit: I shouldn't have mixed booleans and floats - it was misleading.
>>> new_arr array([[ 255., 255., 255., 255., 1., 1., 1., 1.], [ 255., 255., 255., 255., 255., 1., 1., 1.], [ 255., 255., 255., 255., 1., 1., 1., 1.], [ 255., 255., 255., 255., 1., 1., 1., 1.], [ 1., 255., 1., 1., 1., 1., 1., 1.], [ 1., 1., 1., 1., 1., 1., 1., 1.], [ 1., 1., 1., 1., 1., 1., 1., 1.], [ 1., 1., 1., 1., 1., 1., 1., 1.]])
This is more the result I require.
array[mask] = 255
will mask the array using center point (0+radius,0+radius).
However, I'd like to be able to place any size mask at any point (y,x) and have it automatically trimmed to fit.
Python numpy shape function The numpy module provides a shape function to represent the shape and size of an array. The shape of an array is the no. of elements in each dimension. In NumPy, we will use a function called shape that returns a tuple, the elements of the tuple give the lengths of the array dimensions.
I would do it like this, where (a, b) is the center of your mask:
import numpy as np a, b = 1, 1 n = 7 r = 3 y,x = np.ogrid[-a:n-a, -b:n-b] mask = x*x + y*y <= r*r array = np.ones((n, n)) array[mask] = 255
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