我有一个接收图像的功能和一个切片对象,指定要操作的图像的子区域.我想在指定区域周围绘制一个框以进行调试.绘制框的最简单方法是获取其两个角的坐标.然而,我无法找到从切片对象中获取这些坐标的好方法.
在我定义一个大矩阵并在其上使用我的切片来确定哪些元素受到影响时,当然有一种非常低效的方法.
#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])
...
Run Code Online (Sandbox Code Playgroud)
如果这是最好的方法,我可能不得不从传递切片对象切换到某种矩形对象.
我经常dir用来查看一个物体.在你的情况下:
>>> 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']
Run Code Online (Sandbox Code Playgroud)
那些start,step和stop属性看起来很有用:
>>> my_slice[0].start
2
>>> my_slice[0].stop
7
Run Code Online (Sandbox Code Playgroud)
(说实话,我使用IPython,因此dir我不会使用我通常只创建一个对象然后点击TAB来查看内部.)
因此,要将my_slice对象转变为角落,它只是:
>>> [(sl.start, sl.stop) for sl in my_slice]
[(2, 7), (3, 6)]
Run Code Online (Sandbox Code Playgroud)