【发布时间】:2014-11-03 15:05:58
【问题描述】:
我有一个 RGB 图像,它表示为一个大小为 (500、500、3) 的 numpy 数组。我还有一个大小为 (500, 500) 的数组,其中每个像素都有一个介于 0 和 99 之间的整数值。这基本上将图像划分为许多子区域。属于子数组的像素共享相同的整数索引。
我有兴趣进行一些计算,例如计算每个子集的均值和标准差。我可以通过如下循环图像来做到这一点(例如计算平均值):
# image is of size (500, 500, 3) ->RGB values
# label is of size (500, 500) -> contains integers
import numpy as np
mean = np.zeros((100, 3))
for i in range(0, 100):
count = 0
for x in range(0,500):
for y in range(0,500):
if label[x, y] == i:
mean[i, :] += image[x, y,:]
count = count + 1
# Compute the mean
if count > 0:
mean[i,:] /= count
我这样做的方式包括很多循环,它似乎是非常非 Python 的,我想知道是否有更好的(在速度方面)方式来做到这一点。
【问题讨论】:
标签: python performance loops numpy vectorization