{"id":50664481,"url":"https://github.com/allureking/unet-cell-segmentation","last_synced_at":"2026-06-08T05:02:54.636Z","repository":{"id":340776875,"uuid":"1167522747","full_name":"allureking/unet-cell-segmentation","owner":"allureking","description":"U-Net \u0026 Attention U-Net for Cell Counting in Microscopy Images | PyTorch | Kaggle Competition | MAE 2.186","archived":false,"fork":false,"pushed_at":"2026-02-26T12:31:42.000Z","size":36,"stargazers_count":0,"open_issues_count":0,"forks_count":0,"subscribers_count":0,"default_branch":"main","last_synced_at":"2026-02-26T19:07:12.778Z","etag":null,"topics":["attention-unet","biomedical-imaging","cell-counting","computer-vision","deep-learning","image-segmentation","kaggle","microscopy","pytorch","unet"],"latest_commit_sha":null,"homepage":"https://kingke.dev","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/allureking.png","metadata":{"files":{"readme":"README.md","changelog":"CHANGELOG.md","contributing":null,"funding":null,"license":"LICENSE","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":"2026-02-26T11:40:50.000Z","updated_at":"2026-02-26T14:22:00.000Z","dependencies_parsed_at":null,"dependency_job_id":null,"html_url":"https://github.com/allureking/unet-cell-segmentation","commit_stats":null,"previous_names":["allureking/unet-cell-segmentation"],"tags_count":1,"template":false,"template_full_name":null,"purl":"pkg:github/allureking/unet-cell-segmentation","repository_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/allureking%2Funet-cell-segmentation","tags_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/allureking%2Funet-cell-segmentation/tags","releases_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/allureking%2Funet-cell-segmentation/releases","manifests_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/allureking%2Funet-cell-segmentation/manifests","owner_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/owners/allureking","download_url":"https://codeload.github.com/allureking/unet-cell-segmentation/tar.gz/refs/heads/main","sbom_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/allureking%2Funet-cell-segmentation/sbom","scorecard":null,"host":{"name":"GitHub","url":"https://github.com","kind":"github","repositories_count":286080680,"owners_count":34048681,"icon_url":"https://github.com/github.png","version":null,"created_at":"2022-05-30T11:31:42.601Z","updated_at":"2026-05-26T15:22:16.424Z","status":"online","status_checked_at":"2026-06-08T02:00:07.615Z","response_time":111,"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-unet","biomedical-imaging","cell-counting","computer-vision","deep-learning","image-segmentation","kaggle","microscopy","pytorch","unet"],"created_at":"2026-06-08T05:02:53.190Z","updated_at":"2026-06-08T05:02:54.630Z","avatar_url":"https://github.com/allureking.png","language":"Python","funding_links":[],"categories":[],"sub_categories":[],"readme":"# Cell Counting in Microscopy Images — U-Net \u0026 Attention U-Net\n\n\u003cdiv align=\"center\"\u003e\n\n**Deep learning pipeline for automated cell counting in fluorescence microscopy images**\n\n[![Python](https://img.shields.io/badge/Python-3.9+-3776AB?logo=python\u0026logoColor=white)](https://python.org)\n[![PyTorch](https://img.shields.io/badge/PyTorch-1.13+-EE4C2C?logo=pytorch\u0026logoColor=white)](https://pytorch.org)\n[![License](https://img.shields.io/badge/License-MIT-green.svg)](LICENSE)\n\n\u003c/div\u003e\n\n---\n\n## Overview\n\nThis project implements a complete deep learning pipeline for **counting cells in microscopy images** using semantic segmentation. Given fluorescence microscopy images, the model predicts a binary segmentation mask highlighting cell regions, then counts cells via connected-component labeling.\n\nBuilt for the [Kaggle \"Counting Cells in Microscopy Images\" competition](https://www.kaggle.com/competitions/counting-cells-in-microscopy-images-2023), achieving a **MAE of 2.186** on the private leaderboard.\n\n### Key Features\n\n- **Two model architectures**: Standard U-Net and Attention U-Net with learned spatial focus\n- **5 loss functions**: BCE, Dice, BCE+Dice, Focal, and Tversky loss\n- **Rich data augmentation**: Flips, rotations, elastic deformation, noise injection, brightness/contrast\n- **Post-processing**: Morphological operations and watershed segmentation for touching cells\n- **Full evaluation suite**: Dice coefficient, IoU, pixel accuracy, precision/recall, cell count MAE\n- **Visualization toolkit**: Prediction overlays, attention maps, error maps, training curves\n\n## Architecture\n\n### Standard U-Net\n\nBased on [Ronneberger et al. (2015)](https://arxiv.org/abs/1505.04597), adapted for cell counting:\n\n```\nInput (1×128×128)\n    │\n    ├── Encoder 1: 1 → 64    ─────────────────────── Skip ──┐\n    │   MaxPool                                              │\n    ├── Encoder 2: 64 → 128   ──────────────── Skip ──┐     │\n    │   MaxPool                                        │     │\n    ├── Encoder 3: 128 → 256   ─────── Skip ──┐       │     │\n    │   MaxPool                                │       │     │\n    ├── Encoder 4: 256 → 512   ── Skip ─┐     │       │     │\n    │   MaxPool                          │     │       │     │\n    ├── Bottleneck: 512 → 1024           │     │       │     │\n    │                                    │     │       │     │\n    ├── Decoder 4: 1024 → 512  ──── + ──┘     │       │     │\n    │   UpConv                                 │       │     │\n    ├── Decoder 3: 512 → 256   ──────── + ────┘       │     │\n    │   UpConv                                         │     │\n    ├── Decoder 2: 256 → 128   ────────────── + ──────┘     │\n    │   UpConv                                               │\n    ├── Decoder 1: 128 → 64    ──────────────────── + ──────┘\n    │\n    └── 1×1 Conv → Output (1×128×128)\n```\n\nEach encoder/decoder block uses `(Conv3×3 → BatchNorm → ReLU) × 2`.\n\n### Attention U-Net\n\nBased on [Oktay et al. (2018)](https://arxiv.org/abs/1804.03999), adds **attention gates** at each skip connection. The gates learn to highlight cell regions and suppress irrelevant background, particularly useful for noisy microscopy images.\n\n### Cell Counting Pipeline\n\n```\nMicroscopy Image → U-Net Segmentation → Threshold → Morphological Cleanup\n    → Connected Components → Cell Count\n         └── (Optional) Watershed Separation for Touching Cells\n```\n\n## Project Structure\n\n```\nunet-cell-segmentation/\n├── configs/\n│   ├── default.yaml          # Standard U-Net config\n│   ├── attention.yaml        # Attention U-Net config\n│   └── lightweight.yaml      # Lightweight config for quick experiments\n├── src/\n│   ├── model/\n│   │   ├── unet.py           # Standard U-Net architecture\n│   │   ├── attention_unet.py # Attention U-Net with attention gates\n│   │   ├── losses.py         # BCE, Dice, Focal, Tversky losses\n│   │   └── postprocess.py    # Morphological ops + watershed\n│   ├── data/\n│   │   ├── dataset.py        # CellDataset + DataLoader utilities\n│   │   └── augmentation.py   # Augmentation transforms\n│   ├── utils/\n│   │   ├── metrics.py        # Dice, IoU, accuracy, cell counting\n│   │   └── visualization.py  # Plotting utilities\n│   ├── train.py              # Training pipeline\n│   ├── evaluate.py           # Evaluation with visualizations\n│   ├── predict.py            # Kaggle submission generation\n│   └── compare.py            # Model comparison experiments\n├── tests/\n│   ├── test_model.py         # Architecture + loss function tests\n│   └── test_dataset.py       # Dataset, augmentation, metric tests\n├── scripts/\n│   └── run_experiment.sh     # Full pipeline automation\n├── results/                  # Generated plots and metrics\n├── configs/                  # YAML experiment configs\n├── requirements.txt\n└── README.md\n```\n\n## Quick Start\n\n### Installation\n\n```bash\ngit clone https://github.com/allureking/unet-cell-segmentation.git\ncd unet-cell-segmentation\npip install -r requirements.txt\n```\n\n### Download Data\n\nDownload the dataset from the [Kaggle competition page](https://www.kaggle.com/competitions/counting-cells-in-microscopy-images-2023) and place files in `data/`:\n\n```\ndata/\n├── train_data.npz    # 2000 images + masks (128×128, grayscale)\n└── test_images.npz   # 2000 test images\n```\n\n### Training\n\n```bash\n# Standard U-Net\npython -m src.train --config configs/default.yaml\n\n# Attention U-Net\npython -m src.train --config configs/attention.yaml\n\n# Lightweight (quick experiment)\npython -m src.train --config configs/lightweight.yaml\n```\n\n### Evaluation\n\n```bash\npython -m src.evaluate --checkpoint checkpoints/best_model.pth\n```\n\n### Generate Kaggle Submission\n\n```bash\npython -m src.predict \\\n    --checkpoint checkpoints/best_model.pth \\\n    --test data/test_images.npz \\\n    --output submission.csv\n```\n\n### Compare Models\n\n```bash\npython -m src.compare --config configs/default.yaml\n```\n\n### Run Tests\n\n```bash\npytest tests/ -v\n```\n\n## Results\n\n### Kaggle Competition\n\n| Model | Augmentation | Loss | MAE (Private) | MAE (Public) |\n|-------|-------------|------|---------------|--------------|\n| U-Net (32-base) | None | BCE | 9.57 | 10.01 |\n| U-Net (64-base) | Flips + Rotation | BCE+Dice | **2.186** | **2.297** |\n\n### Segmentation Metrics (Validation Set)\n\n| Metric | U-Net | Attention U-Net |\n|--------|-------|-----------------|\n| Dice Coefficient | 0.891 | 0.903 |\n| IoU (Jaccard) | 0.824 | 0.839 |\n| Pixel Accuracy | 0.967 | 0.971 |\n\n## Loss Functions\n\n| Loss | Formula | Best For |\n|------|---------|----------|\n| **BCE** | Standard binary cross-entropy | Baseline |\n| **Dice** | 1 − 2\\|A∩B\\| / (\\|A\\|+\\|B\\|) | Class imbalance |\n| **BCE + Dice** | α·BCE + (1−α)·Dice | General use (default) |\n| **Focal** | −α(1−p)^γ · log(p) | Hard examples |\n| **Tversky** | 1 − TP/(TP+α·FP+β·FN) | Penalize missed cells |\n\n## Data Augmentation\n\nFollowing the original U-Net paper's emphasis on augmentation for biomedical images:\n\n- **Geometric**: Random flips (H/V), 90° rotations\n- **Intensity**: Gaussian noise, brightness/contrast adjustment\n- **Elastic**: Random elastic deformation with smoothed displacement fields\n- All transforms applied jointly to image-mask pairs\n\n## Technical Details\n\n- **Input**: Single-channel grayscale microscopy images (128×128 pixels), normalized to [0, 1]\n- **Output**: Binary segmentation mask (cell vs. background)\n- **Optimizer**: Adam with weight decay (1e-5)\n- **LR Schedule**: ReduceLROnPlateau (factor=0.5, patience=5)\n- **Checkpointing**: Best model saved based on validation loss\n- **Device**: Auto-selects CUDA → MPS → CPU\n\n## References\n\n1. Ronneberger, O., Fischer, P., \u0026 Brox, T. (2015). *U-Net: Convolutional Networks for Biomedical Image Segmentation*. MICCAI. [arXiv:1505.04597](https://arxiv.org/abs/1505.04597)\n\n2. Oktay, O. et al. (2018). *Attention U-Net: Learning Where to Look for the Pancreas*. MIDL. [arXiv:1804.03999](https://arxiv.org/abs/1804.03999)\n\n3. Abraham, N. \u0026 Khan, N.M. (2019). *A Novel Focal Tversky Loss Function with Improved Attention U-Net for Lesion Segmentation*. ISBI.\n\n## License\n\nMIT License — see [LICENSE](LICENSE) for details.\n","project_url":"https://awesome.ecosyste.ms/api/v1/projects/github.com%2Fallureking%2Funet-cell-segmentation","html_url":"https://awesome.ecosyste.ms/projects/github.com%2Fallureking%2Funet-cell-segmentation","lists_url":"https://awesome.ecosyste.ms/api/v1/projects/github.com%2Fallureking%2Funet-cell-segmentation/lists"}