添加多个重叠多维数据集的矢量化方法

时间:2018-08-27 17:17:44

标签: python numpy opencv

我正在使用滑动窗口对大型矩形图像进行深度学习。图像具有形状(高度,宽度)。

预测输出是形状(高度,宽度,prediction_probability)的ndarray。我的预测在重叠的窗口中输出,我需要将这些窗口加在一起才能获得整个输入图像的逐像素预测。窗口的(高度,宽度)重叠超过2个像素。

以前,在C ++中,我已经完成了类似的工作,创建了一个较大的结果索引,然后将所有的ROI加在一起。

#include <opencv2/core/core.hpp>
using namespace std;  

template <int numberOfChannels>
static void AddBlobToBoard(Mat& board, vector<float> blobData,
                                            int blobWidth, int blobHeight,
                                            Rect roi) {
 for (int y = roi.y; y < roi.y + roi.height; y++) {
    auto vecPtr = board.ptr< Vec <float, numberOfChannels> >(y);
    for (int x = roi.x; x < roi.x + roi.width; x++) {
      for (int channel = 0; channel < numberOfChannels; channel++) {
          vecPtr[x][channel] +=
            blobData[(band * blobHeight + y - roi.y) * blobWidth + x - roi.x];}}}

在Python中是否有矢量化的方法?

1 个答案:

答案 0 :(得分:1)

编辑:

@Kevin IMO如果仍在训练网络,则应在完全连接的层上执行此步骤。那就是..

如果您想使用某些东西,我有一个非矢量化的解决方案。任何解决方案都将占用大量内存。在我的笔记本电脑上,它可以快速处理CIFAR大小的灰度图像(32x32)。也许某个聪明的人可以引导关键一步。

首先使用arr将测试数组win拆分为窗口skimage。这是测试数据。

>>> import numpy as np
>>> from skimage.util.shape import view_as_windows as viewW
>>> arr = np.arange(20).reshape(5,4)
>>> win = viewW(arr, (3,3))
>>> arr # test data 
array([[ 0,  1,  2,  3],
       [ 4,  5,  6,  7],
       [ 8,  9, 10, 11],
       [12, 13, 14, 15],
       [16, 17, 18, 19]])
>>> win[0,0]==arr[:3,:3] # it works. 
array([[ True,  True,  True],
       [ True,  True,  True],
       [ True,  True,  True]])

现在要重新组合,生成形状为out的输出数组(5,4,6)6win中的窗口数,而(5,4)arr.shape。我们将沿-1轴在每个切片中的一个窗口中填充此数组。

# the array to be filled
out = np.zeros((5,4,6)) # shape of original arr stacked to the number of windows 

# now make the set of indices of the window corners in arr 
inds = np.indices((3,2)).T.reshape(3*2,2)

# and generate a list of slices. each selects the position of one window in out 
slices = [np.s_[i[0]:i[0]+3:1,i[1]:i[1]+3:1,j] for i,j in zip(inds,range(6))] 

# this will be the slow part. You have to loop through the slices. 
# does anyone know a vectorized way to do this? 
for (ii,jj),slc in zip(inds,slices):
    out[slices] = win[ii,jj,:,:]

现在,out数组包含所有处于适当位置的窗口,但在-1轴上分成多个窗格。要提取原始数组,您可以沿该轴平均所有不包含零的元素。

>>> out = np.true_divide(out.sum(-1),(out!=0).sum(-1))
>>> # this can't handle scenario where all elements in an out[i,i,:] are 0
>>> # so set nan to zero 

>>> out = np.nan_to_num(out)
>>> out 
array([[ 0.,  1.,  2.,  3.],
       [ 4.,  5.,  6.,  7.],
       [ 8.,  9., 10., 11.],
       [12., 13., 14., 15.],
       [16., 17., 18., 19.]])

您能想到一种以矢量化方式对切片数组进行操作的方法吗?

一起:

def from_windows(win):
    """takes in an arrays of windows win and returns the original array from which they come"""
    a0,b0,w,w = win.shape # shape of window
    a,b = a0+w-1,b0+w-1 # a,b are shape of original image 
    n = a*b # number of windows 
    out = np.zeros((a,b,n)) # empty output to be summed over last axis 
    inds = np.indices((a0,b0)).T.reshape(a0*b0,2) # indices of window corners into out 
    slices = [np.s_[i[0]:i[0]+3:1,i[1]:i[1]+3:1,j] for i,j in zip(inds,range(n))] # make em slices 
    for (ii,jj),slc in zip(inds,slices): # do the replacement into out 
        out[slc] = win[ii,jj,:,:]
    out = np.true_divide(out.sum(-1),(out!=0).sum(-1)) # average over all nonzeros 
    out = np.nan_to_num(out) # replace any nans remnant from np.alltrue(out[i,i,:]==0) scenario
    return out # hope you've got ram 

和测试:

>>> arr = np.arange(32**2).reshape(32,32)
>>> win = viewW(arr, (3,3))
>>> np.alltrue(arr==from_windows(win))
True
>>> %timeit from_windows(win)
6.3 ms ± 117 µs per loop (mean ± std. dev. of 7 runs, 100 loops each)

实际上,这还不够快,您无法继续训练