{"id":34861360,"url":"https://github.com/hoangtung386/brain-stroke-segmentation","last_synced_at":"2026-04-19T21:06:39.145Z","repository":{"id":328805701,"uuid":"1114889585","full_name":"hoangtung386/brain-stroke-segmentation","owner":"hoangtung386","description":"Brain Stroke Segmentation in Medical Images: Advanced LCNN (Lightweight CNN) architecture for automatic detection and precise segmentation of ischemic or hemorrhagic lesions in medical scans.","archived":false,"fork":false,"pushed_at":"2025-12-25T18:30:25.000Z","size":5543,"stargazers_count":2,"open_issues_count":0,"forks_count":0,"subscribers_count":0,"default_branch":"main","last_synced_at":"2025-12-27T05:59:40.046Z","etag":null,"topics":["attention-mechanism","brain-stroke-segmentation","computer-vision","ct-scan-images","deep-learning","medical-imaging","monai","pytorch","resnext","segmentation-models","symmetry-learning","wandb"],"latest_commit_sha":null,"homepage":"","language":"Python","has_issues":true,"has_wiki":null,"has_pages":null,"mirror_url":null,"source_name":null,"license":"mit","status":null,"scm":"git","pull_requests_enabled":true,"icon_url":"https://github.com/hoangtung386.png","metadata":{"files":{"readme":"README.md","changelog":null,"contributing":null,"funding":null,"license":"LICENSE.txt","code_of_conduct":null,"threat_model":null,"audit":null,"citation":null,"codeowners":null,"security":null,"support":null,"governance":null,"roadmap":null,"authors":null,"dei":null,"publiccode":null,"codemeta":null,"zenodo":null,"notice":null,"maintainers":null,"copyright":null,"agents":null,"dco":null,"cla":null}},"created_at":"2025-12-12T03:20:56.000Z","updated_at":"2025-12-25T18:30:28.000Z","dependencies_parsed_at":null,"dependency_job_id":null,"html_url":"https://github.com/hoangtung386/brain-stroke-segmentation","commit_stats":null,"previous_names":["hoangtung386/brain-stroke-segmentation"],"tags_count":1,"template":false,"template_full_name":null,"purl":"pkg:github/hoangtung386/brain-stroke-segmentation","repository_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/hoangtung386%2Fbrain-stroke-segmentation","tags_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/hoangtung386%2Fbrain-stroke-segmentation/tags","releases_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/hoangtung386%2Fbrain-stroke-segmentation/releases","manifests_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/hoangtung386%2Fbrain-stroke-segmentation/manifests","owner_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/owners/hoangtung386","download_url":"https://codeload.github.com/hoangtung386/brain-stroke-segmentation/tar.gz/refs/heads/main","sbom_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/hoangtung386%2Fbrain-stroke-segmentation/sbom","scorecard":null,"host":{"name":"GitHub","url":"https://github.com","kind":"github","repositories_count":286080680,"owners_count":32022579,"icon_url":"https://github.com/github.png","version":null,"created_at":"2022-05-30T11:31:42.601Z","updated_at":"2026-04-18T20:23:30.271Z","status":"online","status_checked_at":"2026-04-19T02:00:07.110Z","response_time":55,"last_error":null,"robots_txt_status":"success","robots_txt_updated_at":"2025-07-24T06:49:26.215Z","robots_txt_url":"https://github.com/robots.txt","online":true,"can_crawl_api":true,"host_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub","repositories_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories","repository_names_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repository_names","owners_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/owners"}},"keywords":["attention-mechanism","brain-stroke-segmentation","computer-vision","ct-scan-images","deep-learning","medical-imaging","monai","pytorch","resnext","segmentation-models","symmetry-learning","wandb"],"created_at":"2025-12-25T21:11:29.706Z","updated_at":"2026-04-19T21:06:39.139Z","avatar_url":"https://github.com/hoangtung386.png","language":"Python","funding_links":[],"categories":[],"sub_categories":[],"readme":"# Brain Stroke Segmentation - LCNN Architecture\n\nA deep learning project for brain stroke lesion segmentation using **LCNN (Local-Global Combined Neural Network)**, incorporating **SEAN (Symmetry Enhanced Attention Network)** and **ResNeXt50**. This architecture is designed to capture both fine-grained local details and global semantic context, leveraging the inherent symmetry of the brain to improve segmentation accuracy.\n\n![Architecture Overview](https://img.shields.io/badge/Architecture-LCNN%20%2B%20SEAN-blue)\n![PyTorch](https://img.shields.io/badge/PyTorch-2.0%2B-ee4c2c)\n![CUDA](https://img.shields.io/badge/CUDA-11.8%2B-76b900)\n[![Hugging Face](https://img.shields.io/badge/🤗%20Hugging%20Face-Model-yellow)](https://huggingface.co/hoangtung386/brain-stroke-lcnn)\n[![Acknowledgments](https://img.shields.io/badge/ACKNOWLEDGMENTS-Contributors-orange?style=flat-square\u0026logo=open-source-initiative)](./ACKNOWLEDGMENTS.md)\n[![License: MIT](https://img.shields.io/badge/License-MIT-green.svg)](./LICENSE.txt)\n\n## Quick Links 🎯\n\n- 🤗 **[Pre-trained Model on Hugging Face](https://huggingface.co/hoangtung386/brain-stroke-lcnn)**\n- 📊 **[Dataset Information](#-data-preparation)**\n- 🚀 **[Quick Start Guide](#-installation)**\n- 📖 **[Documentation](#-project-structure)**\n- 💬 **[Contact \u0026 Support](#-contact)**\n\n---\n\n## Model Architecture 🔱\n\n![Architectural Model](./Architectural_model.png)\n\nThis diagram illustrates the **LCNN (Local-Global Combined Network)** architecture used in this project. It highlights the integration of our **Symmetry Enhanced Attention Network (SEAN)** for capturing local, contralateral features and **ResNeXt50** for global semantic understanding. The parallel processing pathways ensure both fine-grained lesion details and broader context are preserved for accurate segmentation.\n\n### Key Features\n\n*   **Symmetry Enhanced Attention (SEAN)**: Exploits the bilateral symmetry of the human brain. An Alignment Network aligns the input slices, allowing the model to compare features from the contralateral hemisphere to identify anomalies.\n*   **Dual-Path Architecture**:\n    *   **Local Path (SEAN)**: Processes 3D stacks of adjacent CT slices to capture volumetric context and details.\n    *   **Global Path (ResNeXt50)**: Extracts high-level semantic features to reduce false positives.\n*   **Combined Loss Function**: Optimized hybrid loss combining:\n    *   **Dice Loss**: Handles severe class imbalance (small stroke lesions).\n    *   **Cross Entropy Loss**: Ensures pixel-level classification accuracy.\n    *   **Alignment Loss**: Enforces symmetry alignment in the SEAN module.\n\n---\n\n## Pre-trained Model 🤗\n\nThe trained model is available on Hugging Face Hub for easy download and inference:\n\n**🔗 Model Repository**: [hoangtung386/brain-stroke-lcnn](https://huggingface.co/hoangtung386/brain-stroke-lcnn)\n\n### Download Pre-trained Weights\n\n```python\nfrom huggingface_hub import hf_hub_download\n\n# Download best model checkpoint\nmodel_path = hf_hub_download(\n    repo_id=\"hoangtung386/brain-stroke-lcnn\",\n    filename=\"best_model.pth\"\n)\n\n# Load model\nimport torch\nfrom models.lcnn import LCNN\n\nmodel = LCNN(num_channels=1, num_classes=2, T=1)\ncheckpoint = torch.load(model_path, map_location='cpu')\nmodel.load_state_dict(checkpoint['model_state_dict'])\nmodel.eval()\n```\n\n### Quick Inference Example\n\n```python\nimport torch\nfrom PIL import Image\nfrom torchvision import transforms\n\n# Load and preprocess image\nimage = Image.open('path/to/ct_scan.png').convert('L')\ntransform = transforms.Compose([\n    transforms.Resize((512, 512)),\n    transforms.ToTensor(),\n    transforms.Normalize(mean=[0.2162], std=[0.1841])\n])\n\n# Create 3-slice stack (2T+1 where T=1)\nimage_tensor = transform(image).unsqueeze(0)  # (1, 512, 512)\nimage_stack = image_tensor.repeat(3, 1, 1).unsqueeze(0)  # (1, 3, 512, 512)\n\n# Inference\nwith torch.no_grad():\n    output = model(image_stack)\n    prediction = torch.argmax(output, dim=1)\n\nprint(f\"Prediction shape: {prediction.shape}\")\n```\n\n---\n\n## Project Structure 📂\n\n```bash\nbrain-stroke-segmentation/\n│\n├── config.py                 # Central configuration\n├── dataset.py                # Dataset and DataLoader (handles 3D slice stacking)\n├── download_dataset.py       # Data download utility\n├── trainer.py                # Training loop and CombinedLoss implementation\n├── train.py                  # Main entry point for training\n├── evaluate.py               # Validation and evaluation script\n├── setup.sh                  # Application environment setup\n├── requirements.txt          # Python dependencies\n│\n├── models/\n│   ├── __init__.py\n│   ├── lcnn.py               # LCNN Main Architecture\n│   ├── sean.py               # SEAN + Alignment Network\n│   ├── global_path.py        # ResNeXt Global Path\n│   └── components.py         # Shared components\n│\n├── utils/\n│   ├── __init__.py\n│   ├── visualization.py      # Plotting and overlay tools\n│   ├── metrics.py            # Dice, IoU, Precision metrics\n│   └── improved_alignment_loss.py  # Advanced loss functions\n│\n├── data/                     # Dataset storage\n│   ├── images/               # CT Images\n│   └── masks/                # Segmentation Masks\n│\n├── checkpoints/              # Model checkpoints\n├── outputs/                  # Logs, charts, and visualizations\n│\n├── ACKNOWLEDGMENTS.md        # Detailed acknowledgments\n├── LICENSE.txt               # MIT License\n└── README.md                 # This file\n```\n\n---\n\n## System Requirements 💻\n\n*   **GPU**: NVIDIA RTX 3090 (24GB VRAM) or equivalent recommended.\n*   **OS**: Linux (tested on Ubuntu 20.04/22.04).\n*   **CUDA**: Version 11.7 or higher.\n*   **Python**: 3.8+.\n\n---\n\n## Installation 🚀\n\n### Option 1: Auto Setup (Recommended)\n\nThis script sets up a virtual environment, installs PyTorch (CUDA-optimized), and dependencies.\n\n```bash\n# Clone repository\ngit clone https://github.com/hoangtung386/brain-stroke-segmentation.git\ncd brain-stroke-segmentation\n\n# Run setup script\nchmod +x setup.sh\n./setup.sh\n```\n\n### Option 2: Manual Setup\n\n```bash\n# Clone repository\ngit clone https://github.com/hoangtung386/brain-stroke-segmentation.git\ncd brain-stroke-segmentation\n\n# Create environment\nconda create -n stroke_seg_env python=3.12 -y\nconda activate stroke_seg_env\n\n# Install PyTorch (adjust CUDA version as needed)\npip install torch torchvision --index-url https://download.pytorch.org/whl/cu121\n\n# Install dependencies\npip install -r requirements.txt\n```\n\n### Option 3: Use Pre-trained Model from Hugging Face\n\n```bash\n# Install Hugging Face Hub\npip install huggingface-hub\n\n# Download model in Python (see example above)\n```\n\n---\n\n## Data Preparation 📊\n\nThe model requires a specific directory structure. You can download the dataset automatically or organize your own.\n\n### Option A: Automatic Download\n\n```bash\npython download_dataset.py\n```\n\n### Option B: Custom Data\n\nOrganize your data as follows:\n\n```text\ndata/\n├── images/\n│   ├── patient_001/\n│   │   ├── 001.png\n│   │   ├── 002.png\n│   │   └── ...\n│   ├── patient_002/\n│   └── ...\n└── masks/\n    ├── patient_001/\n    │   ├── 001.png\n    │   ├── 002.png\n    │   └── ...\n    ├── patient_002/\n    └── ...\n```\n\n---\n\n## Training 🤖\n\n### 1. Configure Weights \u0026 Biases (Optional)\n\nIf you want to use Weights \u0026 Biases for tracking:\n\n```bash\nwandb login\n```\n\nAlternatively, set `USE_WANDB = False` in `config.py`\n\n### 2. Adjust Configuration\n\nEdit `config.py` to adjust hyperparameters if needed:\n\n```python\nBATCH_SIZE = 32         # Adjust based on VRAM (use 8-16 for 3090 if OOM)\nNUM_EPOCHS = 60         # Total training epochs\nLEARNING_RATE = 1e-3    # Initial learning rate\nNORMALIZE = True        # Ensure this matches your data stats\n```\n\n\u003e **Tip**: Before training, verify normalization stats:\n\u003e ```bash\n\u003e python -c \"from config import Config; Config.compute_normalization_stats(Config.IMAGE_DIR)\"\n\u003e ```\n\n### 3. Start Training\n\n**New training:**\n```bash\npython train.py\n```\n\n**Resume from checkpoint:**\n```bash\npython train.py --checkpoint checkpoints/last_checkpoint.pth\n```\n\nTraining logs, best models (`best_model.pth`), and history (`training_history.csv`) will be saved to `outputs/`.\n\n### 4. Monitoring\n\n*   **Console**: Live metrics (Loss, Dice, LR).\n*   **Weights \u0026 Biases**: If enabled in `config.py` (`USE_WANDB = True`), run `wandb login` first.\n\n---\n\n## Evaluation 📉\n\nEvaluate the trained model on the validation set to generate metrics and visual overlays.\n\n```bash\n# Evaluate best model\npython evaluate.py --checkpoint checkpoints/best_model.pth --num-samples 30\n\n# Evaluate Hugging Face model\npython evaluate.py --checkpoint path/to/downloaded/best_model.pth --num-samples 30\n```\n\n**Output:**\n- Report: `outputs/evaluation_report.txt`\n- Visualizations: `outputs/overlay_sample_*.png`\n\n---\n\n## Optimization Tips (RTX 3090) ⚡\n\n*   **Mixed Precision**: The trainer uses `torch.cuda.amp` by default for faster training and lower memory usage.\n*   **Data Loading**: Set `NUM_WORKERS = 4` or `8` in `config.py` for optimal data throughput. `PIN_MEMORY = True` is enabled by default.\n*   **Out of Memory (OOM)**:\n    *   Reduce `BATCH_SIZE` to 16, 8, or 4.\n    *   Reduce `IMAGE_SIZE` to `(256, 256)` in `config.py`.\n\n---\n\n## Troubleshooting 🛠️\n\n| Issue | Possible Cause | Solution |\n| :--- | :--- | :--- |\n| **Loss is NaN** | Exploding gradients or bad normalization | Check dataset stats; enable gradient clipping (default in trainer). |\n| **Dice Score ~0** | Model learning only background | Check class weights in `trainer.py`; verify mask values are 0/1. |\n| **Dimension Errors** | Mismatch in 2D vs 3D shapes | Architecture fix applied; `dataset.py` now handles 3D stacks correctly. |\n| **CUDA OOM** | Batch size too large | Decrease `BATCH_SIZE`; use `nvidia-smi` to check VRAM. |\n\n---\n\n## Citation 📚\n\nIf you use this work in your research, please cite:\n\n```bibtex\n@software{le_vu_hoang_tung_2026_brain_stroke_lcnn,\n  author = {Le Vu Hoang Tung},\n  title = {Brain Stroke Segmentation using LCNN Architecture},\n  year = {2026},\n  publisher = {GitHub},\n  url = {https://github.com/hoangtung386/brain-stroke-segmentation},\n  note = {Pre-trained model: \\url{https://huggingface.co/hoangtung386/brain-stroke-lcnn}}\n}\n```\n\n---\n\n## License 📄\n\nThis project is licensed under the MIT License - see the [LICENSE.txt](LICENSE.txt) file for details.\n\n---\n\n## Contact ✉️\n\n**Author**: Le Vu Hoang Tung  \n**Email**: levuhoangtung1542003@gmail.com  \n**GitHub**: [@hoangtung386](https://github.com/hoangtung386)       \n**X (Twitter)**: [@hoangtung386](https://x.com/hoangtung386)  \n**Hugging Face**: [@hoangtung386](https://huggingface.co/hoangtung386)\n\nIf you encounter any issues, please create an issue on GitHub or contact via email.\n\n---\n\n## Acknowledgments 🤝🏻\n\nSee [ACKNOWLEDGMENTS.md](./ACKNOWLEDGMENTS.md) for detailed acknowledgments including:\n- Primary author contributions\n- AI assistant support (debugging only)\n- Technologies and frameworks used\n- Research foundations\n\n---\n\n## 🌟 Star History\n\n[![Star History Chart](https://api.star-history.com/svg?repos=hoangtung386/brain-stroke-segmentation\u0026type=Date)](https://star-history.com/#hoangtung386/brain-stroke-segmentation\u0026Date)\n","project_url":"https://awesome.ecosyste.ms/api/v1/projects/github.com%2Fhoangtung386%2Fbrain-stroke-segmentation","html_url":"https://awesome.ecosyste.ms/projects/github.com%2Fhoangtung386%2Fbrain-stroke-segmentation","lists_url":"https://awesome.ecosyste.ms/api/v1/projects/github.com%2Fhoangtung386%2Fbrain-stroke-segmentation/lists"}