|
from fastai.vision.all import * |
|
import gradio as gr |
|
import torchvision.transforms as transforms |
|
|
|
|
|
learn = load_learner('best_model.pkl') |
|
|
|
|
|
labels = learn.dls.vocab |
|
|
|
def transform_image(image, device): |
|
my_transforms = transforms.Compose([transforms.ToTensor(), |
|
transforms.Normalize( |
|
[0.485, 0.456, 0.406], |
|
[0.229, 0.224, 0.225])]) |
|
image_aux = image |
|
return my_transforms(image_aux).unsqueeze(0).to(device) |
|
|
|
def mask_to_img(mask): |
|
mask[mask == 1] = 255 |
|
mask[mask == 2] = 150 |
|
mask[mask == 3] = 74 |
|
mask[mask == 4] = 25 |
|
mask=np.reshape(mask,(480,640)) |
|
|
|
return mask |
|
|
|
|
|
def predict(img): |
|
device = torch.device("cuda" if torch.cuda.is_available() else "cpu") |
|
model = learn.cpu() |
|
model.eval() |
|
|
|
image = transforms.Resize((480,640))(img) |
|
tensor = transform_image(image, device) |
|
|
|
model.to(device) |
|
with torch.no_grad(): |
|
outputs = model(tensor) |
|
|
|
outputs = torch.argmax(outputs,1) |
|
|
|
mask = np.array(outputs.cpu()) |
|
mask = mask_to_img(mask) |
|
|
|
return Image.fromarray(mask.astype('uint8')) |
|
|
|
|
|
gr.Interface(fn=predict, inputs=gr.inputs.Image(shape=(128, 128)), outputs=gr.outputs.Image(shape=(128,128)),examples=['1002_5866_6582.jpg','1038_31199_2068.jpg']).launch(share=False) |
|
|