python - How to get coordinates from a numpy slice object -


i have function receives image , slice object specifying sub region of image operate on. draw box around specified region debugging purposes. easiest way draw box coordinates of 2 of corners. cannot find way of getting coordinates out of slice object however.

there of course inefficient way of doing define large matrix , use slice on figure out elements affected

#given slice my_slice = np.s_[ymin:ymax+1, xmin:xmax+1]  #recover 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 best method have switch passing slice objects around kind of rectangle object.

i use dir inside object. in 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 start, step, , stop attributes useful:

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

(to honest, use ipython, , instead of using dir typically make object , hit tab inside.)

and turn my_slice object corners, it's simply:

>>> [(sl.start, sl.stop) sl in my_slice] [(2, 7), (3, 6)] 

Comments