Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is there a "bounding box" function (slice with non-zero values) for a ndarray in NumPy?

Tags:

I am dealing with arrays created via numpy.array(), and I need to draw points on a canvas simulating an image. Since there is a lot of zero values around the central part of the array which contains the meaningful data, I would like to "trim" the array, erasing columns that only contain zeros and rows that only contain zeros.

So, I would like to know of some native numpy function or even a code snippet to "trim" or find a "bounding box" to slice only the data-containing part of the array.

(since it is a conceptual question, I did not put any code, sorry if I should, I'm very fresh to posting at SO.)

Thanks for reading

like image 744
heltonbiker Avatar asked Jan 26 '11 18:01

heltonbiker


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

Which function is used to create a NumPy Ndarray object?

The array object in NumPy is called ndarray . We can create a NumPy ndarray object by using the array() function.

What is the difference between NumPy Ndarray and array?

numpy. array is just a convenience function to create an ndarray ; it is not a class itself. You can also create an array using numpy. ndarray , but it is not the recommended way.


1 Answers

This should do it:

from numpy import array, argwhere  A = array([[0, 0, 0, 0, 0, 0, 0],            [0, 0, 0, 0, 0, 0, 0],            [0, 0, 1, 0, 0, 0, 0],            [0, 0, 1, 1, 0, 0, 0],            [0, 0, 0, 0, 1, 0, 0],            [0, 0, 0, 0, 0, 0, 0],            [0, 0, 0, 0, 0, 0, 0]])  B = argwhere(A) (ystart, xstart), (ystop, xstop) = B.min(0), B.max(0) + 1  Atrim = A[ystart:ystop, xstart:xstop] 
like image 163
Paul Avatar answered Oct 14 '22 19:10

Paul