Emily
Emily

Reputation: 539

Preprocessing test images using opencv for prediction

I am working on a dataset of gray images that are saved under RGB format. I trained VGG16 on this dataset, and preprocessed them this way:

train_data_gen = ImageDataGenerator(rescale=1./255,rotation_range = 20, 
                                width_shift_range = 0.2, 
                                height_shift_range = 0.2,    
                                horizontal_flip = True)

validation_data_gen = ImageDataGenerator(rescale=1./255)

train_gen= train_data_gen.flow_from_directory(trainPath,
                                          target_size=(224, 224), 
                                          batch_size = 64, 
                                          class_mode='categorical' )

validation_gen= validation_data_gen.flow_from_directory(validationPath, target_size=(224, 224), 
batch_size = 64, class_mode='categorical' )

When the training was done, both training and validation accuracy were high (92%).

In the prediction phase, I first tried to preprocess images as indicated in https://keras.io/applications/ :

img = image.load_img(img_path, target_size=(image_size,image_size))
x = image.img_to_array(img)
x = np.expand_dims(x, axis=0)
x = preprocess_input(x)

However, the test accuracy was very low! around 50%. I tried the prediction again on train and validation samples and got a low accuracy, also around 50%, which means that the problem is in the prediction phase.

Instead, I preprocessed images using OpenCV library, and the accuracy was better, but still not as expected. I tried to make the prediction on train samples (where accuracy during training was 92%), and during the prediction I got 82%. Here is the code:

        img = cv2.imread(imagePath)
        #np.flip(img, axis=-1)
        img= cv2.resize(img, (224, 224),
                                 interpolation = cv2.INTER_AREA)
        img = np.reshape(img, 
              (1, img.shape[0], img.shape[1], img.shape[2]))

        img = img/255.

The result is the same with/without flipping the image. What's wrong with the preprocessing step? Thanks

Upvotes: 1

Views: 675

Answers (1)

Emily
Emily

Reputation: 539

The error was in the interpolation parameter of resize function. It should be cv2.INTER_NEAREST instead of cv2.INTER_AREA.

Upvotes: 1

Related Questions