Skip to main content
 首页 » 编程设计

python之python中图像数组的居中

2024年10月17日7三少

我有一组图像要提供给 TensorFlow。我想使图像围绕均值居中并标准化标准差。我跟着 this answer 但我似乎无法将均值归零。我正在学习 numpy,所以也许我遗漏了一些简单的东西。

我当前的代码是:

import numpy as np 
 
# Load pickled data 
import pickle 
 
# TODO: Fill this in based on where you saved the training and testing data 
 
training_file = 'train.p' 
 
with open(training_file, mode='rb') as f: 
    train = pickle.load(f) 
 
X_train, y_train = train['features'], train['labels'] 
 
# Let us inspect whether the data is centered. 
for ch in range(3): 
    print("for channel %s mean or clahe data: %s" %( 
            ch, X_train[:,ch].mean())) 
 
X_norm = np.copy(X_train) 
for ch in range(3): 
    X_norm[:, ch] = (X_norm[:, ch] - X_norm[:,ch].mean())/ X_norm[:, ch].std() 
 
# Let us inspect our new mean. 
for ch in range(3): 
    print("for channel %s new mean for CLAHE data: %s new std: %s" % ( 
            ch, X_norm[:,ch].mean(), X_norm[:,ch].std())) 

选取的数据集可以从here获取

输出:

for channel 0 mean or clahe data: 88.9090870931 
for channel 1 mean or clahe data: 88.2472258708 
for channel 2 mean or clahe data: 87.5765175619 
for channel 0 new mean for CLAHE data: 8.77830238806 new std: 45.7207148838 
for channel 1 new mean for CLAHE data: 8.79695563094 new std: 45.7780456089 
for channel 2 new mean for CLAHE data: 8.71418658131 new std: 45.5661789057 

我想要的结果是每个 channel 的平均值大约为零,标准差为 1。

请您参考如下方法:

主要问题是数组的类型为 uint8(整数 0..255)。如果不改变数组的类型,这就不能真正居中或规范化。像这样:

X_norm = np.array(X_train, dtype=np.float, copy=True) 

现在条目是 float ,所以居中和缩放工作正常。但是,您可能会耗尽内存(数组很大),因此在尝试时,我只会使用一部分数据:

X_norm = np.array(X_train[:100], dtype=np.float, copy=True) 

您的代码还有另一个问题:[:, ch] 选择器没有按照您的预期执行。它沿第二个轴(轴 = 1)而不是最后一个轴切片。你的意思是 [..., ch] 其中省略号代表“需要多少冒号”。参见 NumPy indexing .


对调试有用:print(X_norm.dtype), print(X_norm[:, 0].shape)