Zheng-MJ commited on
Commit
b9029bc
·
verified ·
1 Parent(s): 3c2e96e
Files changed (1) hide show
  1. app.py +173 -0
app.py ADDED
@@ -0,0 +1,173 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import os
2
+ import yaml
3
+ import torch
4
+ import argparse
5
+ import numpy as np
6
+ import gradio as gr
7
+
8
+ from PIL import Image
9
+ from copy import deepcopy
10
+ from torch.nn.parallel import DataParallel, DistributedDataParallel
11
+
12
+ from huggingface_hub import hf_hub_download
13
+ from gradio_imageslider import ImageSlider
14
+
15
+ ## local code
16
+ from models import seemore
17
+
18
+
19
+ def dict2namespace(config):
20
+ namespace = argparse.Namespace()
21
+ for key, value in config.items():
22
+ if isinstance(value, dict):
23
+ new_value = dict2namespace(value)
24
+ else:
25
+ new_value = value
26
+ setattr(namespace, key, new_value)
27
+ return namespace
28
+
29
+ def load_img (filename, norm=True,):
30
+ img = np.array(Image.open(filename).convert("RGB"))
31
+ h, w = img.shape[:2]
32
+
33
+ if w > 1920 or h > 1080:
34
+ new_h, new_w = h // 4, w // 4
35
+ img = np.array(Image.fromarray(img).resize((new_w, new_h), Image.BICUBIC))
36
+
37
+ if norm:
38
+ img = img / 255.
39
+ img = img.astype(np.float32)
40
+ return img
41
+
42
+ def process_img (image):
43
+ img = np.array(image)
44
+ img = img / 255.
45
+ img = img.astype(np.float32)
46
+ y = torch.tensor(img).permute(2,0,1).unsqueeze(0).to(device)
47
+
48
+ with torch.no_grad():
49
+ x_hat = model(y)
50
+
51
+ restored_img = x_hat.squeeze().permute(1,2,0).clamp_(0, 1).cpu().detach().numpy()
52
+ restored_img = np.clip(restored_img, 0. , 1.)
53
+
54
+ restored_img = (restored_img * 255.0).round().astype(np.uint8) # float32 to uint8
55
+ #return Image.fromarray(restored_img) #
56
+ return (image, Image.fromarray(restored_img))
57
+
58
+ def load_network(net, load_path, strict=True, param_key='params'):
59
+ if isinstance(net, (DataParallel, DistributedDataParallel)):
60
+ net = net.module
61
+ load_net = torch.load(load_path, map_location=lambda storage, loc: storage)
62
+ if param_key is not None:
63
+ if param_key not in load_net and 'params' in load_net:
64
+ param_key = 'params'
65
+ load_net = load_net[param_key]
66
+ # remove unnecessary 'module.'
67
+ for k, v in deepcopy(load_net).items():
68
+ if k.startswith('module.'):
69
+ load_net[k[7:]] = v
70
+ load_net.pop(k)
71
+ net.load_state_dict(load_net, strict=strict)
72
+
73
+ CONFIG = "configs/eval_seemore_t_x4.yml"
74
+ hf_hub_download(repo_id="eduardzamfir/SeemoRe-T", filename="SeemoRe_T_X4.pth", local_dir="./")
75
+ MODEL_NAME = "SeemoRe_T_X4.pth"
76
+
77
+ # parse config file
78
+ with open(os.path.join(CONFIG), "r") as f:
79
+ config = yaml.safe_load(f)
80
+
81
+ cfg = dict2namespace(config)
82
+
83
+ device = torch.device("cpu")
84
+ model = seemore.SeemoRe(scale=cfg.model.scale, in_chans=cfg.model.in_chans,
85
+ num_experts=cfg.model.num_experts, num_layers=cfg.model.num_layers, embedding_dim=cfg.model.embedding_dim,
86
+ img_range=cfg.model.img_range, use_shuffle=cfg.model.use_shuffle, global_kernel_size=cfg.model.global_kernel_size,
87
+ recursive=cfg.model.recursive, lr_space=cfg.model.lr_space, topk=cfg.model.topk)
88
+
89
+ model = model.to(device)
90
+ print ("IMAGE MODEL CKPT:", MODEL_NAME)
91
+ load_network(model, MODEL_NAME, strict=True, param_key='params')
92
+
93
+
94
+
95
+
96
+ title = "See More Details"
97
+ description = ''' ### See More Details: Efficient Image Super-Resolution by Experts Mining - ICML 2024, Vienna, Austria
98
+
99
+ #### [Eduard Zamfir<sup>1</sup>](https://eduardzamfir.github.io), [Zongwei Wu<sup>1*</sup>](https://sites.google.com/view/zwwu/accueil), [Nancy Mehta<sup>1</sup>](https://scholar.google.com/citations?user=WwdYdlUAAAAJ&hl=en&oi=ao), [Yulun Zhang<sup>2,3*</sup>](http://yulunzhang.com/) and [Radu Timofte<sup>1</sup>](https://www.informatik.uni-wuerzburg.de/computervision/)
100
+
101
+ #### **<sup>1</sup> University of Würzburg, Germany - <sup>2</sup> Shanghai Jiao Tong University, China - <sup>3</sup> ETH Zürich, Switzerland**
102
+ #### **<sup>*</sup> Corresponding authors**
103
+
104
+ <details>
105
+ <summary> <b> Abstract</b> (click me to read)</summary>
106
+ <p>
107
+ Reconstructing high-resolution (HR) images from low-resolution (LR) inputs poses a significant challenge in image super-resolution (SR). While recent approaches have demonstrated the efficacy of intricate operations customized for various objectives, the straightforward stacking of these disparate operations can result in a substantial computational burden, hampering their practical utility. In response, we introduce **S**eemo**R**e, an efficient SR model employing expert mining. Our approach strategically incorporates experts at different levels, adopting a collaborative methodology. At the macro scale, our experts address rank-wise and spatial-wise informative features, providing a holistic understanding. Subsequently, the model delves into the subtleties of rank choice by leveraging a mixture of low-rank experts. By tapping into experts specialized in distinct key factors crucial for accurate SR, our model excels in uncovering intricate intra-feature details. This collaborative approach is reminiscent of the concept of **see more**, allowing our model to achieve an optimal performance with minimal computational costs in efficient settings
108
+ </p>
109
+ </details>
110
+
111
+
112
+ #### Drag the slider on the super-resolution image left and right to see the changes in the image details. SeemoRe performs x4 upscaling on the input image.
113
+
114
+ <br>
115
+
116
+ <code>
117
+ @inproceedings{zamfir2024details,
118
+ title={See More Details: Efficient Image Super-Resolution by Experts Mining},
119
+ author={Eduard Zamfir and Zongwei Wu and Nancy Mehta and Yulun Zhang and Radu Timofte},
120
+ booktitle={International Conference on Machine Learning},
121
+ year={2024},
122
+ organization={PMLR}
123
+ }
124
+ </code>
125
+ <br>
126
+ '''
127
+
128
+
129
+ article = "<p style='text-align: center'><a href='https://eduardzamfir.github.io/seemore' target='_blank'>See More Details: Efficient Image Super-Resolution by Experts Mining</a></p>"
130
+
131
+ #### Image,Prompts examples
132
+ examples = [
133
+ ['images/0801x4.png'],
134
+ ['images/0840x4.png'],
135
+ ['images/0841x4.png'],
136
+ ['images/0870x4.png'],
137
+ ['images/0878x4.png'],
138
+ ['images/0884x4.png'],
139
+ ['images/0900x4.png'],
140
+ ['images/img002x4.png'],
141
+ ['images/img003x4.png'],
142
+ ['images/img004x4.png'],
143
+ ['images/img035x4.png'],
144
+ ['images/img053x4.png'],
145
+ ['images/img064x4.png'],
146
+ ['images/img083x4.png'],
147
+ ['images/img092x4.png'],
148
+ ]
149
+
150
+ css = """
151
+ .image-frame img, .image-container img {
152
+ width: auto;
153
+ height: auto;
154
+ max-width: none;
155
+ }
156
+ """
157
+
158
+ demo = gr.Interface(
159
+ fn=process_img,
160
+ inputs=[gr.Image(type="pil", label="Input", value="images/0878x4.png"),],
161
+ outputs=ImageSlider(label="Super-Resolved Image",
162
+ type="pil",
163
+ show_download_button=True,
164
+ ), #[gr.Image(type="pil", label="Ouput", min_width=500)],
165
+ title=title,
166
+ description=description,
167
+ article=article,
168
+ examples=examples,
169
+ css=css,
170
+ )
171
+
172
+ if __name__ == "__main__":
173
+ demo.launch()