Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to crop a numpy 2d array to non-zero values?

Tags:

arrays

numpy

crop

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)
like image 556
Jörn Hees Avatar asked Feb 26 '18 11:02

Jörn Hees


People also ask

How can I get non-zero values in NumPy?

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)] .


1 Answers

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)
like image 180
Jörn Hees Avatar answered Oct 02 '22 20:10

Jörn Hees