更快地从图像中提取补丁? [英] Faster way to extract patches from images?

查看:183
本文介绍了更快地从图像中提取补丁?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试提取以某个给定位置(x,y)为中心的固定大小的补丁。代码如下 -

I am trying to extract patches of fixed size centered at some given position (x,y). The code is given below-

for i,j in zip(indices[0],indices[1]):
    patches.append(
        x[None,
          i-int(np.floor(patch_size/2.0)):i+int(np.floor(patch_size/2.0))+1,
          j-int(np.floor(patch_size/2.0)):j+int(np.floor(patch_size/2.0))+1])

变量 indices 是位置( indices.shape =(2,770) )。 x 是原始图片。

Variable indices is the locations (indices.shape=(2,770)). x is the original image.

但此代码需要25秒的时间。谁能告诉我如何让这项工作更快?或任何其他选择,如果你可以建议它会有很大的帮助。

But this code is taking 25s seconds time. Can anyone tell me how to make this work faster? or any other alternatives if you can suggest it would be of great help.

推荐答案

假设你正在分别处理近边界指数,否则你将有不同形状的补丁,让我们建议自己使用 广播 以及有关线性索引的一些知识。下面发布的是一个实现与该哲学一起给我们一个 3D 这样的补丁数组 -

Assuming you are dealing with near-boundary indices separately, as otherwise you would have different shaped patches, let us suggest ourselves a vectorized approach making use broadcasting together with some knowledge about linear-indexing. Posted below is an implementation to go with that philosophy to give us a 3D array of such patches -

m,n = x.shape
K = int(np.floor(patch_size/2.0))
R = np.arange(-K,K+1)                  
out = np.take(x,R[:,None]*n + R + (indices[0]*n+indices[1])[:,None,None])

让我们在输入图像 x <的最小输入案例上运行示例code>(8,10)并且索引使得所需的补丁不会超出输入图像的边界。然后,运行原始和建议的验证方法。我们走了 -

Let's do a sample run on a minimal input case with input image x of (8,10) and indices are such that the desired patches don't extend beyond the boundaries of the input image. Then, run the original and proposed approaches for verification. Here we go -

1]输入:

In [105]: # Inputs
     ...: x = np.random.randint(0,99,(8,10))
     ...: indices = np.array([[4,2,3],[6,3,7]])
     ...: 

3 ]带输出的原始方法:

3] Original approach with output :

In [106]: # Posted code in the question ...

In [107]: patches[0]
Out[107]: 
array([[[92, 21, 84],
        [10, 52, 36],
        [ 5, 62, 61]]])

In [108]: patches[1]
Out[108]: 
array([[[71, 76, 75],
        [80, 32, 55],
        [77, 62, 42]]])

In [109]: patches[2]
Out[109]: 
array([[[16, 88, 31],
        [21, 84, 51],
        [52, 36,  3]]])

3]提出的输出方法:

3] Proposed approach with output :

In [110]:  # Posted code in the solution earlier ...

In [111]: out
Out[111]: 
array([[[92, 21, 84],
        [10, 52, 36],
        [ 5, 62, 61]],

       [[71, 76, 75],
        [80, 32, 55],
        [77, 62, 42]],

       [[16, 88, 31],
        [21, 84, 51],
        [52, 36,  3]]])

这篇关于更快地从图像中提取补丁?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆