[SciPy-User] autocrop 2d array

Zachary Pincus zachary.pincus at yale.edu
Thu May 12 12:44:09 EDT 2011


> 
> You ought to be able to rig something up with numpy.where, which returns the coordinates in the array that match some condition. Something like this:
> 
> foo = np.zeros((5, 5))
> foo[1:4,1:4] = np.arange(9).reshape(3, 3)
> coords = np.array(np.where(foo != 0)).T
> minCorner = np.min(coords, axis = 0)
> maxCorner = np.max(coords, axis = 0) + 1
> foo[minCorner[0]:maxCorner[0], minCorner[1]:maxCorner[1]] 
> 
> There's almost certainly even faster ways to do this; this is just the first solution that came to mind.
> 

The above solution is basically identical to mine, and it might be a little faster or more memory-efficient if np.where() is implemented in C...

Thanks, Chris!




More information about the SciPy-User mailing list