简体   繁体   English

如何在不循环每个像素的情况下同时裁剪具有窗口大小的 numpy 数组的每个元素?

[英]How to crop each element of a numpy array with a window size at the same time without looping over each pixel?

I have a numpy array with a size of 240 x 320 x 3 and I want to use a window (window size ws=5 ) to slide over each pixel and crop out the subarray centered at that pixel.我有一个大小为240 x 320 x 3的 numpy 数组,我想使用一个窗口(窗口大小ws=5 )滑过每个像素并裁剪出以该像素为中心的子数组。 The final output dimension should be 240 x 320 x ws x ws x 3 .最终输出尺寸应为240 x 320 x ws x ws x 3 So I pad the original array with window size and use for loop to do so.所以我用窗口大小填充原始数组并使用for loop来这样做。

height = 240
width = 320
image = np.random.rand((height, width, 3))
image = np.pad(image, ((ws//2, ws//2), (ws//2, ws//2), (0, 0)), mode='reflect')
patches = np.zeros((height, width, ws, ws, 3))
for i in range(height):
    for j in range(width):
        patches[i, j] = image[i:i+ws, j:j+ws]

Are there any ways to do the cropping of each pixel at the sample time?有没有办法在采样时对每个像素进行裁剪? Like without using the for loop over each pixel?就像在每个像素上不使用for loop一样?

You are basically getting sliding windows across the image.您基本上是在图像上滑动窗口。 We can leverage np.lib.stride_tricks.as_strided based scikit-image's view_as_windows to get sliding windows.我们可以利用基于np.lib.stride_tricks.as_stridedscikit-image's view_as_windows来获得滑动窗口。 More info on use of as_strided based view_as_windows .有关使用基于view_as_windowsas_strided的更多信息

from skimage.util.shape import view_as_windows

out = view_as_windows(image,(ws,ws,1)).transpose(0,1,4,3,2,5)[:-1,:-1,...,0]

# Alternatively :
out = view_as_windows(image,(ws,ws,1))[:-1,:-1,...,0].transpose(0,1,4,3,2)

Also note that you are missing out on the last possible window, if you had for i in range(height+1) and for j in range(width+1) .另请注意,如果您有for i in range(height+1)for j in range(width+1) ,您将错过最后一个可能的窗口。 To get the same result with our solution, the last indexing step would modify to [...,0] in place of [:-1,:-1,...,0] , thus giving us -为了使用我们的解决方案获得相同的结果,最后一个索引步骤将修改为[...,0]代替[:-1,:-1,...,0] ,从而给我们 -

out = view_as_windows(image,(ws,ws,1))[...,0].transpose(0,1,4,3,2)

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

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