我的图像分类模型如下所示。使用预测功能时,出现以下错误:
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)
预测功能如下所示: 我使用了请求包,因为我想使用图像的网址进行预测。
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的另一种方法
感谢帮助!
答案 0 :(得分:0)
错误消息说明一切。您的网络需要带有3个颜色通道(RGB
)的图像,但是您正在为其提供带有4个通道的图像。您正在使用png图像,因此图像可能是RGBA
格式,第四个通道是透明通道。
PIL图像可以转换为RGB
格式,如下所示:
img = img.convert(mode='RGB')
x = image.img_to_array(img)
x.shape
> (64, 64, 3)
但是,此转换可能无法提供所需的结果(例如,背景为黑色)。您可以参考this question来了解转换为RGB
的其他方式。
您还可以使用Keras预处理模块中的load_img
功能:
import keras
img = keras.preprocessing.image.load_img(io.BytesIO(response.content))
这将以RGB
格式加载图像。此功能在引擎盖下使用PIL并产生与上述相同的结果。