Python 如何重塑图像的尺寸以同时包含图像的数量(即1)?

Python 如何重塑图像的尺寸以同时包含图像的数量(即1)?,python,pandas,dimensions,Python,Pandas,Dimensions,我正在一些图像上运行一个神经网络模型。最初,为了进行训练,我将所有图像转换成一个维度为(#数据集中的图像)x r x g x b的数据框,其中r,g,b是每个图像的颜色值。现在,当我尝试在单个外部下载的图像上测试模型时,它给出了一个维度错误,因为很明显,图像的维度仅为rxgxb。如何将图像数量作为维度添加到此图像中 编辑:以下是代码: #load the data as a pandas data frame import pandas as pd dataset = pd.read_csv(o

我正在一些图像上运行一个神经网络模型。最初,为了进行训练,我将所有图像转换成一个维度为
(#数据集中的图像)x r x g x b
的数据框,其中
r
g
b
是每个图像的颜色值。现在,当我尝试在单个外部下载的图像上测试模型时,它给出了一个维度错误,因为很明显,图像的维度仅为
rxgxb
。如何将图像数量作为维度添加到此图像中

编辑:以下是代码:

#load the data as a pandas data frame
import pandas as pd
dataset = pd.read_csv(os.path.join(data_path, 'data.csv'))

# split into input (X) and output (Y) variables
X = dataset.values[:,0]
Y = dataset.values[:,1]

# Load all the images and resize them into a single numpy array of consistent dimension
from scipy.misc import imresize
from scipy.misc import imread
import numpy as np

temp = []
for img_name in X:
    img_path = os.path.join(data_dir, 'Train', img_name)
    img = imread(img_path)
    img = imresize(img, (32, 32))
    img = img.astype('float32')
    temp.append(img)

X = np.stack(temp)

# Convert the data classes from words into a number format readable by the program
from sklearn.preprocessing import LabelEncoder
lb = LabelEncoder()
Y = lb.fit_transform(Y)
Y = keras.utils.np_utils.to_categorical(Y)

# Split the data into 67% for training and 33% for testing
X_train, X_test, Y_train, Y_test = train_test_split(X, Y, test_size=0.33)

### Define the neural network model
### Compile and train the model on the data
### Evaluate it

# Test it on an externally downloaded image
img = imread(os.path.join(image_folder, downloaded_image)).astype('float32')
plt.imshow(imresize(img, (128, 128)))

print('X_train shape: ', X_train.shape)
print('Downloaded image shape: ', img.shape)
这将返回:

X_train shape: (13338, 32, 32, 3)
Downloaded image shape: (448, 720, 3)
ValueError: Error when checking : expected conv2d_71_input to have 4 dimensions, but got array with shape (960, 640, 3)
我想将下载图像的形状设置为(1448720,3),以便与
X\u train
形状的尺寸匹配,因为当我尝试预测下载图像的类别时,它会返回一个尺寸错误:

pred = cnn_model.predict_classes(img)
print('Predicted:', lb.inverse_transform(pred))
这将返回:

X_train shape: (13338, 32, 32, 3)
Downloaded image shape: (448, 720, 3)
ValueError: Error when checking : expected conv2d_71_input to have 4 dimensions, but got array with shape (960, 640, 3)

从您的描述来看,似乎您并不是真的想将图像数量用作特征,而是作为样本权重。从概念上讲,您可能想要转换

k x r x g x b

这自然会使输入和输出维度相同,BTW.,如果这增加了学习时间太多,并且你的库有一个样本权重参数,你应该考虑使用它。


如果您只想在技术上添加维度,可以使用:


但是,我不能说我肯定这就是您所需要的。

您使用哪个库来实现这一点?用于将图像转换为数据帧?只是熊猫。对不起,我的意思是你用哪个库来制作神经网络。Keras及其子模块,后台是tensorflow。谢谢你的回答,但我不想重复/替换以前的所有代码。我已经编辑了这个问题,添加了一些关于代码的细节。我只是在寻找一种方法,使维度相等,以便代码运行。