[英]Extract multiple windows/patches from an (image) array, as defined in another array
I have an image im
which is an array as given by imread
. 我有一个图像
im
,这是一个由imread
给出的imread
。 Say eg 比如说
im = np.array([[1,2,3,4],
[2,3,4,5],
[3,4,5,6],
[4,5,6,7]]
I have another (n,4)
array of windows
where each row defines a patch of the image as (x, y, w, h)
. 我有另一个
(n,4)
windows
数组,其中每行定义图像的补丁为(x, y, w, h)
。 Eg 例如
windows = np.array([[0,0,2,2],
[1,1,2,2]]
I'd like to extract all of these patches from im
as sub-arrays without looping through. 我想从
im
提取所有这些补丁作为子数组,而不需要循环。 My current looping solution is something like: 我目前的循环解决方案是这样的:
for x, y, w, h in windows:
patch = im[y:(y+h),x:(x+w)]
But I'd like a nice array-based operation to get all of them, if possible. 但是如果可能的话,我想要一个很好的基于数组的操作来获取所有这些操作。
Thanks. 谢谢。
For same window sizes, we could get views with help from scikit-image's view_as_windows
, like so - 对于相同的窗口大小,我们可以在scikit-image的
view_as_windows
帮助下获得视图,就像这样 -
from skimage.util.shape import view_as_windows
im4D = view_as_windows(im, (windows[0,2],windows[0,3]))
out = im4D[windows[:,0], windows[:,1]]
Sample run - 样品运行 -
In [191]: im4D = view_as_windows(im, (windows[0,2],windows[0,3]))
In [192]: im4D[windows[:,0], windows[:,1]]
Out[192]:
array([[[1, 2],
[2, 3]],
[[3, 4],
[4, 5]]])
If scikit
is not available we can homebrew @Divakar's solution with numpy.lib.stride_tricks
. 如果
scikit
不可用,我们可以使用numpy.lib.stride_tricks
自制numpy.lib.stride_tricks
的解决方案。 The same constraint (all windows must have same shape) applies: 适用相同的约束(所有窗口必须具有相同的形状):
import numpy as np
from numpy.lib.stride_tricks import as_strided
im = np.array([[1,2,3,4],
[2,3,4,5],
[3,4,5,6],
[4,5,6,7]])
windows = np.array([[0,0,2,2],
[1,1,2,2]])
Y, X = im.shape
y, x = windows[0, 2:]
cutmeup = as_strided(im, shape=(Y-y+1, X-x+1, y, x), strides=2*im.strides)
print(cutmeup[windows[:, 0], windows[:, 1]])
Output: 输出:
[[[1 2]
[2 3]]
[[3 4]
[4 5]]]
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.