My model for classifying images is shown below.When using the predict function it is giving the below error:
ValueError: Error when checking input: expected conv2d_1_input to have shape (64, 64, 3) but got array with shape (64, 64, 4)
The model is as shown below:
# 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)
The predict function is shown below: I have used requests package since I want to use a url of an image for prediction.
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)
Is there an alternate way using only one package instead of PIL and keras
Thanks for help!!