Muhammad-Ahmed commited on
Commit
d9705f0
·
verified ·
1 Parent(s): 0112148
Files changed (1) hide show
  1. app.py +53 -0
app.py ADDED
@@ -0,0 +1,53 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import torch
2
+ import torch.nn as nn
3
+ from torchvision import transforms
4
+ from PIL import Image
5
+ import numpy as np
6
+ import gradio as gr
7
+
8
+ # -------- Define your U-Net model (same as training) --------
9
+ class UNet(nn.Module):
10
+ def __init__(self):
11
+ super(UNet, self).__init__()
12
+ # define your encoder-decoder here
13
+ # simplified example
14
+ self.conv1 = nn.Conv2d(1, 16, 3, padding=1)
15
+ self.conv2 = nn.Conv2d(16, 3, 3, padding=1)
16
+
17
+ def forward(self, x):
18
+ x = torch.relu(self.conv1(x))
19
+ x = torch.sigmoid(self.conv2(x))
20
+ return x
21
+
22
+ # -------- Load model --------
23
+ model = UNet()
24
+ model.load_state_dict(torch.load("unet_model.pth", map_location="cpu"))
25
+ model.eval()
26
+
27
+ # -------- Preprocessing & Postprocessing --------
28
+ def predict(image):
29
+ # Resize and convert to tensor
30
+ transform = transforms.Compose([
31
+ transforms.Resize((256, 256)),
32
+ transforms.ToTensor()
33
+ ])
34
+ img = transform(image).unsqueeze(0) # add batch dimension
35
+
36
+ with torch.no_grad():
37
+ output = model(img)
38
+
39
+ # Convert output tensor to image
40
+ output_img = output.squeeze(0).permute(1, 2, 0).numpy()
41
+ output_img = (output_img * 255).astype(np.uint8)
42
+ return Image.fromarray(output_img)
43
+
44
+ # -------- Gradio Interface --------
45
+ iface = gr.Interface(
46
+ fn=predict,
47
+ inputs=gr.Image(type="pil"),
48
+ outputs=gr.Image(type="pil"),
49
+ title="U-Net Pseudo-Color Edge Detection",
50
+ description="Upload an image to see pseudo-color edge detection using U-Net."
51
+ )
52
+
53
+ iface.launch()