Skip to content

avithal/BrainMRIAnalyzer

Folders and files

NameName
Last commit message
Last commit date

Latest commit

 

History

1 Commit
 
 
 
 
 
 

Repository files navigation

🧠 Brain MRI Segmentation & AI Analysis System

Python 3.8+ License: MIT Open Source

A comprehensive Python application that combines state-of-the-art brain MRI segmentation models with AI-powered medical analysis. Built with object-oriented programming best practices and designed for both research and educational purposes.

✨ Features

  • 🔬 Multiple Segmentation Models: Choose from 5 different open-source brain segmentation models
  • 🤖 AI-Powered Analysis: Get detailed medical explanations using LLMs (NVIDIA NIM or Anthropic Claude)
  • 📊 Advanced Visualization: Multi-view segmentation overlays with color-coded regions
  • 📁 Flexible Input: Load real NIfTI files or generate synthetic MRI data
  • 🎯 Abnormality Detection: Automatic identification of enlarged ventricles, lesions, and tumors
  • 💾 Export Options: Save visualizations and detailed reports
  • 🏗️ OOP Architecture: Clean, extensible, and maintainable codebase

🖼️ Sample Output

The system generates comprehensive visualizations showing:

  • Original MRI in three anatomical planes (Axial, Sagittal, Coronal)
  • Segmentation overlays with color-coded brain regions
  • Abnormality highlighting with clinical significance markers

🚀 Quick Start

Prerequisites

python >= 3.8

Installation

  1. Clone the repository
git clone https://github.com/yourusername/brain-mri-segmentation.git
cd brain-mri-segmentation
  1. Install dependencies
pip install numpy nibabel matplotlib requests anthropic
  1. Run the application
python brain_segmentation.py

📦 Available Segmentation Models

Model Speed Accuracy Best For Installation
SynthSeg ⚡⚡⚡⚡ ⭐⭐⭐⭐ General use, any MRI contrast pip install freesurfer
FastSurfer ⚡⚡⚡⚡⚡ ⭐⭐⭐⭐ Speed priority, GPU acceleration pip install fastsurfer
HD-BET ⚡⚡⚡⚡ ⭐⭐⭐⭐ Tumor/lesion detection pip install HD-BET
nnU-Net 🏆 ⚡⚡⚡ ⭐⭐⭐⭐⭐ Research, maximum accuracy pip install nnunet
MONAI ⚡⚡⚡ ⭐⭐⭐⭐ Custom workflows, extensibility pip install monai

Model Details

1. SynthSeg (FreeSurfer)

2. FastSurfer

3. HD-BET

  • Description: Brain extraction and tumor segmentation
  • Speed: Fast inference
  • Strengths: Excellent for pathology, robust to tumors
  • GitHub: MIC-DKFZ/HD-BET

4. nnU-Net

5. MONAI

  • Description: Medical Open Network for AI - comprehensive framework
  • Speed: Varies by model
  • Strengths: Multiple pre-trained models, highly extensible
  • GitHub: Project-MONAI/MONAI

🤖 LLM Provider Options

1. NVIDIA NIM (Recommended - FREE) 🆓

Get detailed medical analysis using Meta Llama 3.1 70B:

  1. Visit build.nvidia.com
  2. Sign up for a free account (no credit card required)
  3. Generate your free API key
  4. Enter the key when prompted

Supported Models:

  • Meta Llama 3.1 70B/405B Instruct
  • Mistral Large
  • Microsoft Phi-3
  • Google Gemma

2. Anthropic Claude

For Claude-powered analysis:

  • Requires Anthropic API key
  • Get key from: console.anthropic.com
  • Uses Claude Sonnet 4 for medical analysis

3. Basic Reporting

No API key needed - provides structured medical reports without AI analysis.

📖 Usage Examples

Example 1: Load Real MRI Data

from brain_segmentation import BrainSegmentationPipeline, SynthSegModel, MedicalLLMAnalyzer, LLMProvider

# Initialize components
seg_model = SynthSegModel()
llm_analyzer = MedicalLLMAnalyzer(
    provider=LLMProvider.NVIDIA_NIM,
    api_key="your-nvidia-key"
)

# Create pipeline
pipeline = BrainSegmentationPipeline(seg_model, llm_analyzer)

# Load and analyze MRI
mri_data = pipeline.load_mri("path/to/brain_mri.nii.gz")
report = pipeline.run_analysis(mri_data)

# Display results
pipeline.print_report(report)
pipeline.visualize_segmentation()

Example 2: Generate Synthetic MRI

# Generate synthetic brain MRI
pipeline = BrainSegmentationPipeline(SynthSegModel())
mri_data = pipeline.generate_random_mri(shape=(256, 256, 128))

# Analyze
report = pipeline.run_analysis(mri_data)
pipeline.visualize_segmentation(output_dir="results")

Example 3: Compare Multiple Models

from brain_segmentation import *

models = [
    SynthSegModel(),
    FastSurferModel(),
    HDBETModel()
]

mri_data = pipeline.load_mri("scan.nii.gz")

for model in models:
    pipeline = BrainSegmentationPipeline(model)
    report = pipeline.run_analysis(mri_data)
    print(f"\n{model.model_name} Results:")
    pipeline.print_report(report)

🏗️ Architecture & OOP Design

Design Patterns Used

  1. Abstract Base Classes: BaseSegmentationModel defines interface for all segmentation models
  2. Strategy Pattern: Interchangeable segmentation models and LLM providers
  3. Data Classes: SegmentationResult for clean data representation
  4. Enumerations: Type-safe brain regions and provider selection
  5. Pipeline Pattern: BrainSegmentationPipeline orchestrates the workflow

Class Hierarchy

BaseSegmentationModel (ABC)
├── SynthSegModel
├── FastSurferModel
├── HDBETModel
├── nnUNetModel
└── MONAIModel

MedicalLLMAnalyzer
├── NVIDIA NIM Integration
├── Anthropic Claude Integration
└── Basic Reporting

BrainSegmentationPipeline
├── load_mri()
├── generate_random_mri()
├── run_analysis()
├── visualize_segmentation()
└── print_report()

📊 Output Files

The system generates the following outputs:

output/
└── segmentation_results.png    # Multi-view visualization with overlays

Report Sections

  1. Segmentation Results: Volume measurements for each brain region
  2. Abnormality Detection: Highlighted findings with confidence scores
  3. Clinical Analysis: AI-generated medical interpretation
  4. Recommendations: Suggested follow-up actions
  5. Model Information: Details about the segmentation model used

🎯 Detected Brain Regions

  • White Matter: Central brain tissue
  • Gray Matter: Cortical tissue
  • Cerebrospinal Fluid (CSF): Fluid surrounding brain
  • Ventricles: Fluid-filled cavities
  • Lesions: Abnormal tissue areas
  • Tumors: Abnormal growth masses

⚠️ Abnormality Detection

The system automatically flags:

  • Enlarged ventricles (hydrocephalus indicators)
  • Tissue lesions (potential MS, stroke, etc.)
  • Tumors or masses
  • Abnormal tissue volumes
  • Asymmetries

🔬 Research Applications

This project can be used for:

  • Educational purposes in medical imaging
  • Research on brain segmentation algorithms
  • Development of clinical decision support tools
  • Comparison studies between segmentation models
  • Integration into larger medical imaging pipelines

🤝 Contributing

Contributions are welcome! Here's how you can help:

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

Areas for Contribution

  • Additional segmentation models
  • More LLM provider integrations
  • 3D volume rendering
  • DICOM file support
  • Web interface
  • Docker containerization
  • Additional visualization options
  • Performance optimizations

📝 License

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

🙏 Acknowledgments

  • FreeSurfer team for SynthSeg
  • Deep-MI for FastSurfer
  • MIC-DKFZ for HD-BET and nnU-Net
  • Project MONAI for the medical imaging framework
  • NVIDIA for free NIM API access
  • Anthropic for Claude AI

📚 References

  1. Billot, B., et al. (2023). "SynthSeg: Segmentation of brain MRI scans of any contrast and resolution without retraining." Medical Image Analysis.
  2. Henschel, L., et al. (2020). "FastSurfer - A fast and accurate deep learning based neuroimaging pipeline." NeuroImage.
  3. Isensee, F., et al. (2018). "nnU-Net: Self-adapting Framework for U-Net-Based Medical Image Segmentation." Nature Methods.

📧 Contact

For questions, issues, or suggestions:

🌟 Star History

If you find this project useful, please consider giving it a star! ⭐


Disclaimer: This tool is for research and educational purposes only. It is not intended for clinical diagnosis or treatment decisions. Always consult qualified healthcare professionals for medical advice.

About

using opensource model to segmenta and generate report

Resources

Stars

Watchers

Forks

Releases

No releases published

Packages

 
 
 

Contributors

Languages