gpt4 book ai didi

python - 在 numpy 中实现规范化过滤器的好方法

转载 作者:行者123 更新时间:2023-11-28 22:51:35 26 4
gpt4 key购买 nike

我对 Numpy 数组的内存模型不是很熟悉。是否有更有效的方法(或“更好的做法”)来计算图像的规范化版本?也就是说,对于每个像素 r+g+b == 1 的图像。

也许使用更面向矩阵的方法?这样的过滤器有名字吗?

这是我目前的代码(忽略被零除的错误):

def normalize(image):
lines, columns, depth = image.shape
normalized = np.zeros(image.shape)
for i in range(lines):
for j in range(columns):
normalized[i,j] = image[i,j] / float(np.sum(image[i,j]))
return normalized

其中图像是深度为 3 的 np.array

谢谢

最佳答案

利用 numpy 的 broadcasting rules 可以更有效地完成此操作

>>> import numpy as np
>>> image = np.random.random(size=(3,4,5))
>>> sums = image.sum(axis=2)
>>> sums.shape
... (3, 4)
>>> normalized = image / sums[:, :, None] #same as image / sums[:, :, np.newaxis]
>>> normalized.sum(axis=2)
... array([[ 1., 1., 1., 1.],
... [ 1., 1., 1., 1.],
... [ 1., 1., 1., 1.]])

如果您担心内存问题,并且不需要原始图像,您可以就地对其进行归一化

>>> image /= image.sum(axis=2)[:, :, None]

作为函数:

def normalize(image, inplace=False):
if inplace:
image /= image.sum(axis=2)[:, :, None]
else:
return image / image.sum(axis=2)[:, :, None]

关于python - 在 numpy 中实现规范化过滤器的好方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21382521/

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