azhongai666666 commited on
Commit
6ab9bc6
·
verified ·
1 Parent(s): 1e26b6b

Create app.py

Browse files
Files changed (1) hide show
  1. app.py +55 -0
app.py ADDED
@@ -0,0 +1,55 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import torch
2
+ import torch.nn as nn
3
+ import torch.nn.functional as F
4
+ import math
5
+
6
+ from torch.nn.init import _calculate_fan_in_and_fan_out
7
+ from timm.models.layers import to_2tuple, trunc_normal_
8
+
9
+ import torchvision.transforms as transforms
10
+ from torchvision import models
11
+
12
+ import gradio as gr
13
+ from PIL import Image
14
+ import numpy as np
15
+ from matplotlib import pyplot as plt
16
+
17
+ # Get cpu or gpu device for training.
18
+ device = "cuda" if torch.cuda.is_available() else "mps" if torch.backends.mps.is_available() else "cpu"
19
+ print(f"Using {device} device")
20
+ t_model_load = dehazeformer_t().to(device)
21
+ t_model_load
22
+ best_model_weights = torch.load('best_t_model_weights.pth')
23
+ t_model_load.load_state_dict(best_model_weights)
24
+
25
+ def pred_one_image(inp):
26
+ one_image = np.array(inp.resize((256, 256)).convert("RGB"))/255
27
+ # convert to other format HWC -> CHW
28
+ one_image = np.moveaxis(one_image, -1, 0)
29
+ # mask = np.expand_dims(mask, 0)
30
+ one_image = torch.tensor(one_image).float()
31
+ one_image = one_image.unsqueeze(0)
32
+ one_image = one_image.to(device)
33
+
34
+ with torch.no_grad():
35
+ t_model_load.eval()
36
+ output = t_model_load(one_image)
37
+ print(output.shape)
38
+ output = output[0].cpu().permute((1, 2, 0))
39
+ plt.figure(figsize=(10, 10))
40
+ plt.imshow(output.numpy()) # convert CHW -> HWC
41
+ plt.axis("off")
42
+ # 保存图像,可以指定文件名和格式,例如 'image.png'
43
+ plt.savefig('image.png', format='png', dpi=300) # dpi是图像的分辨率
44
+ out_img = Image.open('image.png')
45
+
46
+ return out_img
47
+
48
+ demo = gr.Interface(fn=pred_one_image,
49
+ inputs=gr.Image(type="pil"),
50
+ outputs=gr.Image(type="pil"),
51
+ examples=[image_path],
52
+ )
53
+
54
+ demo.launch(debug=True)
55
+ # demo.launch()