ValueError:无法将大小为 40000 的数组重塑为形状 (1,32,32,3)

问题描述

ValueError: 无法将大小为 40000 的数组重塑为形状 (1,32,3)

我正在尝试使用 Trafficsign 数据集构建接口,但是我尝试通过 nn 的输入图像的输入形状不正确(1、32、32、3)。请帮帮我,我试了很久

import pandas as pd
from tensorflow.keras.models import Sequential
from tensorflow.keras.layers import Dense,Conv2D,Flatten,MaxPooling2D
from PIL import Image
from tensorflow.keras.preprocessing import image
import matplotlib.pyplot as plt
import PySimpleGUI as sg
import cv2
import numpy as np



pd.set_option('mode.chained_assignment',None)

train_data = pd.read_csv("C:/Users/henrI/OneDrive/Área de Trabalho/projetos/trafficsign/Data/Train.csv")
train_data['ClassId'] = train_data['ClassId'].astype(str)
for i in range(0,len(train_data['ClassId'])):
    if len(train_data['ClassId'][i]) == 1:
        train_data['ClassId'][i] = '0' + train_data['ClassId'][i]


test_data = pd.read_csv("C:/Users/henrI/OneDrive/Área de Trabalho/projetos/trafficsign/Data/Test.csv")
test_data['ClassId'] = test_data['ClassId'].astype(str)
for i in range(0,len(test_data['ClassId'])):
    if len(test_data['ClassId'][i]) == 1:
        test_data['ClassId'][i] = '0' + test_data['ClassId'][i]

img = Image.open('C:/Users/henrI/OneDrive/Área de Trabalho/projetos/trafficsign/Data/' + train_data['Path'][2])

pre_train = image.ImageDataGenerator(rescale=1./255,shear_range=0.2)
pre_test = image.ImageDataGenerator(rescale=1./255)

gen_train = pre_train.flow_from_dataframe(
    dataframe=train_data,directory='C:/Users/henrI/OneDrive/Área de Trabalho/projetos/trafficsign/Data/',x_col='Path',y_col='ClassId',target_size=(32,32),batch_size=128,class_mode='categorical'
)

gen_test = pre_test.flow_from_dataframe(
    dataframe=test_data,batch_size=16,class_mode='categorical')

model = Sequential()
model.add(Conv2D(64,kernel_size=(3,3),input_shape=(32,3)))
model.add(MaxPooling2D(pool_size=(2,2)))
model.add(Flatten())
model.add(Dense(64,activation=tf.nn.relu))
model.add(Dense(43,activation=tf.nn.softmax))

model.compile(optimizer='adam',loss='categorical_crossentropy',metrics=['accuracy'])

model.fit(gen_train,verbose=1,epochs=1)

#model.save('model_trained')
filename = sg.popup_get_file('Enter the file you wish to process')
imgplot = plt.imread(filename)


#grey_img = cv2.cvtColor(imgplot,cv2.COLOR_BGR2GRAY)
#resize = cv2.resize(imgplot,(32,32))

pred = model.predict(imgplot.reshape(1,3))

print(pred.argmax())

imgplot = plt.imread(filename)
plt.imshow(imgplot)
plt.show()```

解决方法

如果图像数据的大小为 40000 且不等于 1x32x32x3(一张具有宽度和高度、32 x 32 和 RGB 格式的图像),则对其进行整形,然后出现错误。

>>> import numpy as np
>>> a = np.array([1 for i in range(40000)],dtype=np.int8)
>>> a.size
40000
>>> a.reshape((1,32,3))
Traceback (most recent call last):
  File "<interactive input>",line 1,in <module>
ValueError: cannot reshape array of size 40000 into shape (1,3)
>>> 40000 != 1*32*32*3
True

您可能需要先将图像大小调整为 32x32 RGB。