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

本教程将介绍ValueError:无法将大小为40000的数组重塑为形状(1,32,32,3)的处理方法,这篇教程是从别的地方看到的,然后加了一些国外程序员的疑问与解答,希望能对你有所帮助,好了,下面开始学习吧。

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

问题描述

ValueError:无法将大小为40000的数组重塑为形状(1,32,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, directory='C:/Users/henri/OneDrive/Área de Trabalho/projetos/trafficsign/Data/', x_col='Path',
 y_col='ClassId', target_size=(32, 32), batch_size=16, class_mode='categorical')

model = Sequential()
model.add(Conv2D(64, kernel_size=(3, 3), input_shape=(32, 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, 32, 32, 3))

print(pred.argmax())

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

推荐答案

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

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

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

好了关于ValueError:无法将大小为40000的数组重塑为形状(1,32,32,3)的教程就到这里就结束了,希望趣模板源码网找到的这篇技术文章能帮助到大家,更多技术教程可以在站内搜索。