Let's say i have a 2d boolean numpy array like this:
import numpy as np
a = np.array([
[0,0,0,0,0,0],
[0,1,0,1,0,0],
[0,1,1,0,0,0],
[0,0,0,0,0,0],
], dtype=bool)
How can i in general crop it to the smallest box (rectangle, kernel) that includes all True values?
So in the example above:
b = np.array([
[1,0,1],
[1,1,0],
], dtype=bool)
nonzero() function is used to Compute the indices of the elements that are non-zero. It returns a tuple of arrays, one for each dimension of arr, containing the indices of the non-zero elements in that dimension. The corresponding non-zero values in the array can be obtained with arr[nonzero(arr)] .
After some more fiddling with this, i actually found a solution myself:
coords = np.argwhere(a)
x_min, y_min = coords.min(axis=0)
x_max, y_max = coords.max(axis=0)
b = cropped = a[x_min:x_max+1, y_min:y_max+1]
The above works for boolean arrays out of the box. In case you have other conditions like a threshold t
and want to crop to values larger than t, simply modify the first line:
coords = np.argwhere(a > t)
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