gpt4 book ai didi

python - 如何以非矢量化方式计算Python中批量图像的平均值?

转载 作者:太空宇宙 更新时间:2023-11-03 15:47:44 29 4
gpt4 key购买 nike

为了计算图像平均值,可以使用numpy.mean()如果我没错的话。

什么mean()就是简单地将所有元素相加,然后除以所有元素相加的数量。此外,如果我想按 channel 计算平均值(每个 channel 都有自己的平均值计算),并且我有一个形状的输入: (num_batch, num_channel, width, height) ,我会写:

numpy.mean(a,axis=(0,2,3)) 

现在,我尝试对其非矢量化版本进行编码,但我不确定我是否正确执行了所有操作。

这是假定计算 channel 平均值的代码(其输出应与上面给出的命令相匹配:

def calc_mean_classic(a):
#sum all elements in each channel and divide by the number of elements
batch = a.shape[0]
channel = a.shape[1]
width = a.shape[2]
height = a.shape[3]

sum = np.zeros((channel))
for i in range(batch):
for c in range(channel):
for w in range(width):
for h in range(height):
sum[c] += a[i,c,w,h]

return sum, (sum/(width*height))

当我使用 numpy.mean(a,axis=(0,2,3)) 运行数据时,我得到:

[ 125.30691805  122.95039414  113.86538318]

但是当我运行我编码的函数时,我得到:

sum,m3 = calc_mean_classic(data_train)
print 'sum=',sum
print 'm3=',m3
print m3[0]/(32*32)

输出:

sum= [  6.41571420e+09   6.29506018e+09   5.82990762e+09]
m3= [ 6265345.90234375 6147519.70703125 5693269.15917969]
6118.50185776

这里有一个讽刺,图片大小是32*32这就是我这样做的原因m3[0]/(32*32) ( sum/width*height ) 看看我是否可以生成 sum[0]值(value)!正如您所看到的,它们是完全不同的值,但它们应该产生相同的值!

我不知道这里发生了什么。

最佳答案

沿这三个轴使用 sum 并除以 block 大小,即 width*heighta.shape[2]*a.shape [3]-

batch_mean = np.sum(a,axis=(0,2,3))/(a.shape[2]*a.shape[3])

使用np.mean(a,axis=(0,2,3)),您还除以沿第一个轴的元素数,这似乎不是预期的操作在那里,至少不能使用 sum/(width*height) 和您的 func calc_mean_classic

<小时/>

否则,如果您打算使用循环 calc_mean_classic 来模拟 np.mean(a,axis=(0,2,3)) 的行为,只需编辑合并 a.shape[0] -

的 return 语句
return sum, (sum/(width*height*a.shape[0]))

关于python - 如何以非矢量化方式计算Python中批量图像的平均值?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41613963/

29 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com