-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathgradio_inference.py
75 lines (59 loc) · 1.98 KB
/
gradio_inference.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
'''
- Step1. Load the ckpt
- Step2. Masking to the image (predict)
- Step3. Encode (rle -> mask)
- Step4. Return the image (gradio)
'''
import os, cv2, torch
import streamlit
import numpy as np
import gradio as gr
import albumentations as A
import torch.nn.functional as F
from torchvision.models.segmentation import fcn_resnet50
# Import from other files
from dataset import CLASSES, PALETTE, IND2CLASS, XRayInferenceDataset
from functions import encode_mask_to_rle, decode_rle_to_mask
from inference import load_model
from tools.streamlit.vis_test import get_class_color, overlay_masks
def test(model, image, thr=0.5):
# Preprocess
transform = A.Compose([
A.Resize(512, 512),
])
# Convert to RGB if needed
if len(image.shape) == 2:
image = cv2.cvtColor(image, cv2.COLOR_GRAY2RGB)
transformed = transform(image=image)['image']
# Normalize and convert to tensor
input_tensor = torch.from_numpy(transformed).permute(2, 0, 1).float().unsqueeze(0)
with torch.no_grad():
outputs = model(input_tensor)['out']
outputs = F.interpolate(outputs, size=(2048, 2048), mode="bilinear")
outputs = torch.sigmoid(outputs)
outputs = (outputs > thr).detach().numpy()
return outputs[0]
def segmentation_inference(image, model_path='./gradio_sample/checkpoints/sample_checkpoint.pt'):
""" main script file"""
# Load model
model = load_model(model_path)
# Process segmentation
masks = test(model, image)
# Overlay masks
result = overlay_masks(image, masks)
return result
def main():
iface = gr.Interface(
fn=segmentation_inference,
inputs=[
gr.Image(type="numpy", label="Input X-ray Image"),
],
outputs=[
gr.Image(type="numpy", label="Segmentation Result")
],
title="X-ray Image Segmentation",
description="Upload an X-ray image for bone segmentation"
)
iface.launch(share=True)
if __name__ == "__main__":
main()