简体   繁体   English

如何有效地计算嵌套在 numpy ndarray 中的数组的指定索引?

[英]How to efficiently compute over specified index of array nested in numpy ndarray?

I know versions of this question appear frequently on here, but I was not able to find a solution that works for me.我知道这里经常出现这个问题的版本,但我找不到适合我的解决方案。 For some background on the problem, I have an RGB image that is divided into chunks of NxN pixels.对于这个问题的一些背景,我有一个被分成 NxN 像素块的 RGB 图像。 I want to compute the average of each color channel separately for each chunk.我想为每个块分别计算每个颜色通道的平均值。 I know numpy is best used by leveraging vectorized operations, but the level of higher-dimensional slicing and indexing required here is beyond me.我知道 numpy 最好通过利用矢量化操作来使用,但是这里所需的高维切片和索引级别超出了我的范围。 Essentially I need the following functionality:基本上我需要以下功能:

 for row in tiles:
     for col in row:
         rsum = 0;
         gsum = 0;
         bsum = 0;
         for n in col:
             for vec in n:
                 rsum += vec[0]
                 gsum += vec[1]
                 bsum += vec[2]
         col[..., 0] = rsum/n.shape[0]**2
         col[..., 1] = gsum/n.shape[0]**2
         col[..., 2] = bsum/n.shape[0]**2

Where the shape of my ndarray is:我的 ndarray 的形状是:

tiles.shape = (138, 84, 100, 100, 4)

A 138x84 matrix of 100x100 matrices, where each element is a length-4 vector.一个由 100x100 矩阵组成的 138x84 矩阵,其中每个元素是一个长度为 4 的向量。 Is there a way to do this without any loops?有没有办法在没有任何循环的情况下做到这一点? Should I reshape my ndarray?我应该重塑我的 ndarray 吗? Any guidance is much appreciated.非常感谢任何指导。

只需将要平均的轴传递给np.mean

avg = np.mean(tiles, axis=(2, 3))

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

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