SURAJ GEHLOT
Published © GPL3+

Detection of COVID-19 Presence Using Chest X-Rays Scans

My idea presents a deep neural network model to classify images for COVID-19 presence, viral pneumonia or normal from chest X-rays datasets.

IntermediateShowcase (no instructions)2 days1,904
Detection of COVID-19 Presence Using Chest X-Rays Scans

Things used in this project

Hardware components

Android device
Android device
×1

Software apps and online services

Jupyter Notebook
Jupyter Notebook
To develop a deep neural network model to classify images.
Android Studio
Android Studio
To develop lite weight android application that uses trained model to test Chest X-rays images.
TensorFlow
TensorFlow
To develop model using tensorflow model: mobilenet_ssd

Story

Read more

Schematics

Block Diagram

How CNN extracts each features

Model Summary

Model Accuracy

Tensorflow training and loss graph

Deployment on Edge Device

Android Application Test Result

Model can classify between covid19, viral pneumonia and normal chest X-Rays as seen in three images.

Code

covid19_classification.py

Python
"""

Project : Detection of Covid19 Presence from Chest X-Rays Scans
Participant: Suraj Gehlot
Mail: suraj.gehlot@somaiya.edu
Githhub: github.com/enggsuraj/covid19_classification.git

Original file is located at: colab.research.google.com/drive/1LjxxXFCfkpzsC7WSlwe3gDAHWLcCHP28

**Covid19 Chest Xray Classification Model**

Three Classification

1. COVID-19
2. NORMAL
3. VIRAL PNEUMONIA

Steps:
1. Examine and understand data
2. Build an input pipeline
3. Build the model
4. Train the model
5. Test the model
6. Improve the model and repeat the process

Note: This is only training model model, android app building is done after exporting model to android studio.

"""

import tensorflow as tf
print(tf.__version__)
import datetime
from tensorflow.keras.models import Sequential
from tensorflow.keras.layers import Dense, Conv2D, Flatten, Dropout, MaxPooling2D
from tensorflow.keras.preprocessing.image import ImageDataGenerator

import os
import numpy as np
import matplotlib.pyplot as plt

# IMPORTING IMAGE DATASETS FROM GOOGLE DRIVE
from google.colab import drive
drive.mount('/content/gdrive')

import os
import shutil

PATH='/content/gdrive/My Drive/ML'

#install PyDrive so we can upload our dataset from Google Drive
!pip install PyDrive

base_dir = os.path.join(PATH, 'Covid19')
print(base_dir)

BATCH_SIZE = 100
epochs = 5
IMAGE_SIZE = 224
IMAGE_SIZE = 224

#ARRANGING DATASETS
datagen = tf.keras.preprocessing.image.ImageDataGenerator(
    rescale=1./255, 
    validation_split=0.2)

train_generator = datagen.flow_from_directory(
    base_dir,
    target_size=(IMAGE_SIZE, IMAGE_SIZE),
    batch_size=BATCH_SIZE, 
    subset='training')

val_generator = datagen.flow_from_directory(
    base_dir,
    target_size=(IMAGE_SIZE, IMAGE_SIZE),
    batch_size=BATCH_SIZE, 
    subset='validation')

for image_batch, label_batch in train_generator:
  break
image_batch.shape, label_batch.shape

print (train_generator.class_indices)

labels = '\n'.join(sorted(train_generator.class_indices.keys()))

with open('labels.txt', 'w') as f:
  f.write(labels)

sample_training_images, _ = next(train_generator)

def plotImages(images_arr):
    fig, axes = plt.subplots(1, 5, figsize=(20,20))
    axes = axes.flatten()
    for img, ax in zip( images_arr, axes):
        ax.imshow(img)
        ax.axis('off')
    plt.tight_layout()
    plt.show()

plotImages(sample_training_images[:5])



#CREATING MODEL
# Mobilenet_ssd
IMG_SHAPE = (IMAGE_SIZE, IMAGE_SIZE, 3)

# Create the base model from the pre-trained model MobileNet V2
base_model = tf.keras.applications.MobileNetV2(input_shape=IMG_SHAPE,
                                              include_top=False, 
                                              weights='imagenet')

base_model.trainable = False

#ADD OWN DENSE LAYER
model = tf.keras.Sequential([
  base_model,
  tf.keras.layers.Conv2D(512, 3, activation='relu'),
  tf.keras.layers.Dropout(0.2),
  tf.keras.layers.GlobalAveragePooling2D(),
  tf.keras.layers.Dense(3, activation='softmax')
])

model.compile(optimizer=tf.keras.optimizers.Adam(), 
              loss='categorical_crossentropy', 
              metrics=['accuracy'])

model.summary()

ACCURACY_THRESHOLD = 0.90

class myCallback(tf.keras.callbacks.Callback):
	def on_epoch_end(self, epoch, logs={}):
		if(logs.get('acc') > ACCURACY_THRESHOLD):
			print("\nReached %2.2f%% accuracy, so stopping training!!" %(ACCURACY_THRESHOLD*100))
			self.model.stop_training = True

# Instantiate a callback object
callbacks = myCallback()

logdir = os.path.join("logs", datetime.datetime.now().strftime("%Y%m%d-%H%M%S"))
tensorboard_callback = tf.keras.callbacks.TensorBoard(logdir, histogram_freq=1)

#TRAINING
model.fit_generator(train_generator, 
                    epochs=epochs, 
                    validation_data=val_generator)

from keras.preprocessing.image import ImageDataGenerator, load_img, img_to_array
import matplotlib.image as mpimg

#TESTING
img=mpimg.imread('/content/gdrive/My Drive/ML/Covid19/COVID19/COVID-19 (1).png')
imgplot = plt.imshow(img)
plt.show()

#TESTING
x = load_img('/content/gdrive/My Drive/ML/Covid19/COVID19/COVID-19 (1).png', target_size=(IMAGE_SIZE,IMAGE_SIZE))
x = img_to_array(x)
x = np.expand_dims(x, axis=0)
array = model.predict(x)
result = array[0]
print(array)
answer = np.argmax(result)
print(answer)

#SAVING MODEL
saved_model_dir = 'save/fine_tuning'
tf.saved_model.save(model, saved_model_dir)

converter = tf.lite.TFLiteConverter.from_saved_model(saved_model_dir)
tflite_model = converter.convert()

with open('model.tflite', 'wb') as f:
  f.write(tflite_model)

from google.colab import files

files.download('model.tflite')
files.download('labels.txt')

# AFTER THIS model.tflite and label.txt are deployed in tensorflow based classification code in android studio

Covid19, Pneumonia and Normal X-Rays Classification Code

Model Training Python Script trained for 150 images.

Credits

SURAJ GEHLOT

SURAJ GEHLOT

1 project • 5 followers

Comments