add
Browse files- .idea/.gitignore +8 -0
- .idea/SwinIR.iml +12 -0
- .idea/inspectionProfiles/Project_Default.xml +24 -0
- .idea/inspectionProfiles/profiles_settings.xml +6 -0
- .idea/misc.xml +4 -0
- .idea/modules.xml +8 -0
- LICENSE +201 -0
- app.py +31 -0
- butterfly.png +0 -0
- cog.yaml +17 -0
- download-weights.sh +13 -0
- experiments/pretrained_models/README.md +1 -0
- main_test_swinir.py +288 -0
- model_zoo/README.md +3 -0
- models/__pycache__/network_swinir.cpython-37.pyc +0 -0
- models/network_swinir.py +866 -0
- predict.py +159 -0
- testsets/data/Lincoln.png +0 -0
- testsets/data/butterfly.png +0 -0
- testsets/data/tiger.png +0 -0
- utils/__pycache__/util_calculate_psnr_ssim.cpython-37.pyc +0 -0
- utils/util_calculate_psnr_ssim.py +346 -0
.idea/.gitignore
ADDED
@@ -0,0 +1,8 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
# Default ignored files
|
2 |
+
/shelf/
|
3 |
+
/workspace.xml
|
4 |
+
# Editor-based HTTP Client requests
|
5 |
+
/httpRequests/
|
6 |
+
# Datasource local storage ignored files
|
7 |
+
/dataSources/
|
8 |
+
/dataSources.local.xml
|
.idea/SwinIR.iml
ADDED
@@ -0,0 +1,12 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
<?xml version="1.0" encoding="UTF-8"?>
|
2 |
+
<module type="PYTHON_MODULE" version="4">
|
3 |
+
<component name="NewModuleRootManager">
|
4 |
+
<content url="file://$MODULE_DIR$" />
|
5 |
+
<orderEntry type="jdk" jdkName="Python 3.7 (pytorch171) (13)" jdkType="Python SDK" />
|
6 |
+
<orderEntry type="sourceFolder" forTests="false" />
|
7 |
+
</component>
|
8 |
+
<component name="PyDocumentationSettings">
|
9 |
+
<option name="format" value="GOOGLE" />
|
10 |
+
<option name="myDocStringFormat" value="Google" />
|
11 |
+
</component>
|
12 |
+
</module>
|
.idea/inspectionProfiles/Project_Default.xml
ADDED
@@ -0,0 +1,24 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
<component name="InspectionProjectProfileManager">
|
2 |
+
<profile version="1.0">
|
3 |
+
<option name="myName" value="Project Default" />
|
4 |
+
<inspection_tool class="PyPackageRequirementsInspection" enabled="true" level="WARNING" enabled_by_default="true">
|
5 |
+
<option name="ignoredPackages">
|
6 |
+
<value>
|
7 |
+
<list size="11">
|
8 |
+
<item index="0" class="java.lang.String" itemvalue="easydict" />
|
9 |
+
<item index="1" class="java.lang.String" itemvalue="scikit-image" />
|
10 |
+
<item index="2" class="java.lang.String" itemvalue="albumentations" />
|
11 |
+
<item index="3" class="java.lang.String" itemvalue="kornia" />
|
12 |
+
<item index="4" class="java.lang.String" itemvalue="pytorch-lightning" />
|
13 |
+
<item index="5" class="java.lang.String" itemvalue="tensorflow" />
|
14 |
+
<item index="6" class="java.lang.String" itemvalue="hydra-core" />
|
15 |
+
<item index="7" class="java.lang.String" itemvalue="scikit-learn" />
|
16 |
+
<item index="8" class="java.lang.String" itemvalue="tabulate" />
|
17 |
+
<item index="9" class="java.lang.String" itemvalue="webdataset" />
|
18 |
+
<item index="10" class="java.lang.String" itemvalue="wldhx.yadisk-direct" />
|
19 |
+
</list>
|
20 |
+
</value>
|
21 |
+
</option>
|
22 |
+
</inspection_tool>
|
23 |
+
</profile>
|
24 |
+
</component>
|
.idea/inspectionProfiles/profiles_settings.xml
ADDED
@@ -0,0 +1,6 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
<component name="InspectionProjectProfileManager">
|
2 |
+
<settings>
|
3 |
+
<option name="USE_PROJECT_PROFILE" value="false" />
|
4 |
+
<version value="1.0" />
|
5 |
+
</settings>
|
6 |
+
</component>
|
.idea/misc.xml
ADDED
@@ -0,0 +1,4 @@
|
|
|
|
|
|
|
|
|
|
|
1 |
+
<?xml version="1.0" encoding="UTF-8"?>
|
2 |
+
<project version="4">
|
3 |
+
<component name="ProjectRootManager" version="2" project-jdk-name="Python 3.7 (pytorch171) (13)" project-jdk-type="Python SDK" />
|
4 |
+
</project>
|
.idea/modules.xml
ADDED
@@ -0,0 +1,8 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
<?xml version="1.0" encoding="UTF-8"?>
|
2 |
+
<project version="4">
|
3 |
+
<component name="ProjectModuleManager">
|
4 |
+
<modules>
|
5 |
+
<module fileurl="file://$PROJECT_DIR$/.idea/SwinIR.iml" filepath="$PROJECT_DIR$/.idea/SwinIR.iml" />
|
6 |
+
</modules>
|
7 |
+
</component>
|
8 |
+
</project>
|
LICENSE
ADDED
@@ -0,0 +1,201 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
Apache License
|
2 |
+
Version 2.0, January 2004
|
3 |
+
http://www.apache.org/licenses/
|
4 |
+
|
5 |
+
TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
|
6 |
+
|
7 |
+
1. Definitions.
|
8 |
+
|
9 |
+
"License" shall mean the terms and conditions for use, reproduction,
|
10 |
+
and distribution as defined by Sections 1 through 9 of this document.
|
11 |
+
|
12 |
+
"Licensor" shall mean the copyright owner or entity authorized by
|
13 |
+
the copyright owner that is granting the License.
|
14 |
+
|
15 |
+
"Legal Entity" shall mean the union of the acting entity and all
|
16 |
+
other entities that control, are controlled by, or are under common
|
17 |
+
control with that entity. For the purposes of this definition,
|
18 |
+
"control" means (i) the power, direct or indirect, to cause the
|
19 |
+
direction or management of such entity, whether by contract or
|
20 |
+
otherwise, or (ii) ownership of fifty percent (50%) or more of the
|
21 |
+
outstanding shares, or (iii) beneficial ownership of such entity.
|
22 |
+
|
23 |
+
"You" (or "Your") shall mean an individual or Legal Entity
|
24 |
+
exercising permissions granted by this License.
|
25 |
+
|
26 |
+
"Source" form shall mean the preferred form for making modifications,
|
27 |
+
including but not limited to software source code, documentation
|
28 |
+
source, and configuration files.
|
29 |
+
|
30 |
+
"Object" form shall mean any form resulting from mechanical
|
31 |
+
transformation or translation of a Source form, including but
|
32 |
+
not limited to compiled object code, generated documentation,
|
33 |
+
and conversions to other media types.
|
34 |
+
|
35 |
+
"Work" shall mean the work of authorship, whether in Source or
|
36 |
+
Object form, made available under the License, as indicated by a
|
37 |
+
copyright notice that is included in or attached to the work
|
38 |
+
(an example is provided in the Appendix below).
|
39 |
+
|
40 |
+
"Derivative Works" shall mean any work, whether in Source or Object
|
41 |
+
form, that is based on (or derived from) the Work and for which the
|
42 |
+
editorial revisions, annotations, elaborations, or other modifications
|
43 |
+
represent, as a whole, an original work of authorship. For the purposes
|
44 |
+
of this License, Derivative Works shall not include works that remain
|
45 |
+
separable from, or merely link (or bind by name) to the interfaces of,
|
46 |
+
the Work and Derivative Works thereof.
|
47 |
+
|
48 |
+
"Contribution" shall mean any work of authorship, including
|
49 |
+
the original version of the Work and any modifications or additions
|
50 |
+
to that Work or Derivative Works thereof, that is intentionally
|
51 |
+
submitted to Licensor for inclusion in the Work by the copyright owner
|
52 |
+
or by an individual or Legal Entity authorized to submit on behalf of
|
53 |
+
the copyright owner. For the purposes of this definition, "submitted"
|
54 |
+
means any form of electronic, verbal, or written communication sent
|
55 |
+
to the Licensor or its representatives, including but not limited to
|
56 |
+
communication on electronic mailing lists, source code control systems,
|
57 |
+
and issue tracking systems that are managed by, or on behalf of, the
|
58 |
+
Licensor for the purpose of discussing and improving the Work, but
|
59 |
+
excluding communication that is conspicuously marked or otherwise
|
60 |
+
designated in writing by the copyright owner as "Not a Contribution."
|
61 |
+
|
62 |
+
"Contributor" shall mean Licensor and any individual or Legal Entity
|
63 |
+
on behalf of whom a Contribution has been received by Licensor and
|
64 |
+
subsequently incorporated within the Work.
|
65 |
+
|
66 |
+
2. Grant of Copyright License. Subject to the terms and conditions of
|
67 |
+
this License, each Contributor hereby grants to You a perpetual,
|
68 |
+
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
|
69 |
+
copyright license to reproduce, prepare Derivative Works of,
|
70 |
+
publicly display, publicly perform, sublicense, and distribute the
|
71 |
+
Work and such Derivative Works in Source or Object form.
|
72 |
+
|
73 |
+
3. Grant of Patent License. Subject to the terms and conditions of
|
74 |
+
this License, each Contributor hereby grants to You a perpetual,
|
75 |
+
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
|
76 |
+
(except as stated in this section) patent license to make, have made,
|
77 |
+
use, offer to sell, sell, import, and otherwise transfer the Work,
|
78 |
+
where such license applies only to those patent claims licensable
|
79 |
+
by such Contributor that are necessarily infringed by their
|
80 |
+
Contribution(s) alone or by combination of their Contribution(s)
|
81 |
+
with the Work to which such Contribution(s) was submitted. If You
|
82 |
+
institute patent litigation against any entity (including a
|
83 |
+
cross-claim or counterclaim in a lawsuit) alleging that the Work
|
84 |
+
or a Contribution incorporated within the Work constitutes direct
|
85 |
+
or contributory patent infringement, then any patent licenses
|
86 |
+
granted to You under this License for that Work shall terminate
|
87 |
+
as of the date such litigation is filed.
|
88 |
+
|
89 |
+
4. Redistribution. You may reproduce and distribute copies of the
|
90 |
+
Work or Derivative Works thereof in any medium, with or without
|
91 |
+
modifications, and in Source or Object form, provided that You
|
92 |
+
meet the following conditions:
|
93 |
+
|
94 |
+
(a) You must give any other recipients of the Work or
|
95 |
+
Derivative Works a copy of this License; and
|
96 |
+
|
97 |
+
(b) You must cause any modified files to carry prominent notices
|
98 |
+
stating that You changed the files; and
|
99 |
+
|
100 |
+
(c) You must retain, in the Source form of any Derivative Works
|
101 |
+
that You distribute, all copyright, patent, trademark, and
|
102 |
+
attribution notices from the Source form of the Work,
|
103 |
+
excluding those notices that do not pertain to any part of
|
104 |
+
the Derivative Works; and
|
105 |
+
|
106 |
+
(d) If the Work includes a "NOTICE" text file as part of its
|
107 |
+
distribution, then any Derivative Works that You distribute must
|
108 |
+
include a readable copy of the attribution notices contained
|
109 |
+
within such NOTICE file, excluding those notices that do not
|
110 |
+
pertain to any part of the Derivative Works, in at least one
|
111 |
+
of the following places: within a NOTICE text file distributed
|
112 |
+
as part of the Derivative Works; within the Source form or
|
113 |
+
documentation, if provided along with the Derivative Works; or,
|
114 |
+
within a display generated by the Derivative Works, if and
|
115 |
+
wherever such third-party notices normally appear. The contents
|
116 |
+
of the NOTICE file are for informational purposes only and
|
117 |
+
do not modify the License. You may add Your own attribution
|
118 |
+
notices within Derivative Works that You distribute, alongside
|
119 |
+
or as an addendum to the NOTICE text from the Work, provided
|
120 |
+
that such additional attribution notices cannot be construed
|
121 |
+
as modifying the License.
|
122 |
+
|
123 |
+
You may add Your own copyright statement to Your modifications and
|
124 |
+
may provide additional or different license terms and conditions
|
125 |
+
for use, reproduction, or distribution of Your modifications, or
|
126 |
+
for any such Derivative Works as a whole, provided Your use,
|
127 |
+
reproduction, and distribution of the Work otherwise complies with
|
128 |
+
the conditions stated in this License.
|
129 |
+
|
130 |
+
5. Submission of Contributions. Unless You explicitly state otherwise,
|
131 |
+
any Contribution intentionally submitted for inclusion in the Work
|
132 |
+
by You to the Licensor shall be under the terms and conditions of
|
133 |
+
this License, without any additional terms or conditions.
|
134 |
+
Notwithstanding the above, nothing herein shall supersede or modify
|
135 |
+
the terms of any separate license agreement you may have executed
|
136 |
+
with Licensor regarding such Contributions.
|
137 |
+
|
138 |
+
6. Trademarks. This License does not grant permission to use the trade
|
139 |
+
names, trademarks, service marks, or product names of the Licensor,
|
140 |
+
except as required for reasonable and customary use in describing the
|
141 |
+
origin of the Work and reproducing the content of the NOTICE file.
|
142 |
+
|
143 |
+
7. Disclaimer of Warranty. Unless required by applicable law or
|
144 |
+
agreed to in writing, Licensor provides the Work (and each
|
145 |
+
Contributor provides its Contributions) on an "AS IS" BASIS,
|
146 |
+
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
|
147 |
+
implied, including, without limitation, any warranties or conditions
|
148 |
+
of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
|
149 |
+
PARTICULAR PURPOSE. You are solely responsible for determining the
|
150 |
+
appropriateness of using or redistributing the Work and assume any
|
151 |
+
risks associated with Your exercise of permissions under this License.
|
152 |
+
|
153 |
+
8. Limitation of Liability. In no event and under no legal theory,
|
154 |
+
whether in tort (including negligence), contract, or otherwise,
|
155 |
+
unless required by applicable law (such as deliberate and grossly
|
156 |
+
negligent acts) or agreed to in writing, shall any Contributor be
|
157 |
+
liable to You for damages, including any direct, indirect, special,
|
158 |
+
incidental, or consequential damages of any character arising as a
|
159 |
+
result of this License or out of the use or inability to use the
|
160 |
+
Work (including but not limited to damages for loss of goodwill,
|
161 |
+
work stoppage, computer failure or malfunction, or any and all
|
162 |
+
other commercial damages or losses), even if such Contributor
|
163 |
+
has been advised of the possibility of such damages.
|
164 |
+
|
165 |
+
9. Accepting Warranty or Additional Liability. While redistributing
|
166 |
+
the Work or Derivative Works thereof, You may choose to offer,
|
167 |
+
and charge a fee for, acceptance of support, warranty, indemnity,
|
168 |
+
or other liability obligations and/or rights consistent with this
|
169 |
+
License. However, in accepting such obligations, You may act only
|
170 |
+
on Your own behalf and on Your sole responsibility, not on behalf
|
171 |
+
of any other Contributor, and only if You agree to indemnify,
|
172 |
+
defend, and hold each Contributor harmless for any liability
|
173 |
+
incurred by, or claims asserted against, such Contributor by reason
|
174 |
+
of your accepting any such warranty or additional liability.
|
175 |
+
|
176 |
+
END OF TERMS AND CONDITIONS
|
177 |
+
|
178 |
+
APPENDIX: How to apply the Apache License to your work.
|
179 |
+
|
180 |
+
To apply the Apache License to your work, attach the following
|
181 |
+
boilerplate notice, with the fields enclosed by brackets "[]"
|
182 |
+
replaced with your own identifying information. (Don't include
|
183 |
+
the brackets!) The text should be enclosed in the appropriate
|
184 |
+
comment syntax for the file format. We also recommend that a
|
185 |
+
file or class name and description of purpose be included on the
|
186 |
+
same "printed page" as the copyright notice for easier
|
187 |
+
identification within third-party archives.
|
188 |
+
|
189 |
+
Copyright [2021] [SwinIR Authors]
|
190 |
+
|
191 |
+
Licensed under the Apache License, Version 2.0 (the "License");
|
192 |
+
you may not use this file except in compliance with the License.
|
193 |
+
You may obtain a copy of the License at
|
194 |
+
|
195 |
+
http://www.apache.org/licenses/LICENSE-2.0
|
196 |
+
|
197 |
+
Unless required by applicable law or agreed to in writing, software
|
198 |
+
distributed under the License is distributed on an "AS IS" BASIS,
|
199 |
+
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
200 |
+
See the License for the specific language governing permissions and
|
201 |
+
limitations under the License.
|
app.py
ADDED
@@ -0,0 +1,31 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
import os
|
2 |
+
# os.system("wget https://github.com/JingyunLiang/SwinIR/releases/download/v0.0/003_realSR_BSRGAN_DFOWMFC_s64w8_SwinIR-L_x4_GAN.pth -P experiments/pretrained_models")
|
3 |
+
import gradio as gr
|
4 |
+
from PIL import Image, ImageOps
|
5 |
+
import numpy as np
|
6 |
+
|
7 |
+
if not os.path.exists("data"):
|
8 |
+
os.mkdir("data")
|
9 |
+
if not os.path.exists("dataout"):
|
10 |
+
os.mkdir("dataout")
|
11 |
+
|
12 |
+
|
13 |
+
# os.rename("003_realSR_BSRGAN_DFOWMFC_s64w8_SwinIR-L_x4_GAN.pth", "experiments/pretrained_models/003_realSR_BSRGAN_DFOWMFC_s64w8_SwinIR-L_x4_GAN.pth")
|
14 |
+
def infer(img):
|
15 |
+
img = ImageOps.contain(img, (700, 700))
|
16 |
+
width, height = img.size
|
17 |
+
img.save("./data/data.png")
|
18 |
+
# os.system('python ./SwinIR/main_test_swinir.py --task real_sr --model_path ./experiments/pretrained_models/003_realSR_BSRGAN_DFOWMFC_s64w8_SwinIR-L_x4_GAN.pth --folder_lq ./data/ --scale 4 --large_model --tile 640')
|
19 |
+
return "./results/data.png"
|
20 |
+
|
21 |
+
|
22 |
+
inputs = [gr.inputs.Image(type='pil', label="Original Image")]
|
23 |
+
outputs = [gr.outputs.Image(type="file", label="output")]
|
24 |
+
title = "SwinIR: Image Restoration Using Swin Transformer,Super-Resolution part "
|
25 |
+
description = "Gradio demo for SwinIR: Super-Resolution part. To use it, simply upload your image, or click one of the examples to load them. Read more at the links below."
|
26 |
+
article = "<p style='text-align: center'><a href='https://arxiv.org/pdf/2108.10257.pdf' target='_blank'>SwinIR: Image Restoration Using Swin Transformer</a> | <a href='https://github.com/JingyunLiang/SwinIR' target='_blank'>Github Repo</a></p>"
|
27 |
+
examples = [
|
28 |
+
['butterfly.png']
|
29 |
+
]
|
30 |
+
gr.Interface(infer, inputs, outputs, title=title, description=description, article=article, examples=examples).launch(
|
31 |
+
enable_queue=True, cache_examples=True)
|
butterfly.png
ADDED
cog.yaml
ADDED
@@ -0,0 +1,17 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
build:
|
2 |
+
gpu: true
|
3 |
+
python_version: "3.8"
|
4 |
+
system_packages:
|
5 |
+
- "libgl1-mesa-glx"
|
6 |
+
- "libglib2.0-0"
|
7 |
+
python_packages:
|
8 |
+
- "torchvision==0.9.0"
|
9 |
+
- "torch==1.8.0"
|
10 |
+
- "numpy==1.19.4"
|
11 |
+
- "opencv-python==4.4.0.46"
|
12 |
+
- "tqdm==4.62.2"
|
13 |
+
- "Pillow==8.3.2"
|
14 |
+
- "timm==0.4.12"
|
15 |
+
- "ipython==7.19.0"
|
16 |
+
|
17 |
+
predict: "predict.py:Predictor"
|
download-weights.sh
ADDED
@@ -0,0 +1,13 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
#!/bin/sh
|
2 |
+
|
3 |
+
wget https://github.com/JingyunLiang/SwinIR/releases/download/v0.0/003_realSR_BSRGAN_DFO_s64w8_SwinIR-M_x4_GAN.pth -P experiments/pretrained_models
|
4 |
+
wget https://github.com/JingyunLiang/SwinIR/releases/download/v0.0/004_grayDN_DFWB_s128w8_SwinIR-M_noise15.pth -P experiments/pretrained_models
|
5 |
+
wget https://github.com/JingyunLiang/SwinIR/releases/download/v0.0/004_grayDN_DFWB_s128w8_SwinIR-M_noise25.pth -P experiments/pretrained_models
|
6 |
+
wget https://github.com/JingyunLiang/SwinIR/releases/download/v0.0/004_grayDN_DFWB_s128w8_SwinIR-M_noise50.pth -P experiments/pretrained_models
|
7 |
+
wget https://github.com/JingyunLiang/SwinIR/releases/download/v0.0/005_colorDN_DFWB_s128w8_SwinIR-M_noise15.pth -P experiments/pretrained_models
|
8 |
+
wget https://github.com/JingyunLiang/SwinIR/releases/download/v0.0/005_colorDN_DFWB_s128w8_SwinIR-M_noise25.pth -P experiments/pretrained_models
|
9 |
+
wget https://github.com/JingyunLiang/SwinIR/releases/download/v0.0/005_colorDN_DFWB_s128w8_SwinIR-M_noise50.pth -P experiments/pretrained_models
|
10 |
+
wget https://github.com/JingyunLiang/SwinIR/releases/download/v0.0/006_CAR_DFWB_s126w7_SwinIR-M_jpeg10.pth -P experiments/pretrained_models
|
11 |
+
wget https://github.com/JingyunLiang/SwinIR/releases/download/v0.0/006_CAR_DFWB_s126w7_SwinIR-M_jpeg20.pth -P experiments/pretrained_models
|
12 |
+
wget https://github.com/JingyunLiang/SwinIR/releases/download/v0.0/006_CAR_DFWB_s126w7_SwinIR-M_jpeg30.pth -P experiments/pretrained_models
|
13 |
+
wget https://github.com/JingyunLiang/SwinIR/releases/download/v0.0/006_CAR_DFWB_s126w7_SwinIR-M_jpeg40.pth -P experiments/pretrained_models
|
experiments/pretrained_models/README.md
ADDED
@@ -0,0 +1 @@
|
|
|
|
|
1 |
+
# Put downloaded pre-trained models here
|
main_test_swinir.py
ADDED
@@ -0,0 +1,288 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
import argparse
|
2 |
+
import cv2
|
3 |
+
import glob
|
4 |
+
import numpy as np
|
5 |
+
from collections import OrderedDict
|
6 |
+
import os
|
7 |
+
import torch
|
8 |
+
import requests
|
9 |
+
|
10 |
+
from models.network_swinir import SwinIR as net
|
11 |
+
from utils import util_calculate_psnr_ssim as util
|
12 |
+
|
13 |
+
|
14 |
+
def main():
|
15 |
+
parser = argparse.ArgumentParser()
|
16 |
+
parser.add_argument('--task', type=str, default='real_sr', help='classical_sr, lightweight_sr, real_sr, '
|
17 |
+
'gray_dn, color_dn, jpeg_car')
|
18 |
+
parser.add_argument('--scale', type=int, default=4, help='scale factor: 1, 2, 3, 4, 8') # 1 for dn and jpeg car
|
19 |
+
parser.add_argument('--noise', type=int, default=15, help='noise level: 15, 25, 50')
|
20 |
+
parser.add_argument('--jpeg', type=int, default=40, help='scale factor: 10, 20, 30, 40')
|
21 |
+
parser.add_argument('--training_patch_size', type=int, default=128, help='patch size used in training SwinIR. '
|
22 |
+
'Just used to differentiate two different settings in Table 2 of the paper. '
|
23 |
+
'Images are NOT tested patch by patch.')
|
24 |
+
parser.add_argument('--large_model', action='store_true', default=True, help='use large model, only provided for real image sr')
|
25 |
+
parser.add_argument('--model_path', type=str,
|
26 |
+
default='experiments/pretrained_models/003_realSR_BSRGAN_DFOWMFC_s64w8_SwinIR-L_x4_GAN.pth')
|
27 |
+
parser.add_argument('--folder_lq', type=str, default='testsets\data', help='input low-quality test image folder')
|
28 |
+
parser.add_argument('--folder_gt', type=str, default=None, help='input ground-truth test image folder')
|
29 |
+
parser.add_argument('--tile', type=int, default=640, help='Tile size, None for no tile during testing (testing as a whole)')
|
30 |
+
parser.add_argument('--tile_overlap', type=int, default=32, help='Overlapping of different tiles')
|
31 |
+
args = parser.parse_args()
|
32 |
+
|
33 |
+
device = torch.device('cuda' if torch.cuda.is_available() else 'cpu')
|
34 |
+
# set up model
|
35 |
+
if os.path.exists(args.model_path):
|
36 |
+
print(f'loading model from {args.model_path}')
|
37 |
+
else:
|
38 |
+
os.makedirs(os.path.dirname(args.model_path), exist_ok=True)
|
39 |
+
url = 'https://github.com/JingyunLiang/SwinIR/releases/download/v0.0/{}'.format(os.path.basename(args.model_path))
|
40 |
+
r = requests.get(url, allow_redirects=True)
|
41 |
+
print(f'downloading model {args.model_path}')
|
42 |
+
open(args.model_path, 'wb').write(r.content)
|
43 |
+
|
44 |
+
model = define_model(args)
|
45 |
+
model.eval()
|
46 |
+
model = model.to(device)
|
47 |
+
|
48 |
+
# setup folder and path
|
49 |
+
folder, save_dir, border, window_size = setup(args)
|
50 |
+
os.makedirs(save_dir, exist_ok=True)
|
51 |
+
test_results = OrderedDict()
|
52 |
+
test_results['psnr'] = []
|
53 |
+
test_results['ssim'] = []
|
54 |
+
test_results['psnr_y'] = []
|
55 |
+
test_results['ssim_y'] = []
|
56 |
+
test_results['psnr_b'] = []
|
57 |
+
psnr, ssim, psnr_y, ssim_y, psnr_b = 0, 0, 0, 0, 0
|
58 |
+
|
59 |
+
for idx, path in enumerate(sorted(glob.glob(os.path.join(folder, '*')))):
|
60 |
+
# read image
|
61 |
+
imgname, img_lq, img_gt = get_image_pair(args, path) # image to HWC-BGR, float32
|
62 |
+
img_lq = np.transpose(img_lq if img_lq.shape[2] == 1 else img_lq[:, :, [2, 1, 0]], (2, 0, 1)) # HCW-BGR to CHW-RGB
|
63 |
+
img_lq = torch.from_numpy(img_lq).float().unsqueeze(0).to(device) # CHW-RGB to NCHW-RGB
|
64 |
+
|
65 |
+
# inference
|
66 |
+
with torch.no_grad():
|
67 |
+
# pad input image to be a multiple of window_size
|
68 |
+
_, _, h_old, w_old = img_lq.size()
|
69 |
+
h_pad = (h_old // window_size + 1) * window_size - h_old
|
70 |
+
w_pad = (w_old // window_size + 1) * window_size - w_old
|
71 |
+
img_lq = torch.cat([img_lq, torch.flip(img_lq, [2])], 2)[:, :, :h_old + h_pad, :]
|
72 |
+
img_lq = torch.cat([img_lq, torch.flip(img_lq, [3])], 3)[:, :, :, :w_old + w_pad]
|
73 |
+
output = test(img_lq, model, args, window_size)
|
74 |
+
output = output[..., :h_old * args.scale, :w_old * args.scale]
|
75 |
+
|
76 |
+
# save image
|
77 |
+
output = output.data.squeeze().float().cpu().clamp_(0, 1).numpy()
|
78 |
+
if output.ndim == 3:
|
79 |
+
output = np.transpose(output[[2, 1, 0], :, :], (1, 2, 0)) # CHW-RGB to HCW-BGR
|
80 |
+
output = (output * 255.0).round().astype(np.uint8) # float32 to uint8
|
81 |
+
cv2.imwrite(f'{save_dir}/{imgname}.png', output)
|
82 |
+
|
83 |
+
# evaluate psnr/ssim/psnr_b
|
84 |
+
if img_gt is not None:
|
85 |
+
img_gt = (img_gt * 255.0).round().astype(np.uint8) # float32 to uint8
|
86 |
+
img_gt = img_gt[:h_old * args.scale, :w_old * args.scale, ...] # crop gt
|
87 |
+
img_gt = np.squeeze(img_gt)
|
88 |
+
|
89 |
+
psnr = util.calculate_psnr(output, img_gt, crop_border=border)
|
90 |
+
ssim = util.calculate_ssim(output, img_gt, crop_border=border)
|
91 |
+
test_results['psnr'].append(psnr)
|
92 |
+
test_results['ssim'].append(ssim)
|
93 |
+
if img_gt.ndim == 3: # RGB image
|
94 |
+
psnr_y = util.calculate_psnr(output, img_gt, crop_border=border, test_y_channel=True)
|
95 |
+
ssim_y = util.calculate_ssim(output, img_gt, crop_border=border, test_y_channel=True)
|
96 |
+
test_results['psnr_y'].append(psnr_y)
|
97 |
+
test_results['ssim_y'].append(ssim_y)
|
98 |
+
if args.task in ['jpeg_car']:
|
99 |
+
psnr_b = util.calculate_psnrb(output, img_gt, crop_border=border, test_y_channel=True)
|
100 |
+
test_results['psnr_b'].append(psnr_b)
|
101 |
+
print('Testing {:d} {:20s} - PSNR: {:.2f} dB; SSIM: {:.4f}; '
|
102 |
+
'PSNR_Y: {:.2f} dB; SSIM_Y: {:.4f}; '
|
103 |
+
'PSNR_B: {:.2f} dB.'.
|
104 |
+
format(idx, imgname, psnr, ssim, psnr_y, ssim_y, psnr_b))
|
105 |
+
else:
|
106 |
+
print('Testing {:d} {:20s}'.format(idx, imgname))
|
107 |
+
|
108 |
+
# summarize psnr/ssim
|
109 |
+
if img_gt is not None:
|
110 |
+
ave_psnr = sum(test_results['psnr']) / len(test_results['psnr'])
|
111 |
+
ave_ssim = sum(test_results['ssim']) / len(test_results['ssim'])
|
112 |
+
print('\n{} \n-- Average PSNR/SSIM(RGB): {:.2f} dB; {:.4f}'.format(save_dir, ave_psnr, ave_ssim))
|
113 |
+
if img_gt.ndim == 3:
|
114 |
+
ave_psnr_y = sum(test_results['psnr_y']) / len(test_results['psnr_y'])
|
115 |
+
ave_ssim_y = sum(test_results['ssim_y']) / len(test_results['ssim_y'])
|
116 |
+
print('-- Average PSNR_Y/SSIM_Y: {:.2f} dB; {:.4f}'.format(ave_psnr_y, ave_ssim_y))
|
117 |
+
if args.task in ['jpeg_car']:
|
118 |
+
ave_psnr_b = sum(test_results['psnr_b']) / len(test_results['psnr_b'])
|
119 |
+
print('-- Average PSNR_B: {:.2f} dB'.format(ave_psnr_b))
|
120 |
+
|
121 |
+
|
122 |
+
def define_model(args):
|
123 |
+
# 001 classical image sr
|
124 |
+
if args.task == 'classical_sr':
|
125 |
+
model = net(upscale=args.scale, in_chans=3, img_size=args.training_patch_size, window_size=8,
|
126 |
+
img_range=1., depths=[6, 6, 6, 6, 6, 6], embed_dim=180, num_heads=[6, 6, 6, 6, 6, 6],
|
127 |
+
mlp_ratio=2, upsampler='pixelshuffle', resi_connection='1conv')
|
128 |
+
param_key_g = 'params'
|
129 |
+
|
130 |
+
# 002 lightweight image sr
|
131 |
+
# use 'pixelshuffledirect' to save parameters
|
132 |
+
elif args.task == 'lightweight_sr':
|
133 |
+
model = net(upscale=args.scale, in_chans=3, img_size=64, window_size=8,
|
134 |
+
img_range=1., depths=[6, 6, 6, 6], embed_dim=60, num_heads=[6, 6, 6, 6],
|
135 |
+
mlp_ratio=2, upsampler='pixelshuffledirect', resi_connection='1conv')
|
136 |
+
param_key_g = 'params'
|
137 |
+
|
138 |
+
# 003 real-world image sr
|
139 |
+
elif args.task == 'real_sr':
|
140 |
+
if not args.large_model:
|
141 |
+
# use 'nearest+conv' to avoid block artifacts
|
142 |
+
model = net(upscale=4, in_chans=3, img_size=64, window_size=8,
|
143 |
+
img_range=1., depths=[6, 6, 6, 6, 6, 6], embed_dim=180, num_heads=[6, 6, 6, 6, 6, 6],
|
144 |
+
mlp_ratio=2, upsampler='nearest+conv', resi_connection='1conv')
|
145 |
+
else:
|
146 |
+
# larger model size; use '3conv' to save parameters and memory; use ema for GAN training
|
147 |
+
model = net(upscale=4, in_chans=3, img_size=64, window_size=8,
|
148 |
+
img_range=1., depths=[6, 6, 6, 6, 6, 6, 6, 6, 6], embed_dim=240,
|
149 |
+
num_heads=[8, 8, 8, 8, 8, 8, 8, 8, 8],
|
150 |
+
mlp_ratio=2, upsampler='nearest+conv', resi_connection='3conv')
|
151 |
+
param_key_g = 'params_ema'
|
152 |
+
|
153 |
+
# 004 grayscale image denoising
|
154 |
+
elif args.task == 'gray_dn':
|
155 |
+
model = net(upscale=1, in_chans=1, img_size=128, window_size=8,
|
156 |
+
img_range=1., depths=[6, 6, 6, 6, 6, 6], embed_dim=180, num_heads=[6, 6, 6, 6, 6, 6],
|
157 |
+
mlp_ratio=2, upsampler='', resi_connection='1conv')
|
158 |
+
param_key_g = 'params'
|
159 |
+
|
160 |
+
# 005 color image denoising
|
161 |
+
elif args.task == 'color_dn':
|
162 |
+
model = net(upscale=1, in_chans=3, img_size=128, window_size=8,
|
163 |
+
img_range=1., depths=[6, 6, 6, 6, 6, 6], embed_dim=180, num_heads=[6, 6, 6, 6, 6, 6],
|
164 |
+
mlp_ratio=2, upsampler='', resi_connection='1conv')
|
165 |
+
param_key_g = 'params'
|
166 |
+
|
167 |
+
# 006 JPEG compression artifact reduction
|
168 |
+
# use window_size=7 because JPEG encoding uses 8x8; use img_range=255 because it's sligtly better than 1
|
169 |
+
elif args.task == 'jpeg_car':
|
170 |
+
model = net(upscale=1, in_chans=1, img_size=126, window_size=7,
|
171 |
+
img_range=255., depths=[6, 6, 6, 6, 6, 6], embed_dim=180, num_heads=[6, 6, 6, 6, 6, 6],
|
172 |
+
mlp_ratio=2, upsampler='', resi_connection='1conv')
|
173 |
+
param_key_g = 'params'
|
174 |
+
|
175 |
+
pretrained_model = torch.load(args.model_path)
|
176 |
+
model.load_state_dict(pretrained_model[param_key_g] if param_key_g in pretrained_model.keys() else pretrained_model, strict=True)
|
177 |
+
|
178 |
+
return model
|
179 |
+
|
180 |
+
|
181 |
+
def setup(args):
|
182 |
+
# 001 classical image sr/ 002 lightweight image sr
|
183 |
+
if args.task in ['classical_sr', 'lightweight_sr']:
|
184 |
+
save_dir = f'results/swinir_{args.task}_x{args.scale}'
|
185 |
+
folder = args.folder_gt
|
186 |
+
border = args.scale
|
187 |
+
window_size = 8
|
188 |
+
|
189 |
+
# 003 real-world image sr
|
190 |
+
elif args.task in ['real_sr']:
|
191 |
+
# save_dir = f'results/swinir_{args.task}_x{args.scale}'
|
192 |
+
save_dir = f'results'
|
193 |
+
# if args.large_model:
|
194 |
+
# save_dir += '_large'
|
195 |
+
folder = args.folder_lq
|
196 |
+
border = 0
|
197 |
+
window_size = 8
|
198 |
+
|
199 |
+
# 004 grayscale image denoising/ 005 color image denoising
|
200 |
+
elif args.task in ['gray_dn', 'color_dn']:
|
201 |
+
save_dir = f'results/swinir_{args.task}_noise{args.noise}'
|
202 |
+
folder = args.folder_gt
|
203 |
+
border = 0
|
204 |
+
window_size = 8
|
205 |
+
|
206 |
+
# 006 JPEG compression artifact reduction
|
207 |
+
elif args.task in ['jpeg_car']:
|
208 |
+
save_dir = f'results/swinir_{args.task}_jpeg{args.jpeg}'
|
209 |
+
folder = args.folder_gt
|
210 |
+
border = 0
|
211 |
+
window_size = 7
|
212 |
+
|
213 |
+
return folder, save_dir, border, window_size
|
214 |
+
|
215 |
+
|
216 |
+
def get_image_pair(args, path):
|
217 |
+
(imgname, imgext) = os.path.splitext(os.path.basename(path))
|
218 |
+
|
219 |
+
# 001 classical image sr/ 002 lightweight image sr (load lq-gt image pairs)
|
220 |
+
if args.task in ['classical_sr', 'lightweight_sr']:
|
221 |
+
img_gt = cv2.imread(path, cv2.IMREAD_COLOR).astype(np.float32) / 255.
|
222 |
+
img_lq = cv2.imread(f'{args.folder_lq}/{imgname}x{args.scale}{imgext}', cv2.IMREAD_COLOR).astype(
|
223 |
+
np.float32) / 255.
|
224 |
+
|
225 |
+
# 003 real-world image sr (load lq image only)
|
226 |
+
elif args.task in ['real_sr']:
|
227 |
+
img_gt = None
|
228 |
+
img_lq = cv2.imread(path, cv2.IMREAD_COLOR).astype(np.float32) / 255.
|
229 |
+
|
230 |
+
# 004 grayscale image denoising (load gt image and generate lq image on-the-fly)
|
231 |
+
elif args.task in ['gray_dn']:
|
232 |
+
img_gt = cv2.imread(path, cv2.IMREAD_GRAYSCALE).astype(np.float32) / 255.
|
233 |
+
np.random.seed(seed=0)
|
234 |
+
img_lq = img_gt + np.random.normal(0, args.noise / 255., img_gt.shape)
|
235 |
+
img_gt = np.expand_dims(img_gt, axis=2)
|
236 |
+
img_lq = np.expand_dims(img_lq, axis=2)
|
237 |
+
|
238 |
+
# 005 color image denoising (load gt image and generate lq image on-the-fly)
|
239 |
+
elif args.task in ['color_dn']:
|
240 |
+
img_gt = cv2.imread(path, cv2.IMREAD_COLOR).astype(np.float32) / 255.
|
241 |
+
np.random.seed(seed=0)
|
242 |
+
img_lq = img_gt + np.random.normal(0, args.noise / 255., img_gt.shape)
|
243 |
+
|
244 |
+
# 006 JPEG compression artifact reduction (load gt image and generate lq image on-the-fly)
|
245 |
+
elif args.task in ['jpeg_car']:
|
246 |
+
img_gt = cv2.imread(path, cv2.IMREAD_UNCHANGED)
|
247 |
+
if img_gt.ndim != 2:
|
248 |
+
img_gt = util.bgr2ycbcr(img_gt, y_only=True)
|
249 |
+
result, encimg = cv2.imencode('.jpg', img_gt, [int(cv2.IMWRITE_JPEG_QUALITY), args.jpeg])
|
250 |
+
img_lq = cv2.imdecode(encimg, 0)
|
251 |
+
img_gt = np.expand_dims(img_gt, axis=2).astype(np.float32) / 255.
|
252 |
+
img_lq = np.expand_dims(img_lq, axis=2).astype(np.float32) / 255.
|
253 |
+
|
254 |
+
return imgname, img_lq, img_gt
|
255 |
+
|
256 |
+
|
257 |
+
def test(img_lq, model, args, window_size):
|
258 |
+
if args.tile is None:
|
259 |
+
# test the image as a whole
|
260 |
+
output = model(img_lq)
|
261 |
+
else:
|
262 |
+
# test the image tile by tile
|
263 |
+
b, c, h, w = img_lq.size()
|
264 |
+
tile = min(args.tile, h, w)
|
265 |
+
assert tile % window_size == 0, "tile size should be a multiple of window_size"
|
266 |
+
tile_overlap = args.tile_overlap
|
267 |
+
sf = args.scale
|
268 |
+
|
269 |
+
stride = tile - tile_overlap
|
270 |
+
h_idx_list = list(range(0, h-tile, stride)) + [h-tile]
|
271 |
+
w_idx_list = list(range(0, w-tile, stride)) + [w-tile]
|
272 |
+
E = torch.zeros(b, c, h*sf, w*sf).type_as(img_lq)
|
273 |
+
W = torch.zeros_like(E)
|
274 |
+
|
275 |
+
for h_idx in h_idx_list:
|
276 |
+
for w_idx in w_idx_list:
|
277 |
+
in_patch = img_lq[..., h_idx:h_idx+tile, w_idx:w_idx+tile]
|
278 |
+
out_patch = model(in_patch)
|
279 |
+
out_patch_mask = torch.ones_like(out_patch)
|
280 |
+
|
281 |
+
E[..., h_idx*sf:(h_idx+tile)*sf, w_idx*sf:(w_idx+tile)*sf].add_(out_patch)
|
282 |
+
W[..., h_idx*sf:(h_idx+tile)*sf, w_idx*sf:(w_idx+tile)*sf].add_(out_patch_mask)
|
283 |
+
output = E.div_(W)
|
284 |
+
|
285 |
+
return output
|
286 |
+
|
287 |
+
if __name__ == '__main__':
|
288 |
+
main()
|
model_zoo/README.md
ADDED
@@ -0,0 +1,3 @@
|
|
|
|
|
|
|
|
|
1 |
+
model_zoo
|
2 |
+
|
3 |
+
The SwinIR models are available at [here](https://github.com/JingyunLiang/SwinIR/releases/tag/v0.0).
|
models/__pycache__/network_swinir.cpython-37.pyc
ADDED
Binary file (28 kB). View file
|
|
models/network_swinir.py
ADDED
@@ -0,0 +1,866 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
# -----------------------------------------------------------------------------------
|
2 |
+
# SwinIR: Image Restoration Using Swin Transformer, https://arxiv.org/abs/2108.10257
|
3 |
+
# Originally Written by Ze Liu, Modified by Jingyun Liang.
|
4 |
+
# -----------------------------------------------------------------------------------
|
5 |
+
|
6 |
+
import math
|
7 |
+
import torch
|
8 |
+
import torch.nn as nn
|
9 |
+
import torch.nn.functional as F
|
10 |
+
import torch.utils.checkpoint as checkpoint
|
11 |
+
from timm.models.layers import DropPath, to_2tuple, trunc_normal_
|
12 |
+
|
13 |
+
|
14 |
+
class Mlp(nn.Module):
|
15 |
+
def __init__(self, in_features, hidden_features=None, out_features=None, act_layer=nn.GELU, drop=0.):
|
16 |
+
super().__init__()
|
17 |
+
out_features = out_features or in_features
|
18 |
+
hidden_features = hidden_features or in_features
|
19 |
+
self.fc1 = nn.Linear(in_features, hidden_features)
|
20 |
+
self.act = act_layer()
|
21 |
+
self.fc2 = nn.Linear(hidden_features, out_features)
|
22 |
+
self.drop = nn.Dropout(drop)
|
23 |
+
|
24 |
+
def forward(self, x):
|
25 |
+
x = self.fc1(x)
|
26 |
+
x = self.act(x)
|
27 |
+
x = self.drop(x)
|
28 |
+
x = self.fc2(x)
|
29 |
+
x = self.drop(x)
|
30 |
+
return x
|
31 |
+
|
32 |
+
|
33 |
+
def window_partition(x, window_size):
|
34 |
+
"""
|
35 |
+
Args:
|
36 |
+
x: (B, H, W, C)
|
37 |
+
window_size (int): window size
|
38 |
+
|
39 |
+
Returns:
|
40 |
+
windows: (num_windows*B, window_size, window_size, C)
|
41 |
+
"""
|
42 |
+
B, H, W, C = x.shape
|
43 |
+
x = x.view(B, H // window_size, window_size, W // window_size, window_size, C)
|
44 |
+
windows = x.permute(0, 1, 3, 2, 4, 5).contiguous().view(-1, window_size, window_size, C)
|
45 |
+
return windows
|
46 |
+
|
47 |
+
|
48 |
+
def window_reverse(windows, window_size, H, W):
|
49 |
+
"""
|
50 |
+
Args:
|
51 |
+
windows: (num_windows*B, window_size, window_size, C)
|
52 |
+
window_size (int): Window size
|
53 |
+
H (int): Height of image
|
54 |
+
W (int): Width of image
|
55 |
+
|
56 |
+
Returns:
|
57 |
+
x: (B, H, W, C)
|
58 |
+
"""
|
59 |
+
B = int(windows.shape[0] / (H * W / window_size / window_size))
|
60 |
+
x = windows.view(B, H // window_size, W // window_size, window_size, window_size, -1)
|
61 |
+
x = x.permute(0, 1, 3, 2, 4, 5).contiguous().view(B, H, W, -1)
|
62 |
+
return x
|
63 |
+
|
64 |
+
|
65 |
+
class WindowAttention(nn.Module):
|
66 |
+
r""" Window based multi-head self attention (W-MSA) module with relative position bias.
|
67 |
+
It supports both of shifted and non-shifted window.
|
68 |
+
|
69 |
+
Args:
|
70 |
+
dim (int): Number of input channels.
|
71 |
+
window_size (tuple[int]): The height and width of the window.
|
72 |
+
num_heads (int): Number of attention heads.
|
73 |
+
qkv_bias (bool, optional): If True, add a learnable bias to query, key, value. Default: True
|
74 |
+
qk_scale (float | None, optional): Override default qk scale of head_dim ** -0.5 if set
|
75 |
+
attn_drop (float, optional): Dropout ratio of attention weight. Default: 0.0
|
76 |
+
proj_drop (float, optional): Dropout ratio of output. Default: 0.0
|
77 |
+
"""
|
78 |
+
|
79 |
+
def __init__(self, dim, window_size, num_heads, qkv_bias=True, qk_scale=None, attn_drop=0., proj_drop=0.):
|
80 |
+
|
81 |
+
super().__init__()
|
82 |
+
self.dim = dim
|
83 |
+
self.window_size = window_size # Wh, Ww
|
84 |
+
self.num_heads = num_heads
|
85 |
+
head_dim = dim // num_heads
|
86 |
+
self.scale = qk_scale or head_dim ** -0.5
|
87 |
+
|
88 |
+
# define a parameter table of relative position bias
|
89 |
+
self.relative_position_bias_table = nn.Parameter(
|
90 |
+
torch.zeros((2 * window_size[0] - 1) * (2 * window_size[1] - 1), num_heads)) # 2*Wh-1 * 2*Ww-1, nH
|
91 |
+
|
92 |
+
# get pair-wise relative position index for each token inside the window
|
93 |
+
coords_h = torch.arange(self.window_size[0])
|
94 |
+
coords_w = torch.arange(self.window_size[1])
|
95 |
+
coords = torch.stack(torch.meshgrid([coords_h, coords_w])) # 2, Wh, Ww
|
96 |
+
coords_flatten = torch.flatten(coords, 1) # 2, Wh*Ww
|
97 |
+
relative_coords = coords_flatten[:, :, None] - coords_flatten[:, None, :] # 2, Wh*Ww, Wh*Ww
|
98 |
+
relative_coords = relative_coords.permute(1, 2, 0).contiguous() # Wh*Ww, Wh*Ww, 2
|
99 |
+
relative_coords[:, :, 0] += self.window_size[0] - 1 # shift to start from 0
|
100 |
+
relative_coords[:, :, 1] += self.window_size[1] - 1
|
101 |
+
relative_coords[:, :, 0] *= 2 * self.window_size[1] - 1
|
102 |
+
relative_position_index = relative_coords.sum(-1) # Wh*Ww, Wh*Ww
|
103 |
+
self.register_buffer("relative_position_index", relative_position_index)
|
104 |
+
|
105 |
+
self.qkv = nn.Linear(dim, dim * 3, bias=qkv_bias)
|
106 |
+
self.attn_drop = nn.Dropout(attn_drop)
|
107 |
+
self.proj = nn.Linear(dim, dim)
|
108 |
+
|
109 |
+
self.proj_drop = nn.Dropout(proj_drop)
|
110 |
+
|
111 |
+
trunc_normal_(self.relative_position_bias_table, std=.02)
|
112 |
+
self.softmax = nn.Softmax(dim=-1)
|
113 |
+
|
114 |
+
def forward(self, x, mask=None):
|
115 |
+
"""
|
116 |
+
Args:
|
117 |
+
x: input features with shape of (num_windows*B, N, C)
|
118 |
+
mask: (0/-inf) mask with shape of (num_windows, Wh*Ww, Wh*Ww) or None
|
119 |
+
"""
|
120 |
+
B_, N, C = x.shape
|
121 |
+
qkv = self.qkv(x).reshape(B_, N, 3, self.num_heads, C // self.num_heads).permute(2, 0, 3, 1, 4)
|
122 |
+
q, k, v = qkv[0], qkv[1], qkv[2] # make torchscript happy (cannot use tensor as tuple)
|
123 |
+
|
124 |
+
q = q * self.scale
|
125 |
+
attn = (q @ k.transpose(-2, -1))
|
126 |
+
|
127 |
+
relative_position_bias = self.relative_position_bias_table[self.relative_position_index.view(-1)].view(
|
128 |
+
self.window_size[0] * self.window_size[1], self.window_size[0] * self.window_size[1], -1) # Wh*Ww,Wh*Ww,nH
|
129 |
+
relative_position_bias = relative_position_bias.permute(2, 0, 1).contiguous() # nH, Wh*Ww, Wh*Ww
|
130 |
+
attn = attn + relative_position_bias.unsqueeze(0)
|
131 |
+
|
132 |
+
if mask is not None:
|
133 |
+
nW = mask.shape[0]
|
134 |
+
attn = attn.view(B_ // nW, nW, self.num_heads, N, N) + mask.unsqueeze(1).unsqueeze(0)
|
135 |
+
attn = attn.view(-1, self.num_heads, N, N)
|
136 |
+
attn = self.softmax(attn)
|
137 |
+
else:
|
138 |
+
attn = self.softmax(attn)
|
139 |
+
|
140 |
+
attn = self.attn_drop(attn)
|
141 |
+
|
142 |
+
x = (attn @ v).transpose(1, 2).reshape(B_, N, C)
|
143 |
+
x = self.proj(x)
|
144 |
+
x = self.proj_drop(x)
|
145 |
+
return x
|
146 |
+
|
147 |
+
def extra_repr(self) -> str:
|
148 |
+
return f'dim={self.dim}, window_size={self.window_size}, num_heads={self.num_heads}'
|
149 |
+
|
150 |
+
def flops(self, N):
|
151 |
+
# calculate flops for 1 window with token length of N
|
152 |
+
flops = 0
|
153 |
+
# qkv = self.qkv(x)
|
154 |
+
flops += N * self.dim * 3 * self.dim
|
155 |
+
# attn = (q @ k.transpose(-2, -1))
|
156 |
+
flops += self.num_heads * N * (self.dim // self.num_heads) * N
|
157 |
+
# x = (attn @ v)
|
158 |
+
flops += self.num_heads * N * N * (self.dim // self.num_heads)
|
159 |
+
# x = self.proj(x)
|
160 |
+
flops += N * self.dim * self.dim
|
161 |
+
return flops
|
162 |
+
|
163 |
+
|
164 |
+
class SwinTransformerBlock(nn.Module):
|
165 |
+
r""" Swin Transformer Block.
|
166 |
+
|
167 |
+
Args:
|
168 |
+
dim (int): Number of input channels.
|
169 |
+
input_resolution (tuple[int]): Input resulotion.
|
170 |
+
num_heads (int): Number of attention heads.
|
171 |
+
window_size (int): Window size.
|
172 |
+
shift_size (int): Shift size for SW-MSA.
|
173 |
+
mlp_ratio (float): Ratio of mlp hidden dim to embedding dim.
|
174 |
+
qkv_bias (bool, optional): If True, add a learnable bias to query, key, value. Default: True
|
175 |
+
qk_scale (float | None, optional): Override default qk scale of head_dim ** -0.5 if set.
|
176 |
+
drop (float, optional): Dropout rate. Default: 0.0
|
177 |
+
attn_drop (float, optional): Attention dropout rate. Default: 0.0
|
178 |
+
drop_path (float, optional): Stochastic depth rate. Default: 0.0
|
179 |
+
act_layer (nn.Module, optional): Activation layer. Default: nn.GELU
|
180 |
+
norm_layer (nn.Module, optional): Normalization layer. Default: nn.LayerNorm
|
181 |
+
"""
|
182 |
+
|
183 |
+
def __init__(self, dim, input_resolution, num_heads, window_size=7, shift_size=0,
|
184 |
+
mlp_ratio=4., qkv_bias=True, qk_scale=None, drop=0., attn_drop=0., drop_path=0.,
|
185 |
+
act_layer=nn.GELU, norm_layer=nn.LayerNorm):
|
186 |
+
super().__init__()
|
187 |
+
self.dim = dim
|
188 |
+
self.input_resolution = input_resolution
|
189 |
+
self.num_heads = num_heads
|
190 |
+
self.window_size = window_size
|
191 |
+
self.shift_size = shift_size
|
192 |
+
self.mlp_ratio = mlp_ratio
|
193 |
+
if min(self.input_resolution) <= self.window_size:
|
194 |
+
# if window size is larger than input resolution, we don't partition windows
|
195 |
+
self.shift_size = 0
|
196 |
+
self.window_size = min(self.input_resolution)
|
197 |
+
assert 0 <= self.shift_size < self.window_size, "shift_size must in 0-window_size"
|
198 |
+
|
199 |
+
self.norm1 = norm_layer(dim)
|
200 |
+
self.attn = WindowAttention(
|
201 |
+
dim, window_size=to_2tuple(self.window_size), num_heads=num_heads,
|
202 |
+
qkv_bias=qkv_bias, qk_scale=qk_scale, attn_drop=attn_drop, proj_drop=drop)
|
203 |
+
|
204 |
+
self.drop_path = DropPath(drop_path) if drop_path > 0. else nn.Identity()
|
205 |
+
self.norm2 = norm_layer(dim)
|
206 |
+
mlp_hidden_dim = int(dim * mlp_ratio)
|
207 |
+
self.mlp = Mlp(in_features=dim, hidden_features=mlp_hidden_dim, act_layer=act_layer, drop=drop)
|
208 |
+
|
209 |
+
if self.shift_size > 0:
|
210 |
+
attn_mask = self.calculate_mask(self.input_resolution)
|
211 |
+
else:
|
212 |
+
attn_mask = None
|
213 |
+
|
214 |
+
self.register_buffer("attn_mask", attn_mask)
|
215 |
+
|
216 |
+
def calculate_mask(self, x_size):
|
217 |
+
# calculate attention mask for SW-MSA
|
218 |
+
H, W = x_size
|
219 |
+
img_mask = torch.zeros((1, H, W, 1)) # 1 H W 1
|
220 |
+
h_slices = (slice(0, -self.window_size),
|
221 |
+
slice(-self.window_size, -self.shift_size),
|
222 |
+
slice(-self.shift_size, None))
|
223 |
+
w_slices = (slice(0, -self.window_size),
|
224 |
+
slice(-self.window_size, -self.shift_size),
|
225 |
+
slice(-self.shift_size, None))
|
226 |
+
cnt = 0
|
227 |
+
for h in h_slices:
|
228 |
+
for w in w_slices:
|
229 |
+
img_mask[:, h, w, :] = cnt
|
230 |
+
cnt += 1
|
231 |
+
|
232 |
+
mask_windows = window_partition(img_mask, self.window_size) # nW, window_size, window_size, 1
|
233 |
+
mask_windows = mask_windows.view(-1, self.window_size * self.window_size)
|
234 |
+
attn_mask = mask_windows.unsqueeze(1) - mask_windows.unsqueeze(2)
|
235 |
+
attn_mask = attn_mask.masked_fill(attn_mask != 0, float(-100.0)).masked_fill(attn_mask == 0, float(0.0))
|
236 |
+
|
237 |
+
return attn_mask
|
238 |
+
|
239 |
+
def forward(self, x, x_size):
|
240 |
+
H, W = x_size
|
241 |
+
B, L, C = x.shape
|
242 |
+
# assert L == H * W, "input feature has wrong size"
|
243 |
+
|
244 |
+
shortcut = x
|
245 |
+
x = self.norm1(x)
|
246 |
+
x = x.view(B, H, W, C)
|
247 |
+
|
248 |
+
# cyclic shift
|
249 |
+
if self.shift_size > 0:
|
250 |
+
shifted_x = torch.roll(x, shifts=(-self.shift_size, -self.shift_size), dims=(1, 2))
|
251 |
+
else:
|
252 |
+
shifted_x = x
|
253 |
+
|
254 |
+
# partition windows
|
255 |
+
x_windows = window_partition(shifted_x, self.window_size) # nW*B, window_size, window_size, C
|
256 |
+
x_windows = x_windows.view(-1, self.window_size * self.window_size, C) # nW*B, window_size*window_size, C
|
257 |
+
|
258 |
+
# W-MSA/SW-MSA (to be compatible for testing on images whose shapes are the multiple of window size
|
259 |
+
if self.input_resolution == x_size:
|
260 |
+
attn_windows = self.attn(x_windows, mask=self.attn_mask) # nW*B, window_size*window_size, C
|
261 |
+
else:
|
262 |
+
attn_windows = self.attn(x_windows, mask=self.calculate_mask(x_size).to(x.device))
|
263 |
+
|
264 |
+
# merge windows
|
265 |
+
attn_windows = attn_windows.view(-1, self.window_size, self.window_size, C)
|
266 |
+
shifted_x = window_reverse(attn_windows, self.window_size, H, W) # B H' W' C
|
267 |
+
|
268 |
+
# reverse cyclic shift
|
269 |
+
if self.shift_size > 0:
|
270 |
+
x = torch.roll(shifted_x, shifts=(self.shift_size, self.shift_size), dims=(1, 2))
|
271 |
+
else:
|
272 |
+
x = shifted_x
|
273 |
+
x = x.view(B, H * W, C)
|
274 |
+
|
275 |
+
# FFN
|
276 |
+
x = shortcut + self.drop_path(x)
|
277 |
+
x = x + self.drop_path(self.mlp(self.norm2(x)))
|
278 |
+
|
279 |
+
return x
|
280 |
+
|
281 |
+
def extra_repr(self) -> str:
|
282 |
+
return f"dim={self.dim}, input_resolution={self.input_resolution}, num_heads={self.num_heads}, " \
|
283 |
+
f"window_size={self.window_size}, shift_size={self.shift_size}, mlp_ratio={self.mlp_ratio}"
|
284 |
+
|
285 |
+
def flops(self):
|
286 |
+
flops = 0
|
287 |
+
H, W = self.input_resolution
|
288 |
+
# norm1
|
289 |
+
flops += self.dim * H * W
|
290 |
+
# W-MSA/SW-MSA
|
291 |
+
nW = H * W / self.window_size / self.window_size
|
292 |
+
flops += nW * self.attn.flops(self.window_size * self.window_size)
|
293 |
+
# mlp
|
294 |
+
flops += 2 * H * W * self.dim * self.dim * self.mlp_ratio
|
295 |
+
# norm2
|
296 |
+
flops += self.dim * H * W
|
297 |
+
return flops
|
298 |
+
|
299 |
+
|
300 |
+
class PatchMerging(nn.Module):
|
301 |
+
r""" Patch Merging Layer.
|
302 |
+
|
303 |
+
Args:
|
304 |
+
input_resolution (tuple[int]): Resolution of input feature.
|
305 |
+
dim (int): Number of input channels.
|
306 |
+
norm_layer (nn.Module, optional): Normalization layer. Default: nn.LayerNorm
|
307 |
+
"""
|
308 |
+
|
309 |
+
def __init__(self, input_resolution, dim, norm_layer=nn.LayerNorm):
|
310 |
+
super().__init__()
|
311 |
+
self.input_resolution = input_resolution
|
312 |
+
self.dim = dim
|
313 |
+
self.reduction = nn.Linear(4 * dim, 2 * dim, bias=False)
|
314 |
+
self.norm = norm_layer(4 * dim)
|
315 |
+
|
316 |
+
def forward(self, x):
|
317 |
+
"""
|
318 |
+
x: B, H*W, C
|
319 |
+
"""
|
320 |
+
H, W = self.input_resolution
|
321 |
+
B, L, C = x.shape
|
322 |
+
assert L == H * W, "input feature has wrong size"
|
323 |
+
assert H % 2 == 0 and W % 2 == 0, f"x size ({H}*{W}) are not even."
|
324 |
+
|
325 |
+
x = x.view(B, H, W, C)
|
326 |
+
|
327 |
+
x0 = x[:, 0::2, 0::2, :] # B H/2 W/2 C
|
328 |
+
x1 = x[:, 1::2, 0::2, :] # B H/2 W/2 C
|
329 |
+
x2 = x[:, 0::2, 1::2, :] # B H/2 W/2 C
|
330 |
+
x3 = x[:, 1::2, 1::2, :] # B H/2 W/2 C
|
331 |
+
x = torch.cat([x0, x1, x2, x3], -1) # B H/2 W/2 4*C
|
332 |
+
x = x.view(B, -1, 4 * C) # B H/2*W/2 4*C
|
333 |
+
|
334 |
+
x = self.norm(x)
|
335 |
+
x = self.reduction(x)
|
336 |
+
|
337 |
+
return x
|
338 |
+
|
339 |
+
def extra_repr(self) -> str:
|
340 |
+
return f"input_resolution={self.input_resolution}, dim={self.dim}"
|
341 |
+
|
342 |
+
def flops(self):
|
343 |
+
H, W = self.input_resolution
|
344 |
+
flops = H * W * self.dim
|
345 |
+
flops += (H // 2) * (W // 2) * 4 * self.dim * 2 * self.dim
|
346 |
+
return flops
|
347 |
+
|
348 |
+
|
349 |
+
class BasicLayer(nn.Module):
|
350 |
+
""" A basic Swin Transformer layer for one stage.
|
351 |
+
|
352 |
+
Args:
|
353 |
+
dim (int): Number of input channels.
|
354 |
+
input_resolution (tuple[int]): Input resolution.
|
355 |
+
depth (int): Number of blocks.
|
356 |
+
num_heads (int): Number of attention heads.
|
357 |
+
window_size (int): Local window size.
|
358 |
+
mlp_ratio (float): Ratio of mlp hidden dim to embedding dim.
|
359 |
+
qkv_bias (bool, optional): If True, add a learnable bias to query, key, value. Default: True
|
360 |
+
qk_scale (float | None, optional): Override default qk scale of head_dim ** -0.5 if set.
|
361 |
+
drop (float, optional): Dropout rate. Default: 0.0
|
362 |
+
attn_drop (float, optional): Attention dropout rate. Default: 0.0
|
363 |
+
drop_path (float | tuple[float], optional): Stochastic depth rate. Default: 0.0
|
364 |
+
norm_layer (nn.Module, optional): Normalization layer. Default: nn.LayerNorm
|
365 |
+
downsample (nn.Module | None, optional): Downsample layer at the end of the layer. Default: None
|
366 |
+
use_checkpoint (bool): Whether to use checkpointing to save memory. Default: False.
|
367 |
+
"""
|
368 |
+
|
369 |
+
def __init__(self, dim, input_resolution, depth, num_heads, window_size,
|
370 |
+
mlp_ratio=4., qkv_bias=True, qk_scale=None, drop=0., attn_drop=0.,
|
371 |
+
drop_path=0., norm_layer=nn.LayerNorm, downsample=None, use_checkpoint=False):
|
372 |
+
|
373 |
+
super().__init__()
|
374 |
+
self.dim = dim
|
375 |
+
self.input_resolution = input_resolution
|
376 |
+
self.depth = depth
|
377 |
+
self.use_checkpoint = use_checkpoint
|
378 |
+
|
379 |
+
# build blocks
|
380 |
+
self.blocks = nn.ModuleList([
|
381 |
+
SwinTransformerBlock(dim=dim, input_resolution=input_resolution,
|
382 |
+
num_heads=num_heads, window_size=window_size,
|
383 |
+
shift_size=0 if (i % 2 == 0) else window_size // 2,
|
384 |
+
mlp_ratio=mlp_ratio,
|
385 |
+
qkv_bias=qkv_bias, qk_scale=qk_scale,
|
386 |
+
drop=drop, attn_drop=attn_drop,
|
387 |
+
drop_path=drop_path[i] if isinstance(drop_path, list) else drop_path,
|
388 |
+
norm_layer=norm_layer)
|
389 |
+
for i in range(depth)])
|
390 |
+
|
391 |
+
# patch merging layer
|
392 |
+
if downsample is not None:
|
393 |
+
self.downsample = downsample(input_resolution, dim=dim, norm_layer=norm_layer)
|
394 |
+
else:
|
395 |
+
self.downsample = None
|
396 |
+
|
397 |
+
def forward(self, x, x_size):
|
398 |
+
for blk in self.blocks:
|
399 |
+
if self.use_checkpoint:
|
400 |
+
x = checkpoint.checkpoint(blk, x, x_size)
|
401 |
+
else:
|
402 |
+
x = blk(x, x_size)
|
403 |
+
if self.downsample is not None:
|
404 |
+
x = self.downsample(x)
|
405 |
+
return x
|
406 |
+
|
407 |
+
def extra_repr(self) -> str:
|
408 |
+
return f"dim={self.dim}, input_resolution={self.input_resolution}, depth={self.depth}"
|
409 |
+
|
410 |
+
def flops(self):
|
411 |
+
flops = 0
|
412 |
+
for blk in self.blocks:
|
413 |
+
flops += blk.flops()
|
414 |
+
if self.downsample is not None:
|
415 |
+
flops += self.downsample.flops()
|
416 |
+
return flops
|
417 |
+
|
418 |
+
|
419 |
+
class RSTB(nn.Module):
|
420 |
+
"""Residual Swin Transformer Block (RSTB).
|
421 |
+
|
422 |
+
Args:
|
423 |
+
dim (int): Number of input channels.
|
424 |
+
input_resolution (tuple[int]): Input resolution.
|
425 |
+
depth (int): Number of blocks.
|
426 |
+
num_heads (int): Number of attention heads.
|
427 |
+
window_size (int): Local window size.
|
428 |
+
mlp_ratio (float): Ratio of mlp hidden dim to embedding dim.
|
429 |
+
qkv_bias (bool, optional): If True, add a learnable bias to query, key, value. Default: True
|
430 |
+
qk_scale (float | None, optional): Override default qk scale of head_dim ** -0.5 if set.
|
431 |
+
drop (float, optional): Dropout rate. Default: 0.0
|
432 |
+
attn_drop (float, optional): Attention dropout rate. Default: 0.0
|
433 |
+
drop_path (float | tuple[float], optional): Stochastic depth rate. Default: 0.0
|
434 |
+
norm_layer (nn.Module, optional): Normalization layer. Default: nn.LayerNorm
|
435 |
+
downsample (nn.Module | None, optional): Downsample layer at the end of the layer. Default: None
|
436 |
+
use_checkpoint (bool): Whether to use checkpointing to save memory. Default: False.
|
437 |
+
img_size: Input image size.
|
438 |
+
patch_size: Patch size.
|
439 |
+
resi_connection: The convolutional block before residual connection.
|
440 |
+
"""
|
441 |
+
|
442 |
+
def __init__(self, dim, input_resolution, depth, num_heads, window_size,
|
443 |
+
mlp_ratio=4., qkv_bias=True, qk_scale=None, drop=0., attn_drop=0.,
|
444 |
+
drop_path=0., norm_layer=nn.LayerNorm, downsample=None, use_checkpoint=False,
|
445 |
+
img_size=224, patch_size=4, resi_connection='1conv'):
|
446 |
+
super(RSTB, self).__init__()
|
447 |
+
|
448 |
+
self.dim = dim
|
449 |
+
self.input_resolution = input_resolution
|
450 |
+
|
451 |
+
self.residual_group = BasicLayer(dim=dim,
|
452 |
+
input_resolution=input_resolution,
|
453 |
+
depth=depth,
|
454 |
+
num_heads=num_heads,
|
455 |
+
window_size=window_size,
|
456 |
+
mlp_ratio=mlp_ratio,
|
457 |
+
qkv_bias=qkv_bias, qk_scale=qk_scale,
|
458 |
+
drop=drop, attn_drop=attn_drop,
|
459 |
+
drop_path=drop_path,
|
460 |
+
norm_layer=norm_layer,
|
461 |
+
downsample=downsample,
|
462 |
+
use_checkpoint=use_checkpoint)
|
463 |
+
|
464 |
+
if resi_connection == '1conv':
|
465 |
+
self.conv = nn.Conv2d(dim, dim, 3, 1, 1)
|
466 |
+
elif resi_connection == '3conv':
|
467 |
+
# to save parameters and memory
|
468 |
+
self.conv = nn.Sequential(nn.Conv2d(dim, dim // 4, 3, 1, 1), nn.LeakyReLU(negative_slope=0.2, inplace=True),
|
469 |
+
nn.Conv2d(dim // 4, dim // 4, 1, 1, 0),
|
470 |
+
nn.LeakyReLU(negative_slope=0.2, inplace=True),
|
471 |
+
nn.Conv2d(dim // 4, dim, 3, 1, 1))
|
472 |
+
|
473 |
+
self.patch_embed = PatchEmbed(
|
474 |
+
img_size=img_size, patch_size=patch_size, in_chans=0, embed_dim=dim,
|
475 |
+
norm_layer=None)
|
476 |
+
|
477 |
+
self.patch_unembed = PatchUnEmbed(
|
478 |
+
img_size=img_size, patch_size=patch_size, in_chans=0, embed_dim=dim,
|
479 |
+
norm_layer=None)
|
480 |
+
|
481 |
+
def forward(self, x, x_size):
|
482 |
+
return self.patch_embed(self.conv(self.patch_unembed(self.residual_group(x, x_size), x_size))) + x
|
483 |
+
|
484 |
+
def flops(self):
|
485 |
+
flops = 0
|
486 |
+
flops += self.residual_group.flops()
|
487 |
+
H, W = self.input_resolution
|
488 |
+
flops += H * W * self.dim * self.dim * 9
|
489 |
+
flops += self.patch_embed.flops()
|
490 |
+
flops += self.patch_unembed.flops()
|
491 |
+
|
492 |
+
return flops
|
493 |
+
|
494 |
+
|
495 |
+
class PatchEmbed(nn.Module):
|
496 |
+
r""" Image to Patch Embedding
|
497 |
+
|
498 |
+
Args:
|
499 |
+
img_size (int): Image size. Default: 224.
|
500 |
+
patch_size (int): Patch token size. Default: 4.
|
501 |
+
in_chans (int): Number of input image channels. Default: 3.
|
502 |
+
embed_dim (int): Number of linear projection output channels. Default: 96.
|
503 |
+
norm_layer (nn.Module, optional): Normalization layer. Default: None
|
504 |
+
"""
|
505 |
+
|
506 |
+
def __init__(self, img_size=224, patch_size=4, in_chans=3, embed_dim=96, norm_layer=None):
|
507 |
+
super().__init__()
|
508 |
+
img_size = to_2tuple(img_size)
|
509 |
+
patch_size = to_2tuple(patch_size)
|
510 |
+
patches_resolution = [img_size[0] // patch_size[0], img_size[1] // patch_size[1]]
|
511 |
+
self.img_size = img_size
|
512 |
+
self.patch_size = patch_size
|
513 |
+
self.patches_resolution = patches_resolution
|
514 |
+
self.num_patches = patches_resolution[0] * patches_resolution[1]
|
515 |
+
|
516 |
+
self.in_chans = in_chans
|
517 |
+
self.embed_dim = embed_dim
|
518 |
+
|
519 |
+
if norm_layer is not None:
|
520 |
+
self.norm = norm_layer(embed_dim)
|
521 |
+
else:
|
522 |
+
self.norm = None
|
523 |
+
|
524 |
+
def forward(self, x):
|
525 |
+
x = x.flatten(2).transpose(1, 2) # B Ph*Pw C
|
526 |
+
if self.norm is not None:
|
527 |
+
x = self.norm(x)
|
528 |
+
return x
|
529 |
+
|
530 |
+
def flops(self):
|
531 |
+
flops = 0
|
532 |
+
H, W = self.img_size
|
533 |
+
if self.norm is not None:
|
534 |
+
flops += H * W * self.embed_dim
|
535 |
+
return flops
|
536 |
+
|
537 |
+
|
538 |
+
class PatchUnEmbed(nn.Module):
|
539 |
+
r""" Image to Patch Unembedding
|
540 |
+
|
541 |
+
Args:
|
542 |
+
img_size (int): Image size. Default: 224.
|
543 |
+
patch_size (int): Patch token size. Default: 4.
|
544 |
+
in_chans (int): Number of input image channels. Default: 3.
|
545 |
+
embed_dim (int): Number of linear projection output channels. Default: 96.
|
546 |
+
norm_layer (nn.Module, optional): Normalization layer. Default: None
|
547 |
+
"""
|
548 |
+
|
549 |
+
def __init__(self, img_size=224, patch_size=4, in_chans=3, embed_dim=96, norm_layer=None):
|
550 |
+
super().__init__()
|
551 |
+
img_size = to_2tuple(img_size)
|
552 |
+
patch_size = to_2tuple(patch_size)
|
553 |
+
patches_resolution = [img_size[0] // patch_size[0], img_size[1] // patch_size[1]]
|
554 |
+
self.img_size = img_size
|
555 |
+
self.patch_size = patch_size
|
556 |
+
self.patches_resolution = patches_resolution
|
557 |
+
self.num_patches = patches_resolution[0] * patches_resolution[1]
|
558 |
+
|
559 |
+
self.in_chans = in_chans
|
560 |
+
self.embed_dim = embed_dim
|
561 |
+
|
562 |
+
def forward(self, x, x_size):
|
563 |
+
B, HW, C = x.shape
|
564 |
+
x = x.transpose(1, 2).view(B, self.embed_dim, x_size[0], x_size[1]) # B Ph*Pw C
|
565 |
+
return x
|
566 |
+
|
567 |
+
def flops(self):
|
568 |
+
flops = 0
|
569 |
+
return flops
|
570 |
+
|
571 |
+
|
572 |
+
class Upsample(nn.Sequential):
|
573 |
+
"""Upsample module.
|
574 |
+
|
575 |
+
Args:
|
576 |
+
scale (int): Scale factor. Supported scales: 2^n and 3.
|
577 |
+
num_feat (int): Channel number of intermediate features.
|
578 |
+
"""
|
579 |
+
|
580 |
+
def __init__(self, scale, num_feat):
|
581 |
+
m = []
|
582 |
+
if (scale & (scale - 1)) == 0: # scale = 2^n
|
583 |
+
for _ in range(int(math.log(scale, 2))):
|
584 |
+
m.append(nn.Conv2d(num_feat, 4 * num_feat, 3, 1, 1))
|
585 |
+
m.append(nn.PixelShuffle(2))
|
586 |
+
elif scale == 3:
|
587 |
+
m.append(nn.Conv2d(num_feat, 9 * num_feat, 3, 1, 1))
|
588 |
+
m.append(nn.PixelShuffle(3))
|
589 |
+
else:
|
590 |
+
raise ValueError(f'scale {scale} is not supported. ' 'Supported scales: 2^n and 3.')
|
591 |
+
super(Upsample, self).__init__(*m)
|
592 |
+
|
593 |
+
|
594 |
+
class UpsampleOneStep(nn.Sequential):
|
595 |
+
"""UpsampleOneStep module (the difference with Upsample is that it always only has 1conv + 1pixelshuffle)
|
596 |
+
Used in lightweight SR to save parameters.
|
597 |
+
|
598 |
+
Args:
|
599 |
+
scale (int): Scale factor. Supported scales: 2^n and 3.
|
600 |
+
num_feat (int): Channel number of intermediate features.
|
601 |
+
|
602 |
+
"""
|
603 |
+
|
604 |
+
def __init__(self, scale, num_feat, num_out_ch, input_resolution=None):
|
605 |
+
self.num_feat = num_feat
|
606 |
+
self.input_resolution = input_resolution
|
607 |
+
m = []
|
608 |
+
m.append(nn.Conv2d(num_feat, (scale ** 2) * num_out_ch, 3, 1, 1))
|
609 |
+
m.append(nn.PixelShuffle(scale))
|
610 |
+
super(UpsampleOneStep, self).__init__(*m)
|
611 |
+
|
612 |
+
def flops(self):
|
613 |
+
H, W = self.input_resolution
|
614 |
+
flops = H * W * self.num_feat * 3 * 9
|
615 |
+
return flops
|
616 |
+
|
617 |
+
|
618 |
+
class SwinIR(nn.Module):
|
619 |
+
r""" SwinIR
|
620 |
+
A PyTorch impl of : `SwinIR: Image Restoration Using Swin Transformer`, based on Swin Transformer.
|
621 |
+
|
622 |
+
Args:
|
623 |
+
img_size (int | tuple(int)): Input image size. Default 64
|
624 |
+
patch_size (int | tuple(int)): Patch size. Default: 1
|
625 |
+
in_chans (int): Number of input image channels. Default: 3
|
626 |
+
embed_dim (int): Patch embedding dimension. Default: 96
|
627 |
+
depths (tuple(int)): Depth of each Swin Transformer layer.
|
628 |
+
num_heads (tuple(int)): Number of attention heads in different layers.
|
629 |
+
window_size (int): Window size. Default: 7
|
630 |
+
mlp_ratio (float): Ratio of mlp hidden dim to embedding dim. Default: 4
|
631 |
+
qkv_bias (bool): If True, add a learnable bias to query, key, value. Default: True
|
632 |
+
qk_scale (float): Override default qk scale of head_dim ** -0.5 if set. Default: None
|
633 |
+
drop_rate (float): Dropout rate. Default: 0
|
634 |
+
attn_drop_rate (float): Attention dropout rate. Default: 0
|
635 |
+
drop_path_rate (float): Stochastic depth rate. Default: 0.1
|
636 |
+
norm_layer (nn.Module): Normalization layer. Default: nn.LayerNorm.
|
637 |
+
ape (bool): If True, add absolute position embedding to the patch embedding. Default: False
|
638 |
+
patch_norm (bool): If True, add normalization after patch embedding. Default: True
|
639 |
+
use_checkpoint (bool): Whether to use checkpointing to save memory. Default: False
|
640 |
+
upscale: Upscale factor. 2/3/4/8 for image SR, 1 for denoising and compress artifact reduction
|
641 |
+
img_range: Image range. 1. or 255.
|
642 |
+
upsampler: The reconstruction reconstruction module. 'pixelshuffle'/'pixelshuffledirect'/'nearest+conv'/None
|
643 |
+
resi_connection: The convolutional block before residual connection. '1conv'/'3conv'
|
644 |
+
"""
|
645 |
+
|
646 |
+
def __init__(self, img_size=64, patch_size=1, in_chans=3,
|
647 |
+
embed_dim=96, depths=[6, 6, 6, 6], num_heads=[6, 6, 6, 6],
|
648 |
+
window_size=7, mlp_ratio=4., qkv_bias=True, qk_scale=None,
|
649 |
+
drop_rate=0., attn_drop_rate=0., drop_path_rate=0.1,
|
650 |
+
norm_layer=nn.LayerNorm, ape=False, patch_norm=True,
|
651 |
+
use_checkpoint=False, upscale=2, img_range=1., upsampler='', resi_connection='1conv',
|
652 |
+
**kwargs):
|
653 |
+
super(SwinIR, self).__init__()
|
654 |
+
num_in_ch = in_chans
|
655 |
+
num_out_ch = in_chans
|
656 |
+
num_feat = 64
|
657 |
+
self.img_range = img_range
|
658 |
+
if in_chans == 3:
|
659 |
+
rgb_mean = (0.4488, 0.4371, 0.4040)
|
660 |
+
self.mean = torch.Tensor(rgb_mean).view(1, 3, 1, 1)
|
661 |
+
else:
|
662 |
+
self.mean = torch.zeros(1, 1, 1, 1)
|
663 |
+
self.upscale = upscale
|
664 |
+
self.upsampler = upsampler
|
665 |
+
self.window_size = window_size
|
666 |
+
|
667 |
+
#####################################################################################################
|
668 |
+
################################### 1, shallow feature extraction ###################################
|
669 |
+
self.conv_first = nn.Conv2d(num_in_ch, embed_dim, 3, 1, 1)
|
670 |
+
|
671 |
+
#####################################################################################################
|
672 |
+
################################### 2, deep feature extraction ######################################
|
673 |
+
self.num_layers = len(depths)
|
674 |
+
self.embed_dim = embed_dim
|
675 |
+
self.ape = ape
|
676 |
+
self.patch_norm = patch_norm
|
677 |
+
self.num_features = embed_dim
|
678 |
+
self.mlp_ratio = mlp_ratio
|
679 |
+
|
680 |
+
# split image into non-overlapping patches
|
681 |
+
self.patch_embed = PatchEmbed(
|
682 |
+
img_size=img_size, patch_size=patch_size, in_chans=embed_dim, embed_dim=embed_dim,
|
683 |
+
norm_layer=norm_layer if self.patch_norm else None)
|
684 |
+
num_patches = self.patch_embed.num_patches
|
685 |
+
patches_resolution = self.patch_embed.patches_resolution
|
686 |
+
self.patches_resolution = patches_resolution
|
687 |
+
|
688 |
+
# merge non-overlapping patches into image
|
689 |
+
self.patch_unembed = PatchUnEmbed(
|
690 |
+
img_size=img_size, patch_size=patch_size, in_chans=embed_dim, embed_dim=embed_dim,
|
691 |
+
norm_layer=norm_layer if self.patch_norm else None)
|
692 |
+
|
693 |
+
# absolute position embedding
|
694 |
+
if self.ape:
|
695 |
+
self.absolute_pos_embed = nn.Parameter(torch.zeros(1, num_patches, embed_dim))
|
696 |
+
trunc_normal_(self.absolute_pos_embed, std=.02)
|
697 |
+
|
698 |
+
self.pos_drop = nn.Dropout(p=drop_rate)
|
699 |
+
|
700 |
+
# stochastic depth
|
701 |
+
dpr = [x.item() for x in torch.linspace(0, drop_path_rate, sum(depths))] # stochastic depth decay rule
|
702 |
+
|
703 |
+
# build Residual Swin Transformer blocks (RSTB)
|
704 |
+
self.layers = nn.ModuleList()
|
705 |
+
for i_layer in range(self.num_layers):
|
706 |
+
layer = RSTB(dim=embed_dim,
|
707 |
+
input_resolution=(patches_resolution[0],
|
708 |
+
patches_resolution[1]),
|
709 |
+
depth=depths[i_layer],
|
710 |
+
num_heads=num_heads[i_layer],
|
711 |
+
window_size=window_size,
|
712 |
+
mlp_ratio=self.mlp_ratio,
|
713 |
+
qkv_bias=qkv_bias, qk_scale=qk_scale,
|
714 |
+
drop=drop_rate, attn_drop=attn_drop_rate,
|
715 |
+
drop_path=dpr[sum(depths[:i_layer]):sum(depths[:i_layer + 1])], # no impact on SR results
|
716 |
+
norm_layer=norm_layer,
|
717 |
+
downsample=None,
|
718 |
+
use_checkpoint=use_checkpoint,
|
719 |
+
img_size=img_size,
|
720 |
+
patch_size=patch_size,
|
721 |
+
resi_connection=resi_connection
|
722 |
+
|
723 |
+
)
|
724 |
+
self.layers.append(layer)
|
725 |
+
self.norm = norm_layer(self.num_features)
|
726 |
+
|
727 |
+
# build the last conv layer in deep feature extraction
|
728 |
+
if resi_connection == '1conv':
|
729 |
+
self.conv_after_body = nn.Conv2d(embed_dim, embed_dim, 3, 1, 1)
|
730 |
+
elif resi_connection == '3conv':
|
731 |
+
# to save parameters and memory
|
732 |
+
self.conv_after_body = nn.Sequential(nn.Conv2d(embed_dim, embed_dim // 4, 3, 1, 1),
|
733 |
+
nn.LeakyReLU(negative_slope=0.2, inplace=True),
|
734 |
+
nn.Conv2d(embed_dim // 4, embed_dim // 4, 1, 1, 0),
|
735 |
+
nn.LeakyReLU(negative_slope=0.2, inplace=True),
|
736 |
+
nn.Conv2d(embed_dim // 4, embed_dim, 3, 1, 1))
|
737 |
+
|
738 |
+
#####################################################################################################
|
739 |
+
################################ 3, high quality image reconstruction ################################
|
740 |
+
if self.upsampler == 'pixelshuffle':
|
741 |
+
# for classical SR
|
742 |
+
self.conv_before_upsample = nn.Sequential(nn.Conv2d(embed_dim, num_feat, 3, 1, 1),
|
743 |
+
nn.LeakyReLU(inplace=True))
|
744 |
+
self.upsample = Upsample(upscale, num_feat)
|
745 |
+
self.conv_last = nn.Conv2d(num_feat, num_out_ch, 3, 1, 1)
|
746 |
+
elif self.upsampler == 'pixelshuffledirect':
|
747 |
+
# for lightweight SR (to save parameters)
|
748 |
+
self.upsample = UpsampleOneStep(upscale, embed_dim, num_out_ch,
|
749 |
+
(patches_resolution[0], patches_resolution[1]))
|
750 |
+
elif self.upsampler == 'nearest+conv':
|
751 |
+
# for real-world SR (less artifacts)
|
752 |
+
assert self.upscale == 4, 'only support x4 now.'
|
753 |
+
self.conv_before_upsample = nn.Sequential(nn.Conv2d(embed_dim, num_feat, 3, 1, 1),
|
754 |
+
nn.LeakyReLU(inplace=True))
|
755 |
+
self.conv_up1 = nn.Conv2d(num_feat, num_feat, 3, 1, 1)
|
756 |
+
self.conv_up2 = nn.Conv2d(num_feat, num_feat, 3, 1, 1)
|
757 |
+
self.conv_hr = nn.Conv2d(num_feat, num_feat, 3, 1, 1)
|
758 |
+
self.conv_last = nn.Conv2d(num_feat, num_out_ch, 3, 1, 1)
|
759 |
+
self.lrelu = nn.LeakyReLU(negative_slope=0.2, inplace=True)
|
760 |
+
else:
|
761 |
+
# for image denoising and JPEG compression artifact reduction
|
762 |
+
self.conv_last = nn.Conv2d(embed_dim, num_out_ch, 3, 1, 1)
|
763 |
+
|
764 |
+
self.apply(self._init_weights)
|
765 |
+
|
766 |
+
def _init_weights(self, m):
|
767 |
+
if isinstance(m, nn.Linear):
|
768 |
+
trunc_normal_(m.weight, std=.02)
|
769 |
+
if isinstance(m, nn.Linear) and m.bias is not None:
|
770 |
+
nn.init.constant_(m.bias, 0)
|
771 |
+
elif isinstance(m, nn.LayerNorm):
|
772 |
+
nn.init.constant_(m.bias, 0)
|
773 |
+
nn.init.constant_(m.weight, 1.0)
|
774 |
+
|
775 |
+
@torch.jit.ignore
|
776 |
+
def no_weight_decay(self):
|
777 |
+
return {'absolute_pos_embed'}
|
778 |
+
|
779 |
+
@torch.jit.ignore
|
780 |
+
def no_weight_decay_keywords(self):
|
781 |
+
return {'relative_position_bias_table'}
|
782 |
+
|
783 |
+
def check_image_size(self, x):
|
784 |
+
_, _, h, w = x.size()
|
785 |
+
mod_pad_h = (self.window_size - h % self.window_size) % self.window_size
|
786 |
+
mod_pad_w = (self.window_size - w % self.window_size) % self.window_size
|
787 |
+
x = F.pad(x, (0, mod_pad_w, 0, mod_pad_h), 'reflect')
|
788 |
+
return x
|
789 |
+
|
790 |
+
def forward_features(self, x):
|
791 |
+
x_size = (x.shape[2], x.shape[3])
|
792 |
+
x = self.patch_embed(x)
|
793 |
+
if self.ape:
|
794 |
+
x = x + self.absolute_pos_embed
|
795 |
+
x = self.pos_drop(x)
|
796 |
+
|
797 |
+
for layer in self.layers:
|
798 |
+
x = layer(x, x_size)
|
799 |
+
|
800 |
+
x = self.norm(x) # B L C
|
801 |
+
x = self.patch_unembed(x, x_size)
|
802 |
+
|
803 |
+
return x
|
804 |
+
|
805 |
+
def forward(self, x):
|
806 |
+
H, W = x.shape[2:]
|
807 |
+
x = self.check_image_size(x)
|
808 |
+
|
809 |
+
self.mean = self.mean.type_as(x)
|
810 |
+
x = (x - self.mean) * self.img_range
|
811 |
+
|
812 |
+
if self.upsampler == 'pixelshuffle':
|
813 |
+
# for classical SR
|
814 |
+
x = self.conv_first(x)
|
815 |
+
x = self.conv_after_body(self.forward_features(x)) + x
|
816 |
+
x = self.conv_before_upsample(x)
|
817 |
+
x = self.conv_last(self.upsample(x))
|
818 |
+
elif self.upsampler == 'pixelshuffledirect':
|
819 |
+
# for lightweight SR
|
820 |
+
x = self.conv_first(x)
|
821 |
+
x = self.conv_after_body(self.forward_features(x)) + x
|
822 |
+
x = self.upsample(x)
|
823 |
+
elif self.upsampler == 'nearest+conv':
|
824 |
+
# for real-world SR
|
825 |
+
x = self.conv_first(x)
|
826 |
+
x = self.conv_after_body(self.forward_features(x)) + x
|
827 |
+
x = self.conv_before_upsample(x)
|
828 |
+
x = self.lrelu(self.conv_up1(torch.nn.functional.interpolate(x, scale_factor=2, mode='nearest')))
|
829 |
+
x = self.lrelu(self.conv_up2(torch.nn.functional.interpolate(x, scale_factor=2, mode='nearest')))
|
830 |
+
x = self.conv_last(self.lrelu(self.conv_hr(x)))
|
831 |
+
else:
|
832 |
+
# for image denoising and JPEG compression artifact reduction
|
833 |
+
x_first = self.conv_first(x)
|
834 |
+
res = self.conv_after_body(self.forward_features(x_first)) + x_first
|
835 |
+
x = x + self.conv_last(res)
|
836 |
+
|
837 |
+
x = x / self.img_range + self.mean
|
838 |
+
|
839 |
+
return x[:, :, :H*self.upscale, :W*self.upscale]
|
840 |
+
|
841 |
+
def flops(self):
|
842 |
+
flops = 0
|
843 |
+
H, W = self.patches_resolution
|
844 |
+
flops += H * W * 3 * self.embed_dim * 9
|
845 |
+
flops += self.patch_embed.flops()
|
846 |
+
for i, layer in enumerate(self.layers):
|
847 |
+
flops += layer.flops()
|
848 |
+
flops += H * W * 3 * self.embed_dim * self.embed_dim
|
849 |
+
flops += self.upsample.flops()
|
850 |
+
return flops
|
851 |
+
|
852 |
+
|
853 |
+
if __name__ == '__main__':
|
854 |
+
upscale = 4
|
855 |
+
window_size = 8
|
856 |
+
height = (1024 // upscale // window_size + 1) * window_size
|
857 |
+
width = (720 // upscale // window_size + 1) * window_size
|
858 |
+
model = SwinIR(upscale=2, img_size=(height, width),
|
859 |
+
window_size=window_size, img_range=1., depths=[6, 6, 6, 6],
|
860 |
+
embed_dim=60, num_heads=[6, 6, 6, 6], mlp_ratio=2, upsampler='pixelshuffledirect')
|
861 |
+
print(model)
|
862 |
+
print(height, width, model.flops() / 1e9)
|
863 |
+
|
864 |
+
x = torch.randn((1, 3, height, width))
|
865 |
+
x = model(x)
|
866 |
+
print(x.shape)
|
predict.py
ADDED
@@ -0,0 +1,159 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
import cog
|
2 |
+
import tempfile
|
3 |
+
from pathlib import Path
|
4 |
+
import argparse
|
5 |
+
import shutil
|
6 |
+
import os
|
7 |
+
import cv2
|
8 |
+
import glob
|
9 |
+
import torch
|
10 |
+
from collections import OrderedDict
|
11 |
+
import numpy as np
|
12 |
+
from main_test_swinir import define_model, setup, get_image_pair
|
13 |
+
|
14 |
+
|
15 |
+
class Predictor(cog.Predictor):
|
16 |
+
def setup(self):
|
17 |
+
model_dir = 'experiments/pretrained_models'
|
18 |
+
|
19 |
+
self.model_zoo = {
|
20 |
+
'real_sr': {
|
21 |
+
4: os.path.join(model_dir, '003_realSR_BSRGAN_DFO_s64w8_SwinIR-M_x4_GAN.pth')
|
22 |
+
},
|
23 |
+
'gray_dn': {
|
24 |
+
15: os.path.join(model_dir, '004_grayDN_DFWB_s128w8_SwinIR-M_noise15.pth'),
|
25 |
+
25: os.path.join(model_dir, '004_grayDN_DFWB_s128w8_SwinIR-M_noise25.pth'),
|
26 |
+
50: os.path.join(model_dir, '004_grayDN_DFWB_s128w8_SwinIR-M_noise50.pth')
|
27 |
+
},
|
28 |
+
'color_dn': {
|
29 |
+
15: os.path.join(model_dir, '005_colorDN_DFWB_s128w8_SwinIR-M_noise15.pth'),
|
30 |
+
25: os.path.join(model_dir, '005_colorDN_DFWB_s128w8_SwinIR-M_noise25.pth'),
|
31 |
+
50: os.path.join(model_dir, '005_colorDN_DFWB_s128w8_SwinIR-M_noise50.pth')
|
32 |
+
},
|
33 |
+
'jpeg_car': {
|
34 |
+
10: os.path.join(model_dir, '006_CAR_DFWB_s126w7_SwinIR-M_jpeg10.pth'),
|
35 |
+
20: os.path.join(model_dir, '006_CAR_DFWB_s126w7_SwinIR-M_jpeg20.pth'),
|
36 |
+
30: os.path.join(model_dir, '006_CAR_DFWB_s126w7_SwinIR-M_jpeg30.pth'),
|
37 |
+
40: os.path.join(model_dir, '006_CAR_DFWB_s126w7_SwinIR-M_jpeg40.pth')
|
38 |
+
}
|
39 |
+
}
|
40 |
+
|
41 |
+
parser = argparse.ArgumentParser()
|
42 |
+
parser.add_argument('--task', type=str, default='real_sr', help='classical_sr, lightweight_sr, real_sr, '
|
43 |
+
'gray_dn, color_dn, jpeg_car')
|
44 |
+
parser.add_argument('--scale', type=int, default=1, help='scale factor: 1, 2, 3, 4, 8') # 1 for dn and jpeg car
|
45 |
+
parser.add_argument('--noise', type=int, default=15, help='noise level: 15, 25, 50')
|
46 |
+
parser.add_argument('--jpeg', type=int, default=40, help='scale factor: 10, 20, 30, 40')
|
47 |
+
parser.add_argument('--training_patch_size', type=int, default=128, help='patch size used in training SwinIR. '
|
48 |
+
'Just used to differentiate two different settings in Table 2 of the paper. '
|
49 |
+
'Images are NOT tested patch by patch.')
|
50 |
+
parser.add_argument('--large_model', action='store_true',
|
51 |
+
help='use large model, only provided for real image sr')
|
52 |
+
parser.add_argument('--model_path', type=str,
|
53 |
+
default=self.model_zoo['real_sr'][4])
|
54 |
+
parser.add_argument('--folder_lq', type=str, default=None, help='input low-quality test image folder')
|
55 |
+
parser.add_argument('--folder_gt', type=str, default=None, help='input ground-truth test image folder')
|
56 |
+
|
57 |
+
self.args = parser.parse_args('')
|
58 |
+
|
59 |
+
self.device = torch.device('cuda' if torch.cuda.is_available() else 'cpu')
|
60 |
+
|
61 |
+
self.tasks = {
|
62 |
+
'Real-World Image Super-Resolution': 'real_sr',
|
63 |
+
'Grayscale Image Denoising': 'gray_dn',
|
64 |
+
'Color Image Denoising': 'color_dn',
|
65 |
+
'JPEG Compression Artifact Reduction': 'jpeg_car'
|
66 |
+
}
|
67 |
+
|
68 |
+
@cog.input("image", type=Path, help="input image")
|
69 |
+
@cog.input("task_type", type=str, default='Real-World Image Super-Resolution',
|
70 |
+
options=['Real-World Image Super-Resolution', 'Grayscale Image Denoising', 'Color Image Denoising',
|
71 |
+
'JPEG Compression Artifact Reduction'],
|
72 |
+
help="image restoration task type")
|
73 |
+
@cog.input("noise", type=int, default=15, options=[15, 25, 50],
|
74 |
+
help='noise level, activated for Grayscale Image Denoising and Color Image Denoising. '
|
75 |
+
'Leave it as default or arbitrary if other tasks are selected')
|
76 |
+
@cog.input("jpeg", type=int, default=40, options=[10, 20, 30, 40],
|
77 |
+
help='scale factor, activated for JPEG Compression Artifact Reduction. '
|
78 |
+
'Leave it as default or arbitrary if other tasks are selected')
|
79 |
+
def predict(self, image, task_type='Real-World Image Super-Resolution', jpeg=40, noise=15):
|
80 |
+
|
81 |
+
self.args.task = self.tasks[task_type]
|
82 |
+
self.args.noise = noise
|
83 |
+
self.args.jpeg = jpeg
|
84 |
+
|
85 |
+
# set model path
|
86 |
+
if self.args.task == 'real_sr':
|
87 |
+
self.args.scale = 4
|
88 |
+
self.args.model_path = self.model_zoo[self.args.task][4]
|
89 |
+
elif self.args.task in ['gray_dn', 'color_dn']:
|
90 |
+
self.args.model_path = self.model_zoo[self.args.task][noise]
|
91 |
+
else:
|
92 |
+
self.args.model_path = self.model_zoo[self.args.task][jpeg]
|
93 |
+
|
94 |
+
try:
|
95 |
+
# set input folder
|
96 |
+
input_dir = 'input_cog_temp'
|
97 |
+
os.makedirs(input_dir, exist_ok=True)
|
98 |
+
input_path = os.path.join(input_dir, os.path.basename(image))
|
99 |
+
shutil.copy(str(image), input_path)
|
100 |
+
if self.args.task == 'real_sr':
|
101 |
+
self.args.folder_lq = input_dir
|
102 |
+
else:
|
103 |
+
self.args.folder_gt = input_dir
|
104 |
+
|
105 |
+
model = define_model(self.args)
|
106 |
+
model.eval()
|
107 |
+
model = model.to(self.device)
|
108 |
+
|
109 |
+
# setup folder and path
|
110 |
+
folder, save_dir, border, window_size = setup(self.args)
|
111 |
+
os.makedirs(save_dir, exist_ok=True)
|
112 |
+
test_results = OrderedDict()
|
113 |
+
test_results['psnr'] = []
|
114 |
+
test_results['ssim'] = []
|
115 |
+
test_results['psnr_y'] = []
|
116 |
+
test_results['ssim_y'] = []
|
117 |
+
test_results['psnr_b'] = []
|
118 |
+
# psnr, ssim, psnr_y, ssim_y, psnr_b = 0, 0, 0, 0, 0
|
119 |
+
out_path = Path(tempfile.mkdtemp()) / "out.png"
|
120 |
+
|
121 |
+
for idx, path in enumerate(sorted(glob.glob(os.path.join(folder, '*')))):
|
122 |
+
# read image
|
123 |
+
imgname, img_lq, img_gt = get_image_pair(self.args, path) # image to HWC-BGR, float32
|
124 |
+
img_lq = np.transpose(img_lq if img_lq.shape[2] == 1 else img_lq[:, :, [2, 1, 0]],
|
125 |
+
(2, 0, 1)) # HCW-BGR to CHW-RGB
|
126 |
+
img_lq = torch.from_numpy(img_lq).float().unsqueeze(0).to(self.device) # CHW-RGB to NCHW-RGB
|
127 |
+
|
128 |
+
# inference
|
129 |
+
with torch.no_grad():
|
130 |
+
# pad input image to be a multiple of window_size
|
131 |
+
_, _, h_old, w_old = img_lq.size()
|
132 |
+
h_pad = (h_old // window_size + 1) * window_size - h_old
|
133 |
+
w_pad = (w_old // window_size + 1) * window_size - w_old
|
134 |
+
img_lq = torch.cat([img_lq, torch.flip(img_lq, [2])], 2)[:, :, :h_old + h_pad, :]
|
135 |
+
img_lq = torch.cat([img_lq, torch.flip(img_lq, [3])], 3)[:, :, :, :w_old + w_pad]
|
136 |
+
output = model(img_lq)
|
137 |
+
output = output[..., :h_old * self.args.scale, :w_old * self.args.scale]
|
138 |
+
|
139 |
+
# save image
|
140 |
+
output = output.data.squeeze().float().cpu().clamp_(0, 1).numpy()
|
141 |
+
if output.ndim == 3:
|
142 |
+
output = np.transpose(output[[2, 1, 0], :, :], (1, 2, 0)) # CHW-RGB to HCW-BGR
|
143 |
+
output = (output * 255.0).round().astype(np.uint8) # float32 to uint8
|
144 |
+
cv2.imwrite(str(out_path), output)
|
145 |
+
finally:
|
146 |
+
clean_folder(input_dir)
|
147 |
+
return out_path
|
148 |
+
|
149 |
+
|
150 |
+
def clean_folder(folder):
|
151 |
+
for filename in os.listdir(folder):
|
152 |
+
file_path = os.path.join(folder, filename)
|
153 |
+
try:
|
154 |
+
if os.path.isfile(file_path) or os.path.islink(file_path):
|
155 |
+
os.unlink(file_path)
|
156 |
+
elif os.path.isdir(file_path):
|
157 |
+
shutil.rmtree(file_path)
|
158 |
+
except Exception as e:
|
159 |
+
print('Failed to delete %s. Reason: %s' % (file_path, e))
|
testsets/data/Lincoln.png
ADDED
testsets/data/butterfly.png
ADDED
testsets/data/tiger.png
ADDED
utils/__pycache__/util_calculate_psnr_ssim.cpython-37.pyc
ADDED
Binary file (11.3 kB). View file
|
|
utils/util_calculate_psnr_ssim.py
ADDED
@@ -0,0 +1,346 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
import cv2
|
2 |
+
import numpy as np
|
3 |
+
import torch
|
4 |
+
|
5 |
+
|
6 |
+
def calculate_psnr(img1, img2, crop_border, input_order='HWC', test_y_channel=False):
|
7 |
+
"""Calculate PSNR (Peak Signal-to-Noise Ratio).
|
8 |
+
|
9 |
+
Ref: https://en.wikipedia.org/wiki/Peak_signal-to-noise_ratio
|
10 |
+
|
11 |
+
Args:
|
12 |
+
img1 (ndarray): Images with range [0, 255].
|
13 |
+
img2 (ndarray): Images with range [0, 255].
|
14 |
+
crop_border (int): Cropped pixels in each edge of an image. These
|
15 |
+
pixels are not involved in the PSNR calculation.
|
16 |
+
input_order (str): Whether the input order is 'HWC' or 'CHW'.
|
17 |
+
Default: 'HWC'.
|
18 |
+
test_y_channel (bool): Test on Y channel of YCbCr. Default: False.
|
19 |
+
|
20 |
+
Returns:
|
21 |
+
float: psnr result.
|
22 |
+
"""
|
23 |
+
|
24 |
+
assert img1.shape == img2.shape, (f'Image shapes are differnet: {img1.shape}, {img2.shape}.')
|
25 |
+
if input_order not in ['HWC', 'CHW']:
|
26 |
+
raise ValueError(f'Wrong input_order {input_order}. Supported input_orders are ' '"HWC" and "CHW"')
|
27 |
+
img1 = reorder_image(img1, input_order=input_order)
|
28 |
+
img2 = reorder_image(img2, input_order=input_order)
|
29 |
+
img1 = img1.astype(np.float64)
|
30 |
+
img2 = img2.astype(np.float64)
|
31 |
+
|
32 |
+
if crop_border != 0:
|
33 |
+
img1 = img1[crop_border:-crop_border, crop_border:-crop_border, ...]
|
34 |
+
img2 = img2[crop_border:-crop_border, crop_border:-crop_border, ...]
|
35 |
+
|
36 |
+
if test_y_channel:
|
37 |
+
img1 = to_y_channel(img1)
|
38 |
+
img2 = to_y_channel(img2)
|
39 |
+
|
40 |
+
mse = np.mean((img1 - img2) ** 2)
|
41 |
+
if mse == 0:
|
42 |
+
return float('inf')
|
43 |
+
return 20. * np.log10(255. / np.sqrt(mse))
|
44 |
+
|
45 |
+
|
46 |
+
def _ssim(img1, img2):
|
47 |
+
"""Calculate SSIM (structural similarity) for one channel images.
|
48 |
+
|
49 |
+
It is called by func:`calculate_ssim`.
|
50 |
+
|
51 |
+
Args:
|
52 |
+
img1 (ndarray): Images with range [0, 255] with order 'HWC'.
|
53 |
+
img2 (ndarray): Images with range [0, 255] with order 'HWC'.
|
54 |
+
|
55 |
+
Returns:
|
56 |
+
float: ssim result.
|
57 |
+
"""
|
58 |
+
|
59 |
+
C1 = (0.01 * 255) ** 2
|
60 |
+
C2 = (0.03 * 255) ** 2
|
61 |
+
|
62 |
+
img1 = img1.astype(np.float64)
|
63 |
+
img2 = img2.astype(np.float64)
|
64 |
+
kernel = cv2.getGaussianKernel(11, 1.5)
|
65 |
+
window = np.outer(kernel, kernel.transpose())
|
66 |
+
|
67 |
+
mu1 = cv2.filter2D(img1, -1, window)[5:-5, 5:-5]
|
68 |
+
mu2 = cv2.filter2D(img2, -1, window)[5:-5, 5:-5]
|
69 |
+
mu1_sq = mu1 ** 2
|
70 |
+
mu2_sq = mu2 ** 2
|
71 |
+
mu1_mu2 = mu1 * mu2
|
72 |
+
sigma1_sq = cv2.filter2D(img1 ** 2, -1, window)[5:-5, 5:-5] - mu1_sq
|
73 |
+
sigma2_sq = cv2.filter2D(img2 ** 2, -1, window)[5:-5, 5:-5] - mu2_sq
|
74 |
+
sigma12 = cv2.filter2D(img1 * img2, -1, window)[5:-5, 5:-5] - mu1_mu2
|
75 |
+
|
76 |
+
ssim_map = ((2 * mu1_mu2 + C1) * (2 * sigma12 + C2)) / ((mu1_sq + mu2_sq + C1) * (sigma1_sq + sigma2_sq + C2))
|
77 |
+
return ssim_map.mean()
|
78 |
+
|
79 |
+
|
80 |
+
def calculate_ssim(img1, img2, crop_border, input_order='HWC', test_y_channel=False):
|
81 |
+
"""Calculate SSIM (structural similarity).
|
82 |
+
|
83 |
+
Ref:
|
84 |
+
Image quality assessment: From error visibility to structural similarity
|
85 |
+
|
86 |
+
The results are the same as that of the official released MATLAB code in
|
87 |
+
https://ece.uwaterloo.ca/~z70wang/research/ssim/.
|
88 |
+
|
89 |
+
For three-channel images, SSIM is calculated for each channel and then
|
90 |
+
averaged.
|
91 |
+
|
92 |
+
Args:
|
93 |
+
img1 (ndarray): Images with range [0, 255].
|
94 |
+
img2 (ndarray): Images with range [0, 255].
|
95 |
+
crop_border (int): Cropped pixels in each edge of an image. These
|
96 |
+
pixels are not involved in the SSIM calculation.
|
97 |
+
input_order (str): Whether the input order is 'HWC' or 'CHW'.
|
98 |
+
Default: 'HWC'.
|
99 |
+
test_y_channel (bool): Test on Y channel of YCbCr. Default: False.
|
100 |
+
|
101 |
+
Returns:
|
102 |
+
float: ssim result.
|
103 |
+
"""
|
104 |
+
|
105 |
+
assert img1.shape == img2.shape, (f'Image shapes are differnet: {img1.shape}, {img2.shape}.')
|
106 |
+
if input_order not in ['HWC', 'CHW']:
|
107 |
+
raise ValueError(f'Wrong input_order {input_order}. Supported input_orders are ' '"HWC" and "CHW"')
|
108 |
+
img1 = reorder_image(img1, input_order=input_order)
|
109 |
+
img2 = reorder_image(img2, input_order=input_order)
|
110 |
+
img1 = img1.astype(np.float64)
|
111 |
+
img2 = img2.astype(np.float64)
|
112 |
+
|
113 |
+
if crop_border != 0:
|
114 |
+
img1 = img1[crop_border:-crop_border, crop_border:-crop_border, ...]
|
115 |
+
img2 = img2[crop_border:-crop_border, crop_border:-crop_border, ...]
|
116 |
+
|
117 |
+
if test_y_channel:
|
118 |
+
img1 = to_y_channel(img1)
|
119 |
+
img2 = to_y_channel(img2)
|
120 |
+
|
121 |
+
ssims = []
|
122 |
+
for i in range(img1.shape[2]):
|
123 |
+
ssims.append(_ssim(img1[..., i], img2[..., i]))
|
124 |
+
return np.array(ssims).mean()
|
125 |
+
|
126 |
+
|
127 |
+
def _blocking_effect_factor(im):
|
128 |
+
block_size = 8
|
129 |
+
|
130 |
+
block_horizontal_positions = torch.arange(7, im.shape[3] - 1, 8)
|
131 |
+
block_vertical_positions = torch.arange(7, im.shape[2] - 1, 8)
|
132 |
+
|
133 |
+
horizontal_block_difference = (
|
134 |
+
(im[:, :, :, block_horizontal_positions] - im[:, :, :, block_horizontal_positions + 1]) ** 2).sum(
|
135 |
+
3).sum(2).sum(1)
|
136 |
+
vertical_block_difference = (
|
137 |
+
(im[:, :, block_vertical_positions, :] - im[:, :, block_vertical_positions + 1, :]) ** 2).sum(3).sum(
|
138 |
+
2).sum(1)
|
139 |
+
|
140 |
+
nonblock_horizontal_positions = np.setdiff1d(torch.arange(0, im.shape[3] - 1), block_horizontal_positions)
|
141 |
+
nonblock_vertical_positions = np.setdiff1d(torch.arange(0, im.shape[2] - 1), block_vertical_positions)
|
142 |
+
|
143 |
+
horizontal_nonblock_difference = (
|
144 |
+
(im[:, :, :, nonblock_horizontal_positions] - im[:, :, :, nonblock_horizontal_positions + 1]) ** 2).sum(
|
145 |
+
3).sum(2).sum(1)
|
146 |
+
vertical_nonblock_difference = (
|
147 |
+
(im[:, :, nonblock_vertical_positions, :] - im[:, :, nonblock_vertical_positions + 1, :]) ** 2).sum(
|
148 |
+
3).sum(2).sum(1)
|
149 |
+
|
150 |
+
n_boundary_horiz = im.shape[2] * (im.shape[3] // block_size - 1)
|
151 |
+
n_boundary_vert = im.shape[3] * (im.shape[2] // block_size - 1)
|
152 |
+
boundary_difference = (horizontal_block_difference + vertical_block_difference) / (
|
153 |
+
n_boundary_horiz + n_boundary_vert)
|
154 |
+
|
155 |
+
n_nonboundary_horiz = im.shape[2] * (im.shape[3] - 1) - n_boundary_horiz
|
156 |
+
n_nonboundary_vert = im.shape[3] * (im.shape[2] - 1) - n_boundary_vert
|
157 |
+
nonboundary_difference = (horizontal_nonblock_difference + vertical_nonblock_difference) / (
|
158 |
+
n_nonboundary_horiz + n_nonboundary_vert)
|
159 |
+
|
160 |
+
scaler = np.log2(block_size) / np.log2(min([im.shape[2], im.shape[3]]))
|
161 |
+
bef = scaler * (boundary_difference - nonboundary_difference)
|
162 |
+
|
163 |
+
bef[boundary_difference <= nonboundary_difference] = 0
|
164 |
+
return bef
|
165 |
+
|
166 |
+
|
167 |
+
def calculate_psnrb(img1, img2, crop_border, input_order='HWC', test_y_channel=False):
|
168 |
+
"""Calculate PSNR-B (Peak Signal-to-Noise Ratio).
|
169 |
+
|
170 |
+
Ref: Quality assessment of deblocked images, for JPEG image deblocking evaluation
|
171 |
+
# https://gitlab.com/Queuecumber/quantization-guided-ac/-/blob/master/metrics/psnrb.py
|
172 |
+
|
173 |
+
Args:
|
174 |
+
img1 (ndarray): Images with range [0, 255].
|
175 |
+
img2 (ndarray): Images with range [0, 255].
|
176 |
+
crop_border (int): Cropped pixels in each edge of an image. These
|
177 |
+
pixels are not involved in the PSNR calculation.
|
178 |
+
input_order (str): Whether the input order is 'HWC' or 'CHW'.
|
179 |
+
Default: 'HWC'.
|
180 |
+
test_y_channel (bool): Test on Y channel of YCbCr. Default: False.
|
181 |
+
|
182 |
+
Returns:
|
183 |
+
float: psnr result.
|
184 |
+
"""
|
185 |
+
|
186 |
+
assert img1.shape == img2.shape, (f'Image shapes are differnet: {img1.shape}, {img2.shape}.')
|
187 |
+
if input_order not in ['HWC', 'CHW']:
|
188 |
+
raise ValueError(f'Wrong input_order {input_order}. Supported input_orders are ' '"HWC" and "CHW"')
|
189 |
+
img1 = reorder_image(img1, input_order=input_order)
|
190 |
+
img2 = reorder_image(img2, input_order=input_order)
|
191 |
+
img1 = img1.astype(np.float64)
|
192 |
+
img2 = img2.astype(np.float64)
|
193 |
+
|
194 |
+
if crop_border != 0:
|
195 |
+
img1 = img1[crop_border:-crop_border, crop_border:-crop_border, ...]
|
196 |
+
img2 = img2[crop_border:-crop_border, crop_border:-crop_border, ...]
|
197 |
+
|
198 |
+
if test_y_channel:
|
199 |
+
img1 = to_y_channel(img1)
|
200 |
+
img2 = to_y_channel(img2)
|
201 |
+
|
202 |
+
# follow https://gitlab.com/Queuecumber/quantization-guided-ac/-/blob/master/metrics/psnrb.py
|
203 |
+
img1 = torch.from_numpy(img1).permute(2, 0, 1).unsqueeze(0) / 255.
|
204 |
+
img2 = torch.from_numpy(img2).permute(2, 0, 1).unsqueeze(0) / 255.
|
205 |
+
|
206 |
+
total = 0
|
207 |
+
for c in range(img1.shape[1]):
|
208 |
+
mse = torch.nn.functional.mse_loss(img1[:, c:c + 1, :, :], img2[:, c:c + 1, :, :], reduction='none')
|
209 |
+
bef = _blocking_effect_factor(img1[:, c:c + 1, :, :])
|
210 |
+
|
211 |
+
mse = mse.view(mse.shape[0], -1).mean(1)
|
212 |
+
total += 10 * torch.log10(1 / (mse + bef))
|
213 |
+
|
214 |
+
return float(total) / img1.shape[1]
|
215 |
+
|
216 |
+
|
217 |
+
def reorder_image(img, input_order='HWC'):
|
218 |
+
"""Reorder images to 'HWC' order.
|
219 |
+
|
220 |
+
If the input_order is (h, w), return (h, w, 1);
|
221 |
+
If the input_order is (c, h, w), return (h, w, c);
|
222 |
+
If the input_order is (h, w, c), return as it is.
|
223 |
+
|
224 |
+
Args:
|
225 |
+
img (ndarray): Input image.
|
226 |
+
input_order (str): Whether the input order is 'HWC' or 'CHW'.
|
227 |
+
If the input image shape is (h, w), input_order will not have
|
228 |
+
effects. Default: 'HWC'.
|
229 |
+
|
230 |
+
Returns:
|
231 |
+
ndarray: reordered image.
|
232 |
+
"""
|
233 |
+
|
234 |
+
if input_order not in ['HWC', 'CHW']:
|
235 |
+
raise ValueError(f'Wrong input_order {input_order}. Supported input_orders are ' "'HWC' and 'CHW'")
|
236 |
+
if len(img.shape) == 2:
|
237 |
+
img = img[..., None]
|
238 |
+
if input_order == 'CHW':
|
239 |
+
img = img.transpose(1, 2, 0)
|
240 |
+
return img
|
241 |
+
|
242 |
+
|
243 |
+
def to_y_channel(img):
|
244 |
+
"""Change to Y channel of YCbCr.
|
245 |
+
|
246 |
+
Args:
|
247 |
+
img (ndarray): Images with range [0, 255].
|
248 |
+
|
249 |
+
Returns:
|
250 |
+
(ndarray): Images with range [0, 255] (float type) without round.
|
251 |
+
"""
|
252 |
+
img = img.astype(np.float32) / 255.
|
253 |
+
if img.ndim == 3 and img.shape[2] == 3:
|
254 |
+
img = bgr2ycbcr(img, y_only=True)
|
255 |
+
img = img[..., None]
|
256 |
+
return img * 255.
|
257 |
+
|
258 |
+
|
259 |
+
def _convert_input_type_range(img):
|
260 |
+
"""Convert the type and range of the input image.
|
261 |
+
|
262 |
+
It converts the input image to np.float32 type and range of [0, 1].
|
263 |
+
It is mainly used for pre-processing the input image in colorspace
|
264 |
+
convertion functions such as rgb2ycbcr and ycbcr2rgb.
|
265 |
+
|
266 |
+
Args:
|
267 |
+
img (ndarray): The input image. It accepts:
|
268 |
+
1. np.uint8 type with range [0, 255];
|
269 |
+
2. np.float32 type with range [0, 1].
|
270 |
+
|
271 |
+
Returns:
|
272 |
+
(ndarray): The converted image with type of np.float32 and range of
|
273 |
+
[0, 1].
|
274 |
+
"""
|
275 |
+
img_type = img.dtype
|
276 |
+
img = img.astype(np.float32)
|
277 |
+
if img_type == np.float32:
|
278 |
+
pass
|
279 |
+
elif img_type == np.uint8:
|
280 |
+
img /= 255.
|
281 |
+
else:
|
282 |
+
raise TypeError('The img type should be np.float32 or np.uint8, ' f'but got {img_type}')
|
283 |
+
return img
|
284 |
+
|
285 |
+
|
286 |
+
def _convert_output_type_range(img, dst_type):
|
287 |
+
"""Convert the type and range of the image according to dst_type.
|
288 |
+
|
289 |
+
It converts the image to desired type and range. If `dst_type` is np.uint8,
|
290 |
+
images will be converted to np.uint8 type with range [0, 255]. If
|
291 |
+
`dst_type` is np.float32, it converts the image to np.float32 type with
|
292 |
+
range [0, 1].
|
293 |
+
It is mainly used for post-processing images in colorspace convertion
|
294 |
+
functions such as rgb2ycbcr and ycbcr2rgb.
|
295 |
+
|
296 |
+
Args:
|
297 |
+
img (ndarray): The image to be converted with np.float32 type and
|
298 |
+
range [0, 255].
|
299 |
+
dst_type (np.uint8 | np.float32): If dst_type is np.uint8, it
|
300 |
+
converts the image to np.uint8 type with range [0, 255]. If
|
301 |
+
dst_type is np.float32, it converts the image to np.float32 type
|
302 |
+
with range [0, 1].
|
303 |
+
|
304 |
+
Returns:
|
305 |
+
(ndarray): The converted image with desired type and range.
|
306 |
+
"""
|
307 |
+
if dst_type not in (np.uint8, np.float32):
|
308 |
+
raise TypeError('The dst_type should be np.float32 or np.uint8, ' f'but got {dst_type}')
|
309 |
+
if dst_type == np.uint8:
|
310 |
+
img = img.round()
|
311 |
+
else:
|
312 |
+
img /= 255.
|
313 |
+
return img.astype(dst_type)
|
314 |
+
|
315 |
+
|
316 |
+
def bgr2ycbcr(img, y_only=False):
|
317 |
+
"""Convert a BGR image to YCbCr image.
|
318 |
+
|
319 |
+
The bgr version of rgb2ycbcr.
|
320 |
+
It implements the ITU-R BT.601 conversion for standard-definition
|
321 |
+
television. See more details in
|
322 |
+
https://en.wikipedia.org/wiki/YCbCr#ITU-R_BT.601_conversion.
|
323 |
+
|
324 |
+
It differs from a similar function in cv2.cvtColor: `BGR <-> YCrCb`.
|
325 |
+
In OpenCV, it implements a JPEG conversion. See more details in
|
326 |
+
https://en.wikipedia.org/wiki/YCbCr#JPEG_conversion.
|
327 |
+
|
328 |
+
Args:
|
329 |
+
img (ndarray): The input image. It accepts:
|
330 |
+
1. np.uint8 type with range [0, 255];
|
331 |
+
2. np.float32 type with range [0, 1].
|
332 |
+
y_only (bool): Whether to only return Y channel. Default: False.
|
333 |
+
|
334 |
+
Returns:
|
335 |
+
ndarray: The converted YCbCr image. The output image has the same type
|
336 |
+
and range as input image.
|
337 |
+
"""
|
338 |
+
img_type = img.dtype
|
339 |
+
img = _convert_input_type_range(img)
|
340 |
+
if y_only:
|
341 |
+
out_img = np.dot(img, [24.966, 128.553, 65.481]) + 16.0
|
342 |
+
else:
|
343 |
+
out_img = np.matmul(
|
344 |
+
img, [[24.966, 112.0, -18.214], [128.553, -74.203, -93.786], [65.481, -37.797, 112.0]]) + [16, 128, 128]
|
345 |
+
out_img = _convert_output_type_range(out_img, img_type)
|
346 |
+
return out_img
|