【问题标题】:confused about numpy apply_along_axis 4D matrix对 numpy apply_along_axis 4D 矩阵感到困惑
【发布时间】:2018-01-15 21:53:01
【问题描述】:

我注意到一个我不确定是否理解的 stange 错误。我有一个 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

我尝试了几种方法,例如更改输出形状,但仍然一团糟。有谁明白这是怎么回事?

谢谢

【问题讨论】:

  • 只需在所需的轴上进行迭代。 applyalong 没有做任何额外的事情。
  • 你的意思是,有一个循环?
  • map(GetColorHist,[regions[x] for x in range(regions.shape[0])])
  • apply_along_axis 在提供的轴上沿1D 切片调用函数,而不是在所有提供的轴上的N-1D 切片

标签: python numpy matrix apply


【解决方案1】:

事实证明,迭代工作正常(并且使用 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()

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-09-13
    • 2012-07-22
    • 2013-05-13
    • 2020-04-16
    • 2023-03-08
    • 2019-08-04
    相关资源
    最近更新 更多