The Wayback Machine - https://web.archive.org/web/20240903180652/https://www.geeksforgeeks.org/detecting-covid-19-from-chest-x-ray-images-using-cnn/
Open In App

Detecting COVID-19 From Chest X-Ray Images using CNN

Last Updated : 15 Mar, 2024
Comments
Improve
Suggest changes
Like Article
Like
Save
Share
Report
News Follow

A Django Based Web Application built for the purpose of detecting the presence of COVID-19 from Chest X-Ray images with multiple machine learning models trained on pre-built architectures. Three different machine learning models were used to build this project namely Xception, ResNet50, and VGG16. The Deep Learning model was trained on a publicly available dataset, the SARS-COV-2-Ct-Scan Dataset. The purpose of this project is to apply Convolutional Neural Network (CNN) Architectures in solving problems of the pandemic on a preliminary stage.

Tools and Technologies Used

Some important libraries and technologies used are listed below

  • Programming Language: Python
  • Web Framework: Django
  • Machine Learning Framework: Tensorflow
  • Frontend Dev: HTML, CSS (BootStrap)
  • Essential Libraries: keras, sklearn, venv, seaborn, matplotlib

A detailed list of all the libraries can be found here.

Step by Step Implementation

Deep Learning Part

1) Convert Dataset into Dataframe

  • Convert the data into a pandas dataframe with the corresponding columns
    • File [Image File]
    • DiseaseID [Serial Number]
    • DiseaseType [COVID, non-COVID]
  • Python3




    train_dir = 'path/to/dataset'
    train_data = []
      
    for defects_id, sp in enumerate(disease_types):
        for file in os.listdir(os.path.join(train_dir, sp)):
            train_data.append(['{}/{}'.format(sp, file), defects_id, sp])
              
    train = pd.DataFrame(train_data, columns=['File', 'DiseaseID', 'Disease Type'])

    
    

    2) Read and Preprocess the Dataframe

    • Read the Images
    • Convert the Images into the standard size of (64 x 64)
    • Create numpy arrays for input/output X_Train & Y_Train
    • Normalize the RGB values by dividing with 255.

    Python3




    IMAGE_SIZE = 64
      
    def read_image(filepath):
        return cv2.imread(os.path.join(data_dir, filepath))
      
    def resize_image(image, image_size):
        return cv2.resize(image.copy(), image_size, 
                          interpolation=cv2.INTER_AREA)
      
    X_train = np.zeros((train.shape[0], IMAGE_SIZE, IMAGE_SIZE, 3))
      
    for i, file in tqdm(enumerate(train['File'].values)):
        image = read_image(file)
        if image is not None:
            X_train[i] = resize_image(image, (IMAGE_SIZE, IMAGE_SIZE))
              
    X_Train = X_train / 255.
      
    Y_train = train['DiseaseID'].values
    Y_train = to_categorical(Y_train, num_classes=2)

    
    

    3) Split the Dataset into Train/Validation

    • Split into Train, Validation datasets
    • Select split percentage & random state accordingly

    Python3




    X_train, X_val, Y_train, Y_val = train_test_split(
      X_Train, Y_train, test_size=0.2, random_state = 42)

    
    

    4) Define Model Architecture

    • We are going to import three different architectures listed below :
      • VGG16
      • ResNet50
      • Xception
    • Structure of Model Architecture
      • Conv2D of Input Shape (3,3)
      • ResNet50/Xception/VGG16 Architecture
      • Add a GlobalAveragePooling2D()
      • Add a Dropout Layer
      • Final DenseNet Layer with relu activation
      • For Multiple Output add a Softmax layer
    • Use an ‘adam’ optimizer, hyperparameters can be tuned accordingly
    • The following code proposes a sample code for building a model

    Python3




    def build_model():
      
        # Use Any One of the Following Lines
        resnet50 = ResNet50(weights='imagenet', include_top=False)
        xception = Xception(weights='imagenet', include_top=False)
        vgg16 = VGG16(weights='imagenet', include_top=False)
      
        input = Input(shape=(SIZE, SIZE, N_ch))
        x = Conv2D(3, (3, 3), padding='same')(input)
      
        # Use Any One of the Following Lines
        x = resnet50(x)
        x = xception(x)
        x = vgg16(x)
      
        x = GlobalAveragePooling2D()(x)
        x = BatchNormalization()(x)
        x = Dropout(0.5)(x)
        x = Dense(256, activation='relu')(x)
        x = BatchNormalization()(x)
        x = Dropout(0.5)(x)
      
        # multi output
        output = Dense(2, activation='softmax', name='root')(x)
      
        # model
        model = Model(input, output)
      
        optimizer = Adam(lr=0.003, beta_1=0.9, beta_2=0.999,
                         epsilon=0.1, decay=0.0)
          
        model.compile(loss='categorical_crossentropy',
                      optimizer=optimizer, metrics=['accuracy'])
          
        model.summary()
      
        return model

    
    

    5) Train the Model

    • Call build_model() function
    • Use an annealer, a callback that monitors a quantity and if no improvement is seen for a ‘patience’ number of epochs, the learning rate is reduced.
    • Use an ImageDataGenerator to carry out real time image data augmentation
    • Train the model on x_train, y_train
    • Save the model weights in .hdf5 format and model graph in .json format

    Python3




    # Use Any one of the Lines Below
    hdf5_save = 'ResNet50_Model.hdf5'
    hdf5_save = 'Xception_Model.hdf5'
    hdf5_save = 'VGG16_Model.hdf5'
      
    model = build_model()
    annealer = ReduceLROnPlateau(
        monitor='val_accuracy', factor=0.70, patience=5,
        verbose=1, min_lr=1e-4)
      
    checkpoint = ModelCheckpoint(h5f5_save, verbose=1, save_best_only=True)
      
    datagen = ImageDataGenerator(rotation_range=360,
                                 width_shift_range=0.2,
                                 height_shift_range=0.2,
                                 zoom_range=0.2,
                                 horizontal_flip=True,
                                 vertical_flip=True)
      
    datagen.fit(X_train)
      
    # Use Any one of the lines Below
    model_graph = 'ResNet50.json'
    model_graph = 'Xception.json'
    model_graph = 'VGG16.json'
      
    model_json = model.to_json()
    with open(model_graph, "w") as json_file:
        json_file.write(model_json)

    
    

    Building the Web App

    • Create a Django Project with an application initialized inside it which would be using the saved model weights to predict uploaded Chest X-Ray Images
    • Create a basic Static Page with a form to send the image file to the backend

    HTML




    <form method="post" id="imageForm" enctype="multipart/form-data">
       {% csrf_token %}
       <label for="ImgFile">Upload Image</label>
       <input type="file" name="ImgFile" class="form-control"/>
       <input type="submit" id="submitButton" class="btn" name="submit" value="Solve"/>
    </form>

    
    

    • Inside the views.py folder, handle the uploaded image. Load the model files and send the response back to the front end.
    • The response would contain the following details
      • Model Prediction
      • Confidence Score
      • Prediction Duration (in s)
    • Add styling to the frontend using CSS (Bootstrap) accordingly

    Note: Loading multiple models and using model.predict() takes a lot of time and it’d be much more in the absence of GPU services in the Cloud instance. For scaling this application to a higher server load consider using TensorFlow Serving

    Demo

    A Demo Version of the project built and tested on localhost is demonstrated in the video below

    COV-CNN Demo

    Applications in Real Life & Future Work

    The project built in the previous lines cannot be directly applied, however, a lot of such applications can be built on a similar tangent for serving the purpose of preliminary medical diagnosis based on inputs of patients saving a lot of screening stage costs to the medical industry. The machine learning pipeline presented in the project can be taken up a notch by making it dynamic in nature. By adding more training data dynamically to the model and train it on them to improve its accuracy. The ML Model can be converted into a REST API making the application more robust in nature and scalable. A MySQL Database could be used for storing patient data with diagnosis details and other parameters. I’ve presented a use-sketch diagram for illustrating the architecture of the application which could be built in the near future to be applied in the medical industry.

    Resources



    Previous Article
    Next Article

    Similar Reads

    Detecting Covid-19 with Chest X-ray
    COVID-19 pandemic is one of the biggest challenges for the healthcare system right now. It is a respiratory disease that affects our lungs and can cause lasting damage to the lungs that led to symptoms such as difficulty in breathing and in some cases pneumonia and respiratory failure. In this article, we will use X-ray data of lungs normal and COV
    9 min read
    What is the difference between a region-based CNN (R-CNN) and a fully convolutional network (FCN)?
    In computer vision, particularly in object detection and semantic segmentation, two prominent neural network architectures are frequently discussed: Region-based Convolutional Neural Networks (R-CNN) and Fully Convolutional Networks (FCN). Each of these architectures has distinct features and applications. This article will explore the differences
    4 min read
    How Many Images per Class Are Sufficient for Training a CNN?
    Answer: The number of images per class required for training a CNN varies depending on factors like the complexity of the task, dataset variability, and model architecture, but typically ranges from hundreds to thousands for effective learning.Determining the optimal number of images per class for training a Convolutional Neural Network (CNN) invol
    2 min read
    Detecting Spam Emails Using Tensorflow in Python
    Spam messages refer to unsolicited or unwanted messages/emails that are sent in bulk to users. In most messaging/emailing services, messages are detected as spam automatically so that these messages do not unnecessarily flood the users' inboxes. These messages are usually promotional and peculiar in nature. Thus, it is possible for us to build ML/D
    8 min read
    Detecting bills by using OpenCV
    In the field of computer vision and image processing, OpenCV (Open Source Computer Vision Library) is a powerful tool that enables a wide range of applications, from facial recognition to object detection. One interesting application of OpenCV is detecting and processing currency bills, which can be valuable in various fields including retail, bank
    8 min read
    Hyperparameter tuning with Ray Tune in PyTorch
    Hyperparameter tuning is a crucial step in the machine learning pipeline that can significantly impact the performance of a model. Choosing the right set of hyperparameters can be the difference between an average model and a highly accurate one. Ray Tune is an industry-standard tool for distributed hyperparameter tuning that integrates seamlessly
    8 min read
    Traffic Signs Recognition using CNN and Keras in Python
    We always come across incidents of accidents where drivers' Overspeed or lack of vision leads to major accidents. In winter, the risk of road accidents has a 40-50% increase because of the traffic signs' lack of visibility. So here in this article, we will be implementing Traffic Sign recognition using a Convolutional Neural Network. It will be ver
    6 min read
    Lung Cancer Detection using Convolutional Neural Network (CNN)
    Computer Vision is one of the applications of deep neural networks that enables us to automate tasks that earlier required years of expertise and one such use in predicting the presence of cancerous cells. In this article, we will learn how to build a classifier using a simple Convolution Neural Network which can classify normal lung tissues from c
    8 min read
    Pneumonia Detection Using CNN in Python
    In this article, we will learn how to build a classifier using a simple Convolution Neural Network which can classify the images of patient's xray to detect whether the patient is Normal or affected by Pneumonia. To get more understanding, follow the steps accordingly. Importing Libraries The libraries we will using are : Pandas- The pandas library
    10 min read
    Age and Gender Prediction using CNN
    In this article, we will create an Age and Gender Prediction model using Keras Functional API, which will perform both Regression to predict the Age of the person and Classification to predict the Gender from face of the person. Age and Gender PredictionKeras Functional API offers a more flexible and creative way to make models of higher complexity
    9 min read
    Text classification using CNN
    Text classification is a widely used NLP task in different business problems, and using Convolution Neural Networks (CNNs) has become the most popular choice. In this article, you will learn about the basics of Convolutional neural networks and the implementation of text classification using CNNs, along with code examples. Also, you'll learn about
    5 min read
    What is Bipolar Disorder and How Can Artificial Intelligence Help in Detecting it?
    Imagine feeling very happy and excited one second. You feel like you have unlimited energy and you can take over the world!!! Then imagine feeling sad and depressed the very next second. You feel like there is no point in doing anything and may even feel suicidal. And then feeling happy and excited again. Are you wondering what this is? How can any
    5 min read
    How does Deep Learning helps in Detecting Multiple Objects in Single Image?
    Answer: Deep Learning employs object detection algorithms, such as YOLO or SSD, to identify and localize multiple objects within a single image.Deep Learning contributes significantly to detecting multiple objects in a single image through the implementation of sophisticated object detection algorithms. Here's a detailed explanation: Convolutional
    2 min read
    Detecting ArUco markers with OpenCV and Python
    ArUco markers are widely used in computer vision applications for tasks such as camera calibration, pose estimation, and augmented reality. These markers are square fiducial markers with a unique binary pattern that can be easily detected by computer vision algorithms. In this article, we will explore how to detect ArUco markers using OpenCV and Py
    6 min read
    Detecting outliers when fitting data with nonlinear regression
    Nonlinear regression is a powerful tool used to model complex relationships between variables. However, the presence of outliers can significantly distort the results, leading to inaccurate parameter estimates and unreliable predictions. Detecting and managing outliers is therefore crucial for robust nonlinear regression analysis. This article delv
    7 min read
    Detecting Multicollinearity with VIF - Python
    Multicollinearity occurs when there are two or more independent variables in a multiple regression model, which have a high correlation among themselves. When some features are highly correlated, we might have difficulty in distinguishing between their individual effects on the dependent variable. Multicollinearity can be detected using various tec
    3 min read
    COVID-19 Data Visualization using matplotlib in Python
    It feels surreal to imagine how the virus began to spread from one person that is patient zero to four million today. It was possible because of the transport system. Earlier back in the days, we didn’t have a fraction of the transportation system we have today. Well, what good practices you can follow for now is to sanitize your grocery products a
    8 min read
    COVID-19 Peak Prediction using Logistic Function
    Making fast and accurate decisions are vital these days and especially now when the world is facing such a phenomenon as COVID-19, therefore, counting on current as well as projected information is decisive for this process. In this matter, we have applied a model in which is possible to observe the peak in specific country cases, using current sta
    4 min read
    Covid-19 Data Analysis Using Tableau
    Tableau is a software used for data visualization and analysis. it's a tool that can make data-analysis easier. Visualizations can be in the form of worksheets or dashboard. Here are some simple steps in creating worksheets and dashboard using covid-19 dataset in Tableau tool. Data link: https://data.world/covid-19-data-resource-hub/covid-19-case-c
    4 min read
    Covid-19 Analysis and Visualization using Plotly Express
    In this article, we will discuss Analyse Covid-19 data and will visualize it using Plotly Express in Python. This article deals with creating dozens of bar charts, line graphs, bubble charts, scatter plots. The graph that will be made in this project will be of excellent quality. Envisioning COVID-19 will primarily be using Plotly Express for this
    13 min read
    CNN | Introduction to Pooling Layer
    The pooling operation involves sliding a two-dimensional filter over each channel of feature map and summarising the features lying within the region covered by the filter. For a feature map having dimensions nh x nw x nc, the dimensions of output obtained after a pooling layer is (nh - f + 1) / s x (nw - f + 1)/s x nc where, -&gt; nh - height of f
    6 min read
    Convolutional Neural Network (CNN) Architectures
    Convolutional Neural Network(CNN) is a neural network architecture in Deep Learning, used to recognize the pattern from structured arrays. However, over many years, CNN architectures have evolved. Many variants of the fundamental CNN Architecture This been developed, leading to amazing advances in the growing deep-learning field. Let's discuss, How
    11 min read
    Training of Convolutional Neural Network (CNN) in TensorFlow
    In this article, we are going to implement and train a convolutional neural network CNN using TensorFlow a massive machine learning library. Now in this article, we are going to work on a dataset called 'rock_paper_sissors' where we need to simply classify the hand signs as rock paper or scissors. Stepwise ImplementationStep 1: Importing the librar
    5 min read
    Working of Convolutional Neural Network (CNN) in Tensorflow
    In this article, we are going to see the working of convolution neural networks with TensorFlow a powerful machine learning library to create neural networks. Now to know, how a convolution neural network lets break it into parts. the 3 most important parts of this convolution neural networks are, ConvolutionPoolingFlattening These 3 actions are th
    5 min read
    Convolutional Neural Network (CNN) in Tensorflow
    It is assumed that the reader knows the concepts of Neural Networks and Convolutional Neural Networks. If you are sure about the topics please refer to Neural Networks and Convolutional Neural Networks. Building Blocks of CNN: Convolutional Neural Networks are mainly made up of three types of layers: Convolutional Layer: It is the main building blo
    4 min read
    Image Segmentation with Mask R-CNN, GrabCut, and OpenCV
    Image segmentation plays a crucial role in computer vision tasks, enabling machines to understand and analyze visual content at a pixel level. It involves dividing an image into distinct regions or objects, facilitating object recognition, tracking, and scene understanding. In this article, we explore three popular image segmentation techniques: Ma
    13 min read
    Mask R-CNN | ML
    The article provides a comprehensive understanding of the evolution from basic Convolutional Neural Networks (CNN) to the sophisticated Mask R-CNN, exploring the iterative improvements in object detection, instance segmentation, and the challenges and advantages associated with each model. What is R-CNN?R-CNN, which stands for Region-based Convolut
    9 min read
    What is the use of SoftMax in CNN?
    Answer: SoftMax is used in Convolutional Neural Networks (CNNs) to convert the network's final layer logits into probability distributions, ensuring that the output values represent normalized class probabilities, making it suitable for multi-class classification tasks.SoftMax is a crucial activation function in the final layer of Convolutional Neu
    2 min read
    When are Weights Updated in CNN?
    Answer: Weights are updated in a Convolutional Neural Network (CNN) during the training phase through backpropagation and optimization algorithms, such as stochastic gradient descent, after computing the gradient of the loss with respect to the weights.In a Convolutional Neural Network (CNN), the process of updating weights occurs during the traini
    2 min read
    How to Decide Number of Filters in CNN?
    Answer: The number of filters in a CNN is often determined empirically through experimentation, balancing model complexity and performance on the validation set.Deciding the number of filters in a Convolutional Neural Network (CNN) involves a combination of domain knowledge, experimentation, and understanding of the architecture's requirements. Her
    3 min read