File size: 1,113 Bytes
6c0604d
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
"""Segment the example colonoscopy image and save the predicted polyp mask."""
import json
import numpy as np
import onnxruntime as ort
from PIL import Image
from 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 augmentation
mask = 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")