🦠 COVID-19 X-ray Classification System
An advanced AI-powered web application for analyzing chest X-ray images to detect COVID-19, Normal, Lung Opacity, and Viral Pneumonia conditions using deep learning and Grad-CAM visualization.
🚀 Features
🔬 AI-Powered Analysis : Deep learning model based on DenseNet architecture
🎯 Multi-Class Classification : Detects 4 different lung conditions
🔥 Grad-CAM Visualization : Heatmap generation for model interpretability
📊 Prediction History : Track and view all previous predictions
🌐 Web Interface : Beautiful, responsive web UI
📱 Mobile Friendly : Works seamlessly on all devices
⚡ Fast API : RESTful API endpoints for integration
📈 Real-time Results : Instant analysis with confidence scores
📋 Table of Contents
🛠️ Installation
Prerequisites
Python 3.8 or higher
4GB+ RAM (for model inference)
Modern web browser
Setup
Clone the repository
1 git clone https://github.com/yourusername/covid19-xray-classifier.git
2 cd covid19-xray-classifier
Create virtual environment
1 python -m venv venv
2 source venv/bin/activate # On Windows: venv\Scripts\activate
Install dependencies
pip install -r requirements.txt
Download the model (if not included)
1 # The model file should be in the root directory
2 # covid_model.pth (27MB)
Run the application
The application will be available at http://localhost:8000
🎯 Usage
Web Interface
Open your browser and navigate to http://localhost:8000
Upload an X-ray image using the file upload button
Click "Analyze Image" to process the image
View results including:
Predicted class (COVID-19, Normal, Lung Opacity, Viral Pneumonia)
Confidence score
Original image
Grad-CAM heatmap visualization
Download option for heatmap
API Usage
Predict Image
1 curl -X POST "http://localhost:8000/predict" \
2 -H "Content-Type: multipart/form-data" \
3 -F "file=@your_xray_image.jpg"
Health Check
curl "http://localhost:8000/health"
Get Available Classes
curl "http://localhost:8000/api/classes"
📚 API Documentation
Endpoints
Endpoint Method Description /GET Main upload form page /historyGET Prediction history page /predictPOST JSON API for predictions /predict_htmlPOST HTML response with results /healthGET Health check endpoint /api/classesGET Available classification classes
Response Format
1 {
2 "class_index" : 0 ,
3 "class_name" : "COVID-19" ,
4 "confidence" : 0.95 ,
5 "heatmap_url" : "/static/heatmaps/abc123.jpg"
6 }
🧠 Model Architecture
Deep Learning Model
Architecture : DenseNet-121 (modified)
Input Size : 224x224 pixels
Classes : 4 (COVID-19, Normal, Lung Opacity, Viral Pneumonia)
Training : Transfer learning with medical imaging data
Framework : PyTorch
Model Performance
Accuracy : ~95% on test set
Inference Time : <2 seconds per image
Memory Usage : ~500MB RAM
Grad-CAM Implementation
Purpose : Model interpretability and visualization
Method : Gradient-weighted Class Activation Mapping
Output : Heatmap overlay on original image
Benefits : Understand model decision-making process
📊 Dataset
The model was trained on the COVID-19 Radiography Database containing:
Class Images Description COVID-19 3,616 Confirmed COVID-19 cases Normal 10,192 Healthy chest X-rays Lung Opacity 6,012 Non-COVID lung infections Viral Pneumonia 1,345 Other viral pneumonia cases
Total : 21,165 chest X-ray images
Data Preprocessing
Resize to 224x224 pixels
Normalize pixel values
Data augmentation during training
Train/validation/test split: 70/15/15
📁 Project Structure
covid19-xray-classifier/
├── 📄 main.py # FastAPI application entry point
├── 🧠 model/
│ ├── model_loader.py # PyTorch model loading
│ ├── predictor.py # Image prediction logic
│ ├── gradcam.py # Grad-CAM visualization
│ ├── utils.py # Utility functions
│ └── class_map.json # Class index mapping
├── 🎨 templates/
│ ├── upload_form.html # Main upload interface
│ └── history.html # Prediction history page
├── 📁 static/
│ ├── uploads/ # Uploaded images
│ └── heatmaps/ # Generated heatmaps
├── 📁 history/
│ └── predictions.csv # Prediction logs
├── 📁 data/ # Training data structure
├── 📁 COVID-19_Radiography_Dataset/ # Original dataset
├── 🧠 covid_model.pth # Trained model weights
├── 📋 requirements.txt # Python dependencies
├── 📖 README.md # This file
└── 📊 covid19.ipynb # Jupyter notebook for analysis
🔧 Configuration
Environment Variables
1 # Optional: Set custom paths
2 MODEL_PATH = covid_model.pth
3 UPLOAD_DIR = static/uploads
4 HEATMAP_DIR = static/heatmaps
5 HISTORY_DIR = history
Model Parameters
Input Size : 224x224 pixels
Batch Size : 1 (inference)
Device : CPU (can be modified for GPU)
Confidence Threshold : 0.5
🚀 Deployment
Local Development
Production with Gunicorn
1 pip install gunicorn
2 gunicorn main:app -w 4 -k uvicorn.workers.UvicornWorker
Docker Deployment
1 FROM python:3.9-slim
2 WORKDIR /app
3 COPY requirements.txt .
4 RUN pip install -r requirements.txt
5 COPY . .
6 EXPOSE 8000
7 CMD [ "python" , "main.py" ]
🧪 Testing
Run Tests
1 # Install test dependencies
2 pip install pytest pytest-asyncio
3
4 # Run tests
5 pytest tests/
Test Coverage
1 pip install coverage
2 coverage run -m pytest
3 coverage report
📈 Performance
Model Metrics
Accuracy : 95.2%
Precision : 94.8%
Recall : 95.1%
F1-Score : 94.9%
System Requirements
CPU : 2+ cores recommended
RAM : 4GB minimum, 8GB recommended
Storage : 1GB for application + model
Network : Stable internet for initial setup
🤝 Contributing
We welcome contributions! Please follow these steps:
Fork the repository
Create a feature branch
git checkout -b feature/amazing-feature
Make your changes
Add tests for new functionality
Commit your changes
git commit -m 'Add amazing feature'
Push to the branch
git push origin feature/amazing-feature
Open a Pull Request
Development Guidelines
Follow PEP 8 style guide
Add docstrings to functions
Include type hints
Write comprehensive tests
Update documentation
🐛 Troubleshooting
Common Issues
Model not loading
1 # Check if model file exists
2 ls -la covid_model.pth
3
4 # Verify file integrity
5 python -c "import torch; torch.load('covid_model.pth')"
Memory issues
1 # Reduce batch size in model_loader.py
2 # Use CPU instead of GPU
Upload errors
1 # Check directory permissions
2 chmod 755 static/uploads/
3 chmod 755 static/heatmaps/
Logs
Check application logs for detailed error information:
📄 License
This project is licensed under the MIT License - see the
LICENSE file for details.
🙏 Acknowledgments
Dataset : COVID-19 Radiography Database
Framework : FastAPI, PyTorch
UI : HTML5, CSS3, JavaScript
Visualization : Grad-CAM implementation
Icons : Font Awesome
📞 Support
🔮 Roadmap
⚠️ Disclaimer : This tool is for educational and research purposes. Medical decisions should always be made by qualified healthcare professionals. The model predictions should not be used as the sole basis for medical diagnosis.
Made with ❤️ for the medical community