将单个图像作为输入传递到CNN分类器

时间:2020-04-27 08:34:08

标签: keras

我正在尝试将图像分类为“是”“否”类别。到目前为止,我的代码如下所示,但是,我想知道在训练模型后如何在测试目录下对图像进行分类(位于'datasetfinal / test_set / Y1.jpg')。我刚刚开始尝试使用cnn,因此即使我的问题似乎很小且很愚蠢,也请帮助我。预先谢谢你。

classifier = Sequential()    
classifier.add(Convolution2D(32, 3, 3, input_shape = (64, 64, 3), activation = 'relu'))    
classifier.add(MaxPooling2D(pool_size = (2, 2)))    
classifier.add(Flatten())    
classifier.add(Dense(output_dim = 128, activation = 'relu'))    
classifier.add(Dropout(0.50))    
classifier.add(Dense(output_dim = 1, activation = 'sigmoid'))

classifier.compile(optimizer = 'adam', loss = 'binary_crossentropy', metrics = ['accuracy'])


from keras.preprocessing.image import ImageDataGenerator    
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('datasetfinal/training_set',
                                                 target_size = (64, 64),
                                                 batch_size = 32,
                                                 class_mode = 'binary')    
test_set = test_datagen.flow_from_directory('datasetfinal/test_set',
                                            target_size = (64, 64),
                                            batch_size = 32,
                                            class_mode = 'binary')

classifier.fit_generator(training_set,
                         samples_per_epoch = 8000,
                         nb_epoch = 5,
                         validation_data = test_set,
                         nb_val_samples = 2000)

1 个答案:

答案 0 :(得分:0)

您的模型需要输入4维(batch, img_height, img_width, channel),因此只需读取图像,将尺寸调整为64 x 64并扩展尺寸即可。

import cv2

img = cv2.resize(cv2.imread('test.jpg'), (64,64)).reshape(1,64,64,3)

cl = classifier.predict(img)

print(cl)