gpt4 book ai didi

python - 高效标准化 Numpy 数组中的图像

转载 作者:行者123 更新时间:2023-11-28 22:18:48 33 4
gpt4 key购买 nike

我有一个形状为 (N, H, W, C) 的图像数组,其中 N 是图像的数量,H 图像高度,W 图像宽度和 C RGB channel 。

我想按 channel 标准化我的图像,因此对于每个图像,我想按 channel 减去图像 channel 的平均值并除以其标准差。

我在一个循环中执行此操作,该方法有效,但是它非常低效,并且在复制时我的 RAM 变得太满了。

def standardize(img):
mean = np.mean(img)
std = np.std(img)
img = (img - mean) / std
return img

for img in rgb_images:
r_channel = standardize(img[:,:,0])
g_channel = standardize(img[:,:,1])
b_channel = standardize(img[:,:,2])
normalized_image = np.stack([r_channel, g_channel, b_channel], axis=-1)
standardized_images.append(normalized_image)
standardized_images = np.array(standardized_images)

如何利用 numpy 的功能更有效地做到这一点?

最佳答案

沿第二和第三轴执行 ufunc 缩减(均值,标准差),同时保持 dims 完好无损,这有助于 broadcasting稍后进行除法步骤-

mean = np.mean(rgb_images, axis=(1,2), keepdims=True)
std = np.std(rgb_images, axis=(1,2), keepdims=True)
standardized_images_out = (rgb_images - mean) / std

根据其公式并因此受到 this solution 的启发,通过重新使用平均值来计算标准差来进一步提高性能, 像这样 -

std = np.sqrt(((rgb_images - mean)**2).mean((1,2), keepdims=True))

将缩减轴作为参数打包到一个函数中,我们将有 -

from __future__ import division

def normalize_meanstd(a, axis=None):
# axis param denotes axes along which mean & std reductions are to be performed
mean = np.mean(a, axis=axis, keepdims=True)
std = np.sqrt(((a - mean)**2).mean(axis=axis, keepdims=True))
return (a - mean) / std

standardized_images = normalize_meanstd(rgb_images, axis=(1,2))

关于python - 高效标准化 Numpy 数组中的图像,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50239066/

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