Skip to content

About

Deep Learning pipeline designed to classify spinal X-rays as either Healthy or Abnormal, uses DIP and CNN

Topics

Resources

Stars

1 star

Watchers

0 watching

Forks

Latest commit

Β 

History

21 Commits

Folders and files

Repository files navigation

πŸ₯ Vertebral Fracture Detection System

AI-Powered Spinal X-Ray Analysis for Early Diagnosis

Python TensorFlow License Streamlit


πŸ”¬ Overview

The Vertebral Fracture Detection System is an end-to-end deep learning pipeline designed to classify spinal X-rays as Healthy or Abnormal with exceptional accuracy. Leveraging advanced digital image processing techniques and a custom CNN architecture, this system demonstrates the potential of AI in medical diagnostics.


🌐 Live Deployment: Try the interactive web application at https://spine-fracture-ai.streamlit.app/

⚠️ Medical Disclaimer: This is an educational proof-of-concept project. It should NOT be used for actual medical diagnosis without proper clinical validation and physician oversight.

🎯 Project Objectives

  • βœ… Build a robust binary classifier for vertebral abnormality detection
  • βœ… Implement OOD detection to prevent misdiagnosis on invalid inputs
  • βœ… Implement production-grade preprocessing pipelines using OpenCV
  • βœ… Overcome common ML challenges (class imbalance, overfitting, gradient issues)
  • βœ… Deploy an interactive web interface for real-time predictions
  • βœ… Achieve research-level performance metrics

✨ Features

πŸ›‘οΈ Out-of-Distribution (OOD) Detection

  • AI Gatekeeper validates input images before diagnosis
  • Rejects non-X-ray images (photos, charts, random images)
  • Prevents false diagnoses on invalid inputs
  • Dual-model architecture for robust prediction

🧠 Advanced Deep Learning

  • Custom CNN architecture optimized for medical imaging
  • Global Average Pooling to prevent parameter explosion
  • Class-weighted training to handle dataset imbalance
  • Strategic dropout (60%) for robust generalization

πŸ‘οΈ Medical Image Processing

  • CLAHE (Contrast Limited Adaptive Histogram Equalization) for enhanced contrast
  • Gaussian blur filtering for noise reduction
  • Standardized preprocessing pipeline
  • Automated image quality normalization

🎨 Data Augmentation

  • Dynamic rotation (Β±20Β°)
  • Random zoom (80%-120%)
  • Horizontal flipping
  • Width/height shifts for translation invariance

🌐 Production-Ready Deployment

  • Interactive Streamlit web interface
  • Real-time image upload and prediction
  • Confidence score visualization
  • Responsive design for all devices

🎬 Demo

Web Interface

streamlit run app.py

Upload an X-ray β†’ Get Instant Diagnosis

Input X-Ray Preprocessing Prediction
Raw Medical Image CLAHE Enhancement Healthy / Abnormal

πŸ–₯️ UI Showcase

Vertebral Fracture Detection UI

Live Demo Interface Features:

  • πŸ“€ Drag-and-drop file upload (JPG/PNG supported)
  • πŸ” Side-by-side comparison (Original vs. CLAHE-enhanced)
  • πŸ“Š Real-time diagnosis with confidence scores
  • 🎨 Clean, dark-themed professional UI
  • ⚑ Instant predictions (<2 seconds)

πŸ›‘οΈ Training the AI Gatekeeper (OOD Detection)

To keep this repository lightweight and adhere to Git best practices, the raw image datasets are not included in version control.

If you wish to retrain the gatekeeper_v1.keras Out-of-Distribution (OOD) detection model from scratch, please follow these steps to assemble the training data:

1. Download the Data:

  • Random Images (Class 0 - Not X-Ray): Download the Natural Images Dataset from Kaggle. Select ~200 random images (dogs, cars, people, etc.).
  • Digital Charts (Class 0 - Not X-Ray): Download the Data Visualization Charts Dataset from Kaggle or save ~50 images of pie charts and bar graphs from Google Images.
  • Real X-Rays (Class 1 - Is X-Ray): Gather ~200 of your existing healthy and abnormal spinal X-rays.

2. Assemble the Folder Structure: Create the following directory structure and place the images inside:

data/
└── gatekeeper_data/
    β”œβ”€β”€ random/       # Place the ~250 natural images and charts here
    └── xrays/        # Place the ~200 real spinal X-rays here

3. Train the Model: Once the folders are populated, run the training script from the root directory:

python -m src.train_gatekeeper

πŸ› οΈ Technology Stack

Category Technologies
Deep Learning TensorFlow Keras
Computer Vision OpenCV
ML Tools scikit-learn
Data Science NumPy Pandas
Visualization Matplotlib
Web Framework Streamlit

πŸ—οΈ Architecture

System Pipeline

Raw Image Upload
      ↓
πŸ›‘οΈ OOD Gatekeeper (Is this an X-ray?)
      β”œβ”€β†’ ❌ Not X-ray β†’ Reject
      └─→ βœ… Valid X-ray
            ↓
      Preprocessing (Grayscale Conversion)
            ↓
      CLAHE Enhancement (Clip Limit: 1.2)
            ↓
      Gaussian Blur (3Γ—3 Kernel)
            ↓
      Resize to 224Γ—224
            ↓
      🧠 CNN Classifier Model
            ↓
      Prediction (Healthy/Abnormal)
            ↓
      πŸ“Š Confidence Score

Two-Stage Architecture:

  1. Stage 1 - OOD Detection: gatekeeper_v1.keras validates input is a real X-ray
  2. Stage 2 - Classification: cnn_spine_v1.keras diagnoses healthy vs. abnormal

CNN Architecture

Input (224Γ—224Γ—1)
    ↓
Rescaling (1/255)
    ↓
Data Augmentation Layer
β”œβ”€ RandomFlip (horizontal)
β”œβ”€ RandomRotation (Β±10%)
└─ RandomZoom (Β±10%)
    ↓
Conv2D(32, 3Γ—3, padding='same') β†’ ReLU β†’ MaxPool(2Γ—2)
    ↓
Conv2D(64, 3Γ—3, padding='same') β†’ ReLU β†’ MaxPool(2Γ—2)
    ↓
Conv2D(128, 3Γ—3, padding='same') β†’ ReLU β†’ MaxPool(2Γ—2)
    ↓
GlobalAveragePooling2D
    ↓
Dense(128, he_normal) β†’ ReLU
    ↓
Dropout(0.6)
    ↓
Dense(1, sigmoid) β†’ Output

Key Innovation: GlobalAveragePooling reduced parameters from 12.8M β†’ 16K while maintaining accuracy!


πŸ“¦ Installation

Prerequisites

  • Python 3.8 or higher
  • pip package manager
  • Virtual environment (recommended)

Step-by-Step Setup

# 1. Clone the repository
git clone https://github.com/RaviKumarYadav15/vertebral-disease-detection-v1.0.git
cd vertebral-disease-detection-v1.0

# 2. Create virtual environment
python -m venv venv

# 3. Activate virtual environment
# On Windows:
venv\Scripts\activate
# On macOS/Linux:
source venv/bin/activate

# 4. Install dependencies
pip install -r requirements.txt

Dependencies

opencv-python==4.8.0.76
tensorflow==2.16.1
scikit-learn==1.3.2
numpy==1.26.2
matplotlib==3.8.2
streamlit==1.29.0
pillow>=9.3.0
pandas>=1.5.0

***removed exact version as it needed locally for pip, and while deployment change python version to 11 for tensor flow ***



πŸš€ Usage

Training Pipeline

# Step 1: Preprocess raw X-ray images
python -m src.preprocess

# Step 2: Train baseline logistic regression model
python -m src.train_baseline

# Step 3: Train custom CNN model
python -m src.train_cnn

# Step 4: Compare model performance
python -m src.compare_models

Web Application

# Launch Streamlit interface
streamlit run app.py

Then navigate to http://localhost:8501 in your browser.

Programmatic Inference

from src.predict import predict_image

# Predict on a single image
result = predict_image('path/to/xray.jpg')
print(f"Prediction: {result['class']}")
print(f"Confidence: {result['confidence']:.2%}")

πŸ“ Project Structure

vertebral-disease-detection/
β”‚
β”œβ”€β”€ πŸ“‚ data/
β”‚   β”œβ”€β”€ gatekeeper_data/         # OOD detection training data
β”‚   β”‚   β”œβ”€β”€ random/              # Non-X-ray images (natural images, charts)
β”‚   β”‚   └── xrays/               # Real X-ray images
β”‚   β”œβ”€β”€ processed/               # Enhanced images after DIP pipeline
β”‚   β”‚   β”œβ”€β”€ abnormal/            # Preprocessed abnormal X-rays
β”‚   β”‚   └── healthy/             # Preprocessed healthy X-rays
β”‚   └── raw/                     # Original X-ray images
β”‚       β”œβ”€β”€ abnormal/            # 500 abnormal spine X-rays
β”‚       └── healthy/             # 500 healthy spine X-rays
β”‚
β”œβ”€β”€ πŸ“‚ models/                   # Saved model checkpoints
β”‚   β”œβ”€β”€ baseline_logistic.pkl    # Baseline ML model
β”‚   β”œβ”€β”€ cnn_spine_v1.keras       # Trained CNN classifier
β”‚   └── gatekeeper_v1.keras      # OOD detection model
β”‚
β”œβ”€β”€ πŸ“‚ src/                      # Source code
β”‚   β”œβ”€β”€ __init__.py              # Package initialization
β”‚   β”œβ”€β”€ config.py                # Configuration & hyperparameters
β”‚   β”œβ”€β”€ preprocess.py            # Image preprocessing pipeline
β”‚   β”œβ”€β”€ model_cnn.py             # CNN architecture definition
β”‚   β”œβ”€β”€ train_baseline.py        # Baseline model training
β”‚   β”œβ”€β”€ train_cnn.py             # CNN training script with callbacks
β”‚   β”œβ”€β”€ train_gatekeeper.py      # OOD detection model training
β”‚   β”œβ”€β”€ predict.py               # Inference engine
β”‚   └── compare_models.py        # Model evaluation & comparison
β”‚
β”œβ”€β”€ πŸ“‚ uploads/                  # Temporary upload directory for web app
β”œβ”€β”€ πŸ“‚ venv/                     # Virtual environment (not in git)
β”‚
β”œβ”€β”€ πŸ“„ app.py                    # Streamlit web application
β”œβ”€β”€ πŸ“Š training_history.png      # Training/validation curves
β”œβ”€β”€ πŸ“‹ requirements.txt          # Python dependencies
β”œβ”€β”€ πŸ“– README.md                 # Project documentation
└── πŸ”’ .gitignore                # Git ignore rules

🀝 Contributing

Contributions are welcome! Please follow these steps:

  1. Fork the repository
  2. Create a feature branch (git checkout -b feature/AmazingFeature)
  3. Commit your changes (git commit -m 'Add AmazingFeature')
  4. Push to the branch (git push origin feature/AmazingFeature)
  5. Open a Pull Request

πŸ“„ License

This project is licensed under the MIT License - see the LICENSE file for details.


πŸ™ Acknowledgments

  • Dataset: Vertebral X-ray images from Kaggle - Spine Fracture Prediction from X-rays
  • Inspiration: Medical AI research community
  • Libraries: TensorFlow, OpenCV, Streamlit teams
  • Guidance: Deep learning and computer vision best practices

πŸ“¬ Contact

Ravi - Project Author


⭐ If you found this project helpful, please consider giving it a star!

Made with ❀️ and 🧠 for advancing medical AI

⬆ Back to Top

About

Deep Learning pipeline designed to classify spinal X-rays as either Healthy or Abnormal, uses DIP and CNN

Topics

Resources

Stars

1 star

Watchers

0 watching

Forks

Releases

Packages

Contributors

Languages