繁体   English   中英

更快地从图像中提取补丁?

[英]Faster way to extract patches from images?

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

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是原始图像。

但是这段代码需要25秒的时间。 谁能告诉我如何让这项工作更快? 或任何其他替代方案,如果你能提出它会有很大的帮助。

假设你分别处理近边界索引,否则你会有不同形状的补丁,让我们自己建议一个矢量化的方法,利用broadcastinglinear-indexing一些知识。 下面发表的是一个实现与该哲学一起为我们提供这样的补丁的3D阵列 -

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(8,10)的最小输入情况下运行样本,索引使得所需的补丁不会超出输入图像的边界。 然后,运行原始和建议的验证方法。 开始了 -

1]输入:

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

3]输出的原始方法:

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]提出的输出方法:

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]]])

使用scikit-learn:

from sklearn.feature_extraction.image import extract_patches

all_patches = extract_patches(x, patch_size)

upper_left = indices - patch_size // 2
patches = all_patches[upper_left[0], upper_left[1]]

类似的功能可以在scikit-image: view_as_windows

暂无
暂无

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

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