如何将 NumPy 数组规范化到某个范围内? [英] How to normalize a NumPy array to within a certain range?
问题描述
对音频或图像数组进行一些处理后,需要在一个范围内进行归一化,然后才能将其写回文件.可以这样做:
After doing some processing on an audio or image array, it needs to be normalized within a range before it can be written back to a file. This can be done like so:
# Normalize audio channels to between -1.0 and +1.0
audio[:,0] = audio[:,0]/abs(audio[:,0]).max()
audio[:,1] = audio[:,1]/abs(audio[:,1]).max()
# Normalize image to between 0 and 255
image = image/(image.max()/255.0)
有没有一种不那么冗长、方便的函数方式来做到这一点?matplotlib.colors.Normalize()
似乎没有关系.
Is there a less verbose, convenience function way to do this? matplotlib.colors.Normalize()
doesn't seem to be related.
推荐答案
audio /= np.max(np.abs(audio),axis=0)
image *= (255.0/image.max())
使用 /=
和 *=
可以消除中间临时数组,从而节省一些内存.乘法比除法便宜,所以
Using /=
and *=
allows you to eliminate an intermediate temporary array, thus saving some memory. Multiplication is less expensive than division, so
image *= 255.0/image.max() # Uses 1 division and image.size multiplications
比
image /= image.max()/255.0 # Uses 1+image.size divisions
由于我们在这里使用基本的 numpy 方法,我认为这是 numpy 中最有效的解决方案.
Since we are using basic numpy methods here, I think this is about as efficient a solution in numpy as can be.
就地操作不会改变容器数组的数据类型.由于所需的归一化值是浮点数,audio
和 image
数组在执行就地操作之前需要具有浮点数据类型.如果它们还不是浮点 dtype,则需要使用 astype
转换它们.例如,
In-place operations do not change the dtype of the container array. Since the desired normalized values are floats, the audio
and image
arrays need to have floating-point point dtype before the in-place operations are performed.
If they are not already of floating-point dtype, you'll need to convert them using astype
. For example,
image = image.astype('float64')
这篇关于如何将 NumPy 数组规范化到某个范围内?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!