首页 > 解决方案 > 检查输入时出错:预期 conv2d_1_input 的形状为 (64, 64, 3) 但得到的数组的形状为 (64, 64, 4)

问题描述

我的图像分类模型如下所示。使用预测功能时,它会出现以下错误:

ValueError:检查输入时出错:预期 conv2d_1_input 的形状为 (64, 64, 3) 但得到的数组的形状为 (64, 64, 4)

模型如下图:

# Importing the Keras libraries and packages
from keras.models import Sequential
from keras.layers import Conv2D
from keras.layers import MaxPooling2D
from keras.layers import Flatten
from keras.layers import Dense
# Initialising the CNN
classifier = Sequential()
# Step 1 - Convolution
classifier.add(Conv2D(32, (3, 3), input_shape = (64, 64, 3), activation = 'relu'))
# Step 2 - Pooling
classifier.add(MaxPooling2D(pool_size = (2, 2)))
# Adding a second convolutional layer
classifier.add(Conv2D(32, (3, 3), activation = 'relu'))
classifier.add(MaxPooling2D(pool_size = (2, 2)))
# Step 3 - Flattening
classifier.add(Flatten())
# Step 4 - Full connection
classifier.add(Dense(units = 128, activation = 'relu'))
classifier.add(Dense(units = 1, activation = 'sigmoid'))
# Compiling the CNN
classifier.compile(optimizer = 'adam', loss = 'binary_crossentropy', 
metrics = ['accuracy'])

# Part 2 - Fitting the CNN to the images
from keras.preprocessing.image import ImageDataGenerator
import pickle
train_datagen = ImageDataGenerator(rescale = 1./255,
shear_range = 0.2,
zoom_range = 0.2,
horizontal_flip = True)
test_datagen = ImageDataGenerator(rescale = 1./255)
training_set = train_datagen.flow_from_directory('Dataset/training_data',
target_size = (64, 64),batch_size = 32,class_mode = 'binary')
test_set = test_datagen.flow_from_directory('Dataset/test_data',
target_size = (64, 64),batch_size = 32,class_mode = 'binary')
classifier.fit_generator(training_set,
steps_per_epoch = 350,epochs = 2,validation_data = test_set,validation_steps 
= 101)

predict 函数如下所示: 我使用了 requests 包,因为我想使用图像的 url 进行预测。

import requests
from io import BytesIO
from PIL import Image
import numpy as np
from keras.preprocessing import image
import cv2

 url='http://answers.opencv.org/upfiles/logo_2.png'
 response = requests.get(url)
 img = Image.open(BytesIO(response.content))
 #file = cv2.imread(img)
 img = img.resize((64,64))
 x = image.img_to_array(img)
 x = np.expand_dims(x, axis=0)
 result = classifier.predict(x)
 #training_set.class_indices
 if result[0][0] == 1:
      prediction = 'signature'
 else:
      prediction = 'nonsignature'



 print(prediction)

是否有另一种方法只使用一个包而不是 PIL 和 keras

感谢帮助!!

标签: pythonimagekeraspython-imaging-librarycv2

解决方案


错误消息不言自明。您的网络需要具有 3 个颜色通道 ( RGB) 的图像,但您正在为其提供具有 4 个通道的图像。您正在使用 png 图像,因此图像可能是RGBA格式的,第四个通道是透明通道。

PIL 图像可以转换RGB为如下格式:

img = img.convert(mode='RGB')
x = image.img_to_array(img)

x.shape
> (64, 64, 3)

但是,这种转换可能不会给出想要的结果(例如背景是黑色的)。您可以参考此问题了解其他转换为RGB.

您还可以使用load_imgKeras 预处理模块中的函数:

import keras
img = keras.preprocessing.image.load_img(io.BytesIO(response.content))

这将以RGB格式加载图像。此函数在后台使用 PIL 并产生与上述相同的结果。


推荐阅读