Release model, model card and example
Browse filesFiles changed (7)
- ATTRIBUTION.mdAdded+11
- README.mdAdded+68
- config.jsonAdded+18
- example.pyAdded+21
- example_1.jpgAdded
- model.ptAdded+3
- model_fp16.onnxAdded+3
1234567891011# Example image credits
All three come from Wikimedia Commons. Each was re-saved as JPEG (removing camera metadata) andshrunk to at most 1000 pixels. They have **no expert masks**, so they illustrate the demo and arenot evidence of accuracy. The code licence of this demo does not change the licences below.
| File | Original | Author | Licence | Further change ||---|---|---|---|---|| example_1.jpg | [Polyp.jpeg](https://commons.wikimedia.org/wiki/File:Polyp.jpeg) | Stephen Holland, M.D., Naperville Gastroenterology | [CC BY 2.5](https://creativecommons.org/licenses/by/2.5/) | none || example_2.jpg | [Colon polyp (Telugu title)](https://commons.wikimedia.org/wiki/File:%E0%B0%AA%E0%B1%86%E0%B0%A6%E0%B1%8D%E0%B0%A6%E0%B0%AA%E0%B1%8D%E0%B0%B0%E0%B1%87%E0%B0%B5%E0%B1%81%E0%B0%B2%E0%B1%8B_%E0%B0%95%E0%B0%82%E0%B0%A4%E0%B0%BF_(Colon_polyp).jpeg) | డా. గన్నవరపు నరసింహమూర్తి | [CC0](https://creativecommons.org/publicdomain/zero/1.0/) | none || example_3.jpg | [Polypectomy.jpg](https://commons.wikimedia.org/wiki/File:Polypectomy.jpg) | Gilo1969 | [CC BY-SA 3.0](https://creativecommons.org/licenses/by-sa/3.0/) (this crop is shared under the same licence) | cropped to the left panel, white border removed |1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768---license: otherlicense_name: kvasir-seg-research-and-educationlicense_link: https://datasets.simula.no/kvasir-seg/library_name: onnxpipeline_tag: image-segmentationtags: [colonoscopy, polyp-segmentation, medical-imaging, healthcare, medical-ai, unet, resnet34, domain-shift, pytorch, onnx]metrics: [dice]---
# PolypShift: colonoscopy polyp segmentation, tested across hospitals
A U-Net with an ImageNet-pretrained ResNet34 encoder that outlines **polyps in colonoscopy images**. It was trained onKvasir-SEG and tested **unchanged on three datasets it never saw**.
> ⚠️ **Research model, not a medical device.** Trained and tested on public retrospective data only. Do not use it for diagnosis or treatment decisions.
▶ **Try it in your browser:** https://huggingface.co/spaces/rigel08/polypshift· **Code and results:** https://github.com/rigel08/polyp-segmentation
## Results (mean Dice, 95% CI)| Images from | Images | Dice ||---|---:|---|| Kvasir-SEG held-out test (same source) | 100 | **0.894** (0.862–0.920) || CVC-ColonDB (unseen) | 380 | 0.754 (0.726–0.781) || ETIS-Larib (unseen) | 196 | 0.649 (0.598–0.699) |
Small polyps drive much of the drop. ImageNet pretraining added +0.069 Dice (95% CI 0.031–0.110).Near-duplicate video frames were grouped (ORB + RANSAC) so no polyp appears in both train and test.
## Files| File | What it is ||---|---|| `model_fp16.onnx` | ONNX, 16-bit weights (49 MB). Input `image` (1, 3, 256, 256); output `logits` (1, 1, 256, 256). Matches full precision to within 0.00054 per pixel || `model.pt` | Full-precision PyTorch checkpoint for `load_checkpoint()` in the repo || `config.json` | Preprocessing, mask threshold (0.4), test-time augmentation || `example_1.jpg` | A Kvasir-SEG image (see `ATTRIBUTION.md`) || `example.py` | Segments the image and saves `mask.png` |
## Use it```bashpip install onnxruntime huggingface_hub numpy pillowpython example.py # writes mask.png``````pythonimport json, numpy as np, onnxruntime as ortfrom PIL import Imagefrom huggingface_hub import hf_hub_download
repo = "rigel08/polypshift-polyp-segmentation"cfg = json.load(open(hf_hub_download(repo, "config.json")))sess = ort.InferenceSession(hf_hub_download(repo, "model_fp16.onnx"))img = Image.open("frame.jpg").convert("RGB")x = (np.asarray(img.resize((256, 256)), np.float32) / 255 - cfg["imagenet_mean"]) / cfg["imagenet_std"]x = x.transpose(2, 0, 1)[None].astype(np.float32)prob = 1 / (1 + np.exp(-sess.run(None, {"image": x})[0][0, 0]))flip = 1 / (1 + np.exp(-sess.run(None, {"image": x[..., ::-1].copy()})[0][0, 0]))[:, ::-1]mask = ((prob + flip) / 2) >= cfg["mask_threshold"] # 256 x 256 polyp mask```
## Training data and licenceKvasir-SEG (Jha et al., MMM 2020) is licensed for **research and educational use only**, so these weights carry the same restriction.
## LimitationsOne training run. Every test image contains a polyp. Frames from the same video are not independent. Expect worse results on smallpolyps and on unfamiliar endoscopes.
**Portfolio:** https://rigel08.github.io/portfolio-site/ · **GitHub:** https://github.com/rigel08 · **All my models and demos:** https://huggingface.co/rigel08123456789101112131415161718{ "task": "colonoscopy polyp segmentation", "architecture": "U-Net with ImageNet-pretrained ResNet34 encoder", "image_size": 256, "imagenet_mean": [ 0.485, 0.456, 0.406 ], "imagenet_std": [ 0.229, 0.224, 0.225 ], "output": "logits (1,1,256,256); sigmoid -> per-pixel polyp probability", "mask_threshold": 0.4, "test_time_augmentation": "average of the image and its horizontal flip"}123456789101112131415161718192021"""Segment the example colonoscopy image and save the predicted polyp mask."""import jsonimport numpy as npimport onnxruntime as ortfrom PIL import Imagefrom huggingface_hub import hf_hub_download
REPO = "rigel08/polypshift-polyp-segmentation"cfg = json.load(open(hf_hub_download(REPO, "config.json")))sess = ort.InferenceSession(hf_hub_download(REPO, "model_fp16.onnx"))img = Image.open(hf_hub_download(REPO, "example_1.jpg")).convert("RGB")
x = (np.asarray(img.resize((256, 256)), np.float32) / 255 - np.array(cfg["imagenet_mean"])) / np.array(cfg["imagenet_std"])x = x.transpose(2, 0, 1)[None].astype(np.float32)sig = lambda z: 1 / (1 + np.exp(-z))prob = sig(sess.run(None, {"image": x})[0][0, 0])prob_flip = sig(sess.run(None, {"image": np.ascontiguousarray(x[..., ::-1])})[0][0, 0])[:, ::-1]prob = (prob + prob_flip) / 2 # test-time augmentationmask = prob >= cfg["mask_threshold"]Image.fromarray((mask * 255).astype(np.uint8)).resize(img.size, Image.NEAREST).save("mask.png")print(f"polyp covers {mask.mean():.1%} of the image; mask saved to mask.png")123version https://git-lfs.github.com/spec/v1oid sha256:ce9e87d96ad7fd41847b1a40fcbeadf72dcb2abdc9aa867ada200482812eb8f4size 97907567123version https://git-lfs.github.com/spec/v1oid sha256:b22d2cf7cbbaba828636c1b9430fc036f2852a64cecfd32cf12b33d1e0881c32size 49164793ATTRIBUTION.mdAdded+11
README.mdAdded+68
config.jsonAdded+18
example.pyAdded+21
example_1.jpgAdded

model.ptAdded+3
model_fp16.onnxAdded+3