0
votes

ValueError: cannot reshape array of size 40000 into shape (1,32,32,3)

I'm trying to build an Interface with the Trafficsign dataset, but the input image that i'm trying to go through the nn are not in the correct input shape (1, 32, 32, 3). Pls help me, I'm trying it in a long time

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()```
1
Why did you comment #resize = cv2.resize(imgplot, (32, 32)) ? - Lescurel

1 Answers

0
votes

If size of image data is 40000 and not equal 1x32x32x3 (One image with width and height, 32 x 32, and RGB format), you reshape it and then got the error.

>>> 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

You may need to resize image to 32x32 RGB firstly.