混淆numpy apply_along_axis 4D矩阵

时间:2018-01-15 21:53:02

标签: python numpy matrix apply

我注意到一个我不确定理解的stange bug。我有一个4D矩阵(样本,高度,长度,通道)和这个函数来计算每个通道的直方图(处理图片)

regions.shape #(110, 60, 100, 3)

def GetColorHist(i):
    r = measurements.histogram(i[:,:,0], 20, 220, 10) # histogram of reds
    g = measurements.histogram(i[:,:,1], 20, 220, 10) # histogram of greens
    b = measurements.histogram(i[:,:,2], 20, 220, 10) # histogram of blues
    return(np.dstack((r,g,b)))

当应用于矩阵(区域)的特定样本时,它工作正常。例如

GetColorHist(regions[70])
> array([[[   0,    0,    0],
    [   0,    0,    0],
    [   0,    0,    0],
    [   0,    0,    0],
    [   0,    0,    0],
    [   0,    0,  600],
    [   0, 1271, 5400],
    [   3, 4729,    0],
    [5942,    0,    0],
    [  55,    0,    0]]])

但我未能将其应用于矩阵的相关维度

np.apply_along_axis(GetColorHist,0,regions)

<ipython-input-57-246240b60568> in GetColorHist(i)
  1 def GetColorHist(i):
   ----> 2     r = measurements.histogram(i[:,:,0], 20, 220, 10) # histogram of reds
  3     g = measurements.histogram(i[:,:,1], 20, 220, 10) # histogram of greens
  4     b = measurements.histogram(i[:,:,2], 20, 220, 10) # histogram of blues
  5     return(np.dstack((r,g,b)))

 IndexError: too many indices for array

我尝试了几件事,比如改变我的输出形状,但仍然得到同样的混乱。有谁知道发生了什么?

由于

1 个答案:

答案 0 :(得分:0)

结果是,迭代工作正常(并且使用pool.map技巧快速)

pool = ThreadPool(multiprocessing.cpu_count()) # get the number of CPU

X = pool.map(GetColorHist,[regions[x] for x in range(regions.shape[0])])
X = np.array(X)

pool.close() 
pool.join()