Table of Contents

Image Classification – Pneumonia with File – Python

Example Description
The example shows how to run image classification in Python on an image file using OpenCV.

Image Classification Model

 

Code

####################imports####################
#do not change

import cv2
import numpy as np
import tensorflow as tf

#do not change
####################imports####################

#Following are the model and video capture configurations
#do not change

model = tf.keras.models.load_model('saved_model.h5',
                                   custom_objects=None,
                                   compile=True,
                                   options=None)

text_color = (206, 235, 135)
org = (50, 50)
font = cv2.FONT_HERSHEY_SIMPLEX
fontScale = 0.5
thickness = 1

class_list = ['Bacteria', 'Normal', 'Virus']  # List of all the classes

#do not change
###############################################

image_np = cv2.imread("test.jpg", cv2.IMREAD_COLOR)
image_resized = cv2.resize(image_np, (224, 224))
img_array = tf.expand_dims(image_resized,
                           0)  # Expanding the image array dimensions
predict = model.predict(img_array)  # Making an initial model prediction
predict_index = np.argmax(predict[0],
                          axis=0)  # Generating index out of the prediction
predicted_class = class_list[
    predict_index]  # Tallying the index with class list

image_np = cv2.putText(image_np,
                       "Image Classification Output: " + str(predicted_class),
                       org, font, fontScale, text_color, thickness,
                       cv2.LINE_AA)

print(predict)
cv2.imshow("Image Classification Window",
           image_np)  # Displaying the classification window

cv2.imwrite("TestResult.jpg", image_np)
cv2.waitKey(0)
cv2.destroyAllWindows()