在对音频或图像数组进行一些处理后,需要在一个范围内对其进行规范化,然后才能将其写回文件。可以这样做:

# 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()似乎并不相关。


你可以使用“i”(如idiv, imul..)版本,看起来还不错:

image /= (image.max()/255.0)

对于另一种情况,你可以写一个函数来规范一个n维数组的列:

def normalize_columns(arr):
    rows, cols = arr.shape
    for col in xrange(cols):
        arr[:,col] /= abs(arr[:,col]).max()

# Normalize audio channels to between -1.0 and +1.0
audio /= np.max(np.abs(audio),axis=0)
# Normalize image to between 0 and 255
image *= (255.0/image.max())

使用/=和*=可以消除中间临时数组,从而节省一些内存。乘法比除法便宜,所以

image *= 255.0/image.max()    # Uses 1 division and image.size multiplications

略快于

image /= image.max()/255.0    # Uses 1+image.size divisions

由于我们在这里使用的是基本的numpy方法,所以我认为这是numpy中最有效的解决方案。


就地操作不会改变容器数组的dtype。由于所需的规范化值是浮点数,因此音频和图像数组在执行原地操作之前需要具有浮点点dtype。 如果它们不是浮点dtype,则需要使用astype对它们进行转换。例如,

image = image.astype('float64')

您还可以使用sklearn重新缩放。其优点是,除了对数据进行均值居中之外,还可以调整标准偏差的归一化,并且可以在任意一个轴上、通过特征或通过记录进行此操作。

from sklearn.preprocessing import scale
X = scale( X, axis=0, with_mean=True, with_std=True, copy=True )

关键字参数axis、with_mean、with_std是不言自明的,并以默认状态显示。如果参数副本被设置为False,则该参数副本就地执行操作。这里的文档。


如果数组同时包含正数据和负数据,我将使用:

import numpy as np

a = np.random.rand(3,2)

# Normalised [0,1]
b = (a - np.min(a))/np.ptp(a)

# Normalised [0,255] as integer: don't forget the parenthesis before astype(int)
c = (255*(a - np.min(a))/np.ptp(a)).astype(int)        

# Normalised [-1,1]
d = 2.*(a - np.min(a))/np.ptp(a)-1

如果数组包含nan,一种解决方案是将它们删除为:

def nan_ptp(a):
    return np.ptp(a[np.isfinite(a)])

b = (a - np.nanmin(a))/nan_ptp(a)

但是,根据上下文的不同,您可能希望以不同的方式对待nan。例如,插入值,替换为0,或引发错误。

最后,值得一提的是,即使这不是OP的问题,标准化:

e = (a - np.mean(a)) / np.std(a)

一个简单的解决方案是使用sklearn提供的标量。预处理的图书馆。

scaler = sk.MinMaxScaler(feature_range=(0, 250))
scaler = scaler.fit(X)
X_scaled = scaler.transform(X)
# Checking reconstruction
X_rec = scaler.inverse_transform(X_scaled)

错误X_rec-X将为零。您可以根据需要调整feature_range,甚至可以使用标准缩放器sk.StandardScaler()


我试着遵循这个方法,但得到了错误

TypeError: ufunc 'true_divide' output (typecode 'd') could not be coerced to provided output parameter (typecode 'l') according to the casting rule ''same_kind''

我试图规范化的numpy数组是一个整数数组。似乎他们在> 1.10版本中弃用了类型强制转换,你必须使用numpy.true_divide()来解决这个问题。

arr = np.array(img)
arr = np.true_divide(arr,[255.0],out=None)

img是PIL。图像对象。


您正在尝试将音频的值在-1到+1之间,图像的值在0到255之间进行最小-最大缩放。

使用sklearn.preprocessing。Minmax_scale应该很容易解决您的问题。

例如:

audio_scaled = minmax_scale(audio, feature_range=(-1,1))

and

shape = image.shape
image_scaled = minmax_scale(image.ravel(), feature_range=(0,255)).reshape(shape)

注意:不要与将向量的范数(长度)缩放到某个值(通常为1)的操作混淆,这也通常被称为归一化。


这个类似问题的答案为我解决了这个问题

np.interp(a, (a.min(), a.max()), (-1, +1))