Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to get coordinates from a numpy slice object

Tags:

python

numpy

I have a function which receives an image and a slice object specifying a sub region of that image to operate on. I would like to draw a box around the specified region for debugging purposes. The easiest way to draw a box is to get the coordinates of two of its corners. I cannot find a good way of getting those coordinates out of the slice object however.

There is of course a really inefficient way of doing it where I define a large matrix and use my slice on it to figure out what elements are affected

#given some slice like this
my_slice = np.s_[ymin:ymax+1, xmin:xmax+1]

#recover its dimensions
large_matrix = np.ones((max_height, max_width))
large_matrix[my_slice] = 1
minx = np.min(np.where(large_matrix == 1)[0])
maxx = np.max(np.where(large_matrix == 1)[0])
...

If this is the best method I will probably have to switch from passing slice objects around to some kind of rectangle object.

like image 506
Hammer Avatar asked Jan 20 '26 11:01

Hammer


1 Answers

I often use dir to look inside an object. In your case:

>>> xmin,xmax = 3,5
>>> ymin,ymax = 2, 6
>>> my_slice = np.s_[ymin:ymax+1, xmin:xmax+1]
>>> my_slice
(slice(2, 7, None), slice(3, 6, None))
>>> my_slice[0]
slice(2, 7, None)
>>> dir(my_slice[0])
['__class__', '__cmp__', '__delattr__', '__doc__', '__format__', 
'__getattribute__', '__hash__', '__init__', '__new__', '__reduce__', 
'__reduce_ex__', '__repr__', '__setattr__', '__sizeof__', '__str__', 
'__subclasshook__', 'indices', 'start', 'step', 'stop']

And those start, step, and stop attributes look useful:

>>> my_slice[0].start
2
>>> my_slice[0].stop
7

(To be perfectly honest, I use IPython, and so instead of using dir I would typically just make an object and then hit TAB to look inside.)

And so to turn your my_slice object into the corners, it's simply:

>>> [(sl.start, sl.stop) for sl in my_slice]
[(2, 7), (3, 6)]
like image 123
DSM Avatar answered Jan 22 '26 00:01

DSM



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!