Update app.py
Browse files
app.py
CHANGED
|
@@ -1,46 +1,41 @@
|
|
| 1 |
import gradio as gr
|
| 2 |
from fastai.vision.all import *
|
| 3 |
-
|
| 4 |
-
from pathlib import Path
|
| 5 |
-
import PIL
|
| 6 |
import torchvision.transforms as transforms
|
| 7 |
-
|
| 8 |
-
|
|
|
|
| 9 |
|
| 10 |
device = torch.device("cuda" if torch.cuda.is_available() else "cpu")
|
| 11 |
-
model = torch.jit.load("unet.pth")
|
| 12 |
-
model = model.cpu()
|
| 13 |
model.eval()
|
| 14 |
|
| 15 |
def transform_image(image):
|
| 16 |
-
|
| 17 |
-
|
| 18 |
-
|
| 19 |
-
|
| 20 |
-
|
|
|
|
| 21 |
|
| 22 |
-
|
| 23 |
-
|
| 24 |
-
|
| 25 |
-
|
| 26 |
-
|
| 27 |
-
with torch.no_grad():
|
| 28 |
-
|
| 29 |
-
|
| 30 |
-
|
| 31 |
-
|
| 32 |
-
|
| 33 |
-
mask = np.
|
| 34 |
-
mask
|
| 35 |
-
mask
|
| 36 |
-
mask
|
| 37 |
-
mask
|
| 38 |
-
mask[mask==4]=0
|
| 39 |
-
|
| 40 |
-
mask=np.reshape(mask,(480,640))
|
| 41 |
-
return Image.fromarray(mask.astype('uint8'))
|
| 42 |
-
|
| 43 |
-
|
| 44 |
|
| 45 |
-
|
| 46 |
-
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
import gradio as gr
|
| 2 |
from fastai.vision.all import *
|
|
|
|
|
|
|
|
|
|
| 3 |
import torchvision.transforms as transforms
|
| 4 |
+
import torch
|
| 5 |
+
from PIL import Image
|
| 6 |
+
import numpy as np
|
| 7 |
|
| 8 |
device = torch.device("cuda" if torch.cuda.is_available() else "cpu")
|
| 9 |
+
model = torch.jit.load("unet.pth").to(device)
|
|
|
|
| 10 |
model.eval()
|
| 11 |
|
| 12 |
def transform_image(image):
|
| 13 |
+
# Definimos las transformaciones necesarias para la imagen
|
| 14 |
+
resize_transform = transforms.Resize((480, 640))
|
| 15 |
+
tensor_transforms = transforms.Compose([
|
| 16 |
+
transforms.ToTensor(),
|
| 17 |
+
transforms.Normalize([0.485, 0.456, 0.406], [0.229, 0.224, 0.225])
|
| 18 |
+
])
|
| 19 |
|
| 20 |
+
# Aplicamos las transformaciones
|
| 21 |
+
image = resize_transform(Image.fromarray(image))
|
| 22 |
+
tensor = tensor_transforms(image).unsqueeze(0).to(device)
|
| 23 |
+
|
| 24 |
+
# Realizamos la inferencia
|
| 25 |
+
with torch.no_grad():
|
| 26 |
+
outputs = model(tensor)
|
| 27 |
+
outputs = torch.argmax(outputs, 1)
|
| 28 |
+
|
| 29 |
+
# Convertimos el tensor de salida a una imagen
|
| 30 |
+
mask = np.array(outputs.cpu().squeeze(0))
|
| 31 |
+
mask = np.where(mask == 0, 255, mask)
|
| 32 |
+
mask = np.where(mask == 1, 150, mask)
|
| 33 |
+
mask = np.where(mask == 2, 76, mask)
|
| 34 |
+
mask = np.where(mask == 3, 25, mask)
|
| 35 |
+
mask = np.where(mask == 4, 0, mask)
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 36 |
|
| 37 |
+
mask = mask.reshape((480, 640))
|
| 38 |
+
return Image.fromarray(mask.astype('uint8'))
|
| 39 |
+
|
| 40 |
+
# Creamos la interfaz y la lanzamos.
|
| 41 |
+
gr.Interface(fn=transform_image, inputs=gr.inputs.Image(shape=(640, 480)), outputs=gr.outputs.Image(), examples=['color_154.jpg', 'color_189.jpg']).launch(share=False)
|