简体   繁体   English

如何从numpy切片对象获取坐标

[英]How to get coordinates from a numpy slice object

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. 如果这是最好的方法,我可能不得不从传递切片对象切换到某种矩形对象。

I often use dir to look inside an object. 我经常使用dir来查看对象内部。 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: 那些startstepstop属性看起来很有用:

>>> 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.) (说实话,我使用IPython,因此通常不使用dir而是创建一个对象,然后按TAB键查看内部。)

And so to turn your my_slice object into the corners, it's simply: 因此,要将my_slice对象转换为角落,它只是:

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM