gpt4 book ai didi

python - 在 Python 中计算图像数据集 channel 明智均值和标准差的最快方法

转载 作者:太空狗 更新时间:2023-10-29 21:45:12 24 4
gpt4 key购买 nike

我有一个内存无法容纳的巨大图像数据集。我想计算均值标准差,从磁盘加载图像。

我目前正在尝试使用在 wikipedia 上找到的算法.

# for a new value newValue, compute the new count, new mean, the new M2.
# mean accumulates the mean of the entire dataset
# M2 aggregates the squared distance from the mean
# count aggregates the amount of samples seen so far
def update(existingAggregate, newValue):
(count, mean, M2) = existingAggregate
count = count + 1
delta = newValue - mean
mean = mean + delta / count
delta2 = newValue - mean
M2 = M2 + delta * delta2

return existingAggregate

# retrieve the mean and variance from an aggregate
def finalize(existingAggregate):
(count, mean, M2) = existingAggregate
(mean, variance) = (mean, M2/(count - 1))
if count < 2:
return float('nan')
else:
return (mean, variance)

这是我当前的实现(只为红色 channel 计算):

count = 0
mean = 0
delta = 0
delta2 = 0
M2 = 0
for i, file in enumerate(tqdm(first)):
image = cv2.imread(file)
for i in range(224):
for j in range(224):
r, g, b = image[i, j, :]
newValue = r
count = count + 1
delta = newValue - mean
mean = mean + delta / count
delta2 = newValue - mean
M2 = M2 + delta * delta2

print('first mean', mean)
print('first std', np.sqrt(M2 / (count - 1)))

这个实现在我尝试过的数据集的一个子集上工作得非常接近。

问题是它非常慢,因此不可行。

  • 是否有执行此操作的标准方法?

  • 我如何调整它以获得更快的结果或计算所有数据集的 RGB 均值和标准差,而无需同时以合理的速度将其全部加载到内存中?

最佳答案

由于这是一项繁重的数值任务(围绕矩阵或张量进行大量迭代),我总是建议使用擅长此操作的库:numpy。

正确安装的 numpy 应该能够利用底层 BLAS(基本线性代数子例程)例程,这些例程针对从内存层次结构角度操作 float 组进行了优化。

imread 应该已经为您提供了 numpy 数组。您可以通过

获得红色 channel 图像的 reshape 一维数组
import numpy as np
val = np.reshape(image[:,:,0], -1)

平均数

np.mean(val)

和标准偏差

np.std(val)

这样就可以摆脱两层python循环:

count = 0
mean = 0
delta = 0
delta2 = 0
M2 = 0
for i, file in enumerate(tqdm(first)):
image = cv2.imread(file)
val = np.reshape(image[:,:,0], -1)
img_mean = np.mean(val)
img_std = np.std(val)
...

其余的增量更新应该很简单。

一旦你这样做了,瓶颈就会变成图像加载速度,它受到磁盘读取操作性能的限制。在这方面,根据我以前的经验,我怀疑像其他人建议的那样使用多线程会有很大帮助。

关于python - 在 Python 中计算图像数据集 channel 明智均值和标准差的最快方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47850280/

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