diff --git a/LICENSE b/LICENSE
new file mode 100644
index 000000000..e5e4ee061
--- /dev/null
+++ b/LICENSE
@@ -0,0 +1,201 @@
+ Apache License
+ Version 2.0, January 2004
+ http://www.apache.org/licenses/
+
+ TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
+
+ 1. Definitions.
+
+ "License" shall mean the terms and conditions for use, reproduction,
+ and distribution as defined by Sections 1 through 9 of this document.
+
+ "Licensor" shall mean the copyright owner or entity authorized by
+ the copyright owner that is granting the License.
+
+ "Legal Entity" shall mean the union of the acting entity and all
+ other entities that control, are controlled by, or are under common
+ control with that entity. For the purposes of this definition,
+ "control" means (i) the power, direct or indirect, to cause the
+ direction or management of such entity, whether by contract or
+ otherwise, or (ii) ownership of fifty percent (50%) or more of the
+ outstanding shares, or (iii) beneficial ownership of such entity.
+
+ "You" (or "Your") shall mean an individual or Legal Entity
+ exercising permissions granted by this License.
+
+ "Source" form shall mean the preferred form for making modifications,
+ including but not limited to software source code, documentation
+ source, and configuration files.
+
+ "Object" form shall mean any form resulting from mechanical
+ transformation or translation of a Source form, including but
+ not limited to compiled object code, generated documentation,
+ and conversions to other media types.
+
+ "Work" shall mean the work of authorship, whether in Source or
+ Object form, made available under the License, as indicated by a
+ copyright notice that is included in or attached to the work
+ (an example is provided in the Appendix below).
+
+ "Derivative Works" shall mean any work, whether in Source or Object
+ form, that is based on (or derived from) the Work and for which the
+ editorial revisions, annotations, elaborations, or other modifications
+ represent, as a whole, an original work of authorship. For the purposes
+ of this License, Derivative Works shall not include works that remain
+ separable from, or merely link (or bind by name) to the interfaces of,
+ the Work and Derivative Works thereof.
+
+ "Contribution" shall mean any work of authorship, including
+ the original version of the Work and any modifications or additions
+ to that Work or Derivative Works thereof, that is intentionally
+ submitted to Licensor for inclusion in the Work by the copyright owner
+ or by an individual or Legal Entity authorized to submit on behalf of
+ the copyright owner. For the purposes of this definition, "submitted"
+ means any form of electronic, verbal, or written communication sent
+ to the Licensor or its representatives, including but not limited to
+ communication on electronic mailing lists, source code control systems,
+ and issue tracking systems that are managed by, or on behalf of, the
+ Licensor for the purpose of discussing and improving the Work, but
+ excluding communication that is conspicuously marked or otherwise
+ designated in writing by the copyright owner as "Not a Contribution."
+
+ "Contributor" shall mean Licensor and any individual or Legal Entity
+ on behalf of whom a Contribution has been received by Licensor and
+ subsequently incorporated within the Work.
+
+ 2. Grant of Copyright License. Subject to the terms and conditions of
+ this License, each Contributor hereby grants to You a perpetual,
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
+ copyright license to reproduce, prepare Derivative Works of,
+ publicly display, publicly perform, sublicense, and distribute the
+ Work and such Derivative Works in Source or Object form.
+
+ 3. Grant of Patent License. Subject to the terms and conditions of
+ this License, each Contributor hereby grants to You a perpetual,
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
+ (except as stated in this section) patent license to make, have made,
+ use, offer to sell, sell, import, and otherwise transfer the Work,
+ where such license applies only to those patent claims licensable
+ by such Contributor that are necessarily infringed by their
+ Contribution(s) alone or by combination of their Contribution(s)
+ with the Work to which such Contribution(s) was submitted. If You
+ institute patent litigation against any entity (including a
+ cross-claim or counterclaim in a lawsuit) alleging that the Work
+ or a Contribution incorporated within the Work constitutes direct
+ or contributory patent infringement, then any patent licenses
+ granted to You under this License for that Work shall terminate
+ as of the date such litigation is filed.
+
+ 4. Redistribution. You may reproduce and distribute copies of the
+ Work or Derivative Works thereof in any medium, with or without
+ modifications, and in Source or Object form, provided that You
+ meet the following conditions:
+
+ (a) You must give any other recipients of the Work or
+ Derivative Works a copy of this License; and
+
+ (b) You must cause any modified files to carry prominent notices
+ stating that You changed the files; and
+
+ (c) You must retain, in the Source form of any Derivative Works
+ that You distribute, all copyright, patent, trademark, and
+ attribution notices from the Source form of the Work,
+ excluding those notices that do not pertain to any part of
+ the Derivative Works; and
+
+ (d) If the Work includes a "NOTICE" text file as part of its
+ distribution, then any Derivative Works that You distribute must
+ include a readable copy of the attribution notices contained
+ within such NOTICE file, excluding those notices that do not
+ pertain to any part of the Derivative Works, in at least one
+ of the following places: within a NOTICE text file distributed
+ as part of the Derivative Works; within the Source form or
+ documentation, if provided along with the Derivative Works; or,
+ within a display generated by the Derivative Works, if and
+ wherever such third-party notices normally appear. The contents
+ of the NOTICE file are for informational purposes only and
+ do not modify the License. You may add Your own attribution
+ notices within Derivative Works that You distribute, alongside
+ or as an addendum to the NOTICE text from the Work, provided
+ that such additional attribution notices cannot be construed
+ as modifying the License.
+
+ You may add Your own copyright statement to Your modifications and
+ may provide additional or different license terms and conditions
+ for use, reproduction, or distribution of Your modifications, or
+ for any such Derivative Works as a whole, provided Your use,
+ reproduction, and distribution of the Work otherwise complies with
+ the conditions stated in this License.
+
+ 5. Submission of Contributions. Unless You explicitly state otherwise,
+ any Contribution intentionally submitted for inclusion in the Work
+ by You to the Licensor shall be under the terms and conditions of
+ this License, without any additional terms or conditions.
+ Notwithstanding the above, nothing herein shall supersede or modify
+ the terms of any separate license agreement you may have executed
+ with Licensor regarding such Contributions.
+
+ 6. Trademarks. This License does not grant permission to use the trade
+ names, trademarks, service marks, or product names of the Licensor,
+ except as required for reasonable and customary use in describing the
+ origin of the Work and reproducing the content of the NOTICE file.
+
+ 7. Disclaimer of Warranty. Unless required by applicable law or
+ agreed to in writing, Licensor provides the Work (and each
+ Contributor provides its Contributions) on an "AS IS" BASIS,
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
+ implied, including, without limitation, any warranties or conditions
+ of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
+ PARTICULAR PURPOSE. You are solely responsible for determining the
+ appropriateness of using or redistributing the Work and assume any
+ risks associated with Your exercise of permissions under this License.
+
+ 8. Limitation of Liability. In no event and under no legal theory,
+ whether in tort (including negligence), contract, or otherwise,
+ unless required by applicable law (such as deliberate and grossly
+ negligent acts) or agreed to in writing, shall any Contributor be
+ liable to You for damages, including any direct, indirect, special,
+ incidental, or consequential damages of any character arising as a
+ result of this License or out of the use or inability to use the
+ Work (including but not limited to damages for loss of goodwill,
+ work stoppage, computer failure or malfunction, or any and all
+ other commercial damages or losses), even if such Contributor
+ has been advised of the possibility of such damages.
+
+ 9. Accepting Warranty or Additional Liability. While redistributing
+ the Work or Derivative Works thereof, You may choose to offer,
+ and charge a fee for, acceptance of support, warranty, indemnity,
+ or other liability obligations and/or rights consistent with this
+ License. However, in accepting such obligations, You may act only
+ on Your own behalf and on Your sole responsibility, not on behalf
+ of any other Contributor, and only if You agree to indemnify,
+ defend, and hold each Contributor harmless for any liability
+ incurred by, or claims asserted against, such Contributor by reason
+ of your accepting any such warranty or additional liability.
+
+ END OF TERMS AND CONDITIONS
+
+ APPENDIX: How to apply the Apache License to your work.
+
+ To apply the Apache License to your work, attach the following
+ boilerplate notice, with the fields enclosed by brackets "[]"
+ replaced with your own identifying information. (Don't include
+ the brackets!) The text should be enclosed in the appropriate
+ comment syntax for the file format. We also recommend that a
+ file or class name and description of purpose be included on the
+ same "printed page" as the copyright notice for easier
+ identification within third-party archives.
+
+ Copyright [2021] [SwinIR Authors]
+
+ Licensed under the Apache License, Version 2.0 (the "License");
+ you may not use this file except in compliance with the License.
+ You may obtain a copy of the License at
+
+ http://www.apache.org/licenses/LICENSE-2.0
+
+ Unless required by applicable law or agreed to in writing, software
+ distributed under the License is distributed on an "AS IS" BASIS,
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ See the License for the specific language governing permissions and
+ limitations under the License.
diff --git a/README.md b/README.md
index e09ca7195..06d93685d 100644
--- a/README.md
+++ b/README.md
@@ -1,2 +1,178 @@
# SwinIR: Image Restoration Using Swin Transformer
-## Stay tuned. The code will arrive before 27th, August.
+
+This repository is the official PyTorch implementation of SwinIR: Image Restoration Using Shifted Window Transformer
+([arxiv](https://arxiv.org/pdf/2108.10257.pdf), [supp](https://github.com/JingyunLiang/SwinIR/releases/tag/v0.0)). SwinIR ahcieves **state-of-the-art performance** in
+- bicubic/lighweight/real-world image SR
+- grayscale/color image denoising
+- JPEG compression artifact reduction
+
+
+
+:rocket: :rocket: :rocket: **News**:
+ - *Aug. 26, 2021: See our recent work on real-world image SR: [a pratical degrdation model BSRGAN, ICCV2021](https://github.com/cszn/BSRGAN)*
+ - *Aug. 26, 2021: See our recent work on generative modelling of image SR and image rescaling: [normalizing-flow-based HCFlow, ICCV2021](https://github.com/JingyunLiang/HCFlow)*
+ - *Aug. 26, 2021: See our recent work on blind SR kernel estimation: [spatially variant kernel estimation (MANet, ICCV2021)](https://github.com/JingyunLiang/MANet) and [unsupervised kernel estimation (FKP, CVPR2021)](https://github.com/JingyunLiang/FKP)*
+
+---
+
+> Image restoration is a long-standing low-level vision problem that aims to restore high-quality images from low-quality images (e.g., downscaled, noisy and compressed images). While state-of-the-art image restoration methods are based on convolutional neural networks, few attempts have been made with Transformers which show impressive performance on high-level vision tasks. In this paper, we propose a strong baseline model SwinIR for image restoration based on the Swin Transformer. SwinIR consists of three parts: shallow feature extraction, deep feature extraction and high-quality image reconstruction. In particular, the deep feature extraction module is composed of several residual Swin Transformer blocks (RSTB), each of which has several Swin Transformer layers together with a residual connection. We conduct experiments on three representative tasks: image super-resolution (including classical, lightweight and real-world image super-resolution), image denoising (including grayscale and color image denoising) and JPEG compression artifact reduction. Experimental results demonstrate that SwinIR outperforms state-of-the-art methods on different tasks by up to 0.14~0.45dB, while the total number of parameters can be reduced by up to 67%.
+>
+
+
+
+
+
+#### Contents
+
+1. [Training](#Training)
+1. [Testing](#Testing)
+1. [Results](#Results)
+1. [Citation](#Citation)
+1. [License and Acknowledgement](#License-and-Acknowledgement)
+
+
+### Training
+
+
+Used training and testing sets can be downloaded as follows:
+
+| Task | Training Set | Testing Set|
+| :--- | :---: | :---: |
+| classical/lightweight image SR | [DIV2K](https://cv.snu.ac.kr/research/EDSR/DIV2K.tar) (800 training images) or DIV2K +[Flickr2K](https://cv.snu.ac.kr/research/EDSR/Flickr2K.tar) (2650 images) | Set5 + Set14 + BSD100 + Urban100 + Manga109 [download all](https://drive.google.com/drive/folders/1B3DJGQKB6eNdwuQIhdskA64qUuVKLZ9u) |
+| real-world image SR | SwinIR-M (middle size): [DIV2K](https://cv.snu.ac.kr/research/EDSR/DIV2K.tar) (800 training images) +[Flickr2K](https://cv.snu.ac.kr/research/EDSR/Flickr2K.tar) (2650 images) + [OST](https://openmmlab.oss-cn-hangzhou.aliyuncs.com/datasets/OST_dataset.zip) (10324 images, sky,water,grass,mountain,building,plant,animal)
SwinIR-L (large size): DIV2K + Flickr2K + OST + [WED](ivc.uwaterloo.ca/database/WaterlooExploration/exploration_database_and_code.rar)(4744 images) + [FFHQ](https://drive.google.com/drive/folders/1tZUcXDBeOibC6jcMCtgRRz67pzrAHeHL) (first 2000 images, face) + Manga109 (manga) + [SCUT-CTW1500](https://universityofadelaide.box.com/shared/static/py5uwlfyyytbb2pxzq9czvu6fuqbjdh8.zip) (first 100 training images, texts)
***We use the degradation model proposed in [BSRGAN, ICCV2021](https://github.com/cszn/BSRGAN)** | [RealSRSet](https://github.com/cszn/BSRGAN/tree/main/testsets/RealSRSet) |
+| color/grayscale image denoising | [DIV2K](https://cv.snu.ac.kr/research/EDSR/DIV2K.tar) (800 training images) + [Flickr2K](https://cv.snu.ac.kr/research/EDSR/Flickr2K.tar) (2650 images) + [BSD500](www.eecs.berkeley.edu/Research/Projects/CS/vision/grouping/BSR/BSR_bsds500.tgz) (400 training&testing images) + [WED](ivc.uwaterloo.ca/database/WaterlooExploration/exploration_database_and_code.rar)(4744 images) | grayscale: Set12 + BSD68 + Urban100
color: CBSD68 + Kodak24 + McMaster + Urban100 [download all](https://github.com/cszn/FFDNet/tree/master/testsets) |
+| JPEG compression artifact reduction | [DIV2K](https://cv.snu.ac.kr/research/EDSR/DIV2K.tar) (800 training images) + [Flickr2K](https://cv.snu.ac.kr/research/EDSR/Flickr2K.tar) (2650 images) + [BSD500](www.eecs.berkeley.edu/Research/Projects/CS/vision/grouping/BSR/BSR_bsds500.tgz) (400 training&testing images) + [WED](ivc.uwaterloo.ca/database/WaterlooExploration/exploration_database_and_code.rar)(4744 images) | grayscale: Classic5 +LIVE1 [download all](https://github.com/cszn/DnCNN/tree/master/testsets) |
+
+
+
+
+The training code will be put in [KAIR](https://github.com/cszn/KAIR).
+
+## Testing (without preparing datasets)
+For your convience, we provide some example datasets (~20Mb) in `/testsets`.
+If you just want codes, downloading `models/network_swinir.py`, `utils/util_calculate_psnr_ssim.py` and `main_test_swinir.py` is enough.
+Download [pretrained models](https://github.com/JingyunLiang/SwinIR/releases/tag/v0.0) and put them in `model_zoo/swinir`, then run following commands:
+
+
+```bash
+# 001 Classical Image Super-Resolution (middle size)
+# (when model is trained on DIV2K, use patch_size=48)
+python main_test_swinir.py --task classical_sr --scale 2 --patch_size 48 --model_path model_zoo/swinir/001_classicalSR_DIV2K_s48w8_SwinIR-M_x2.pth --folder_lq testsets/Set5/LR_bicubic/X2 --folder_gt testsets/Set5/HR
+python main_test_swinir.py --task classical_sr --scale 3 --patch_size 48 --model_path model_zoo/swinir/001_classicalSR_DIV2K_s48w8_SwinIR-M_x3.pth --folder_lq testsets/Set5/LR_bicubic/X3 --folder_gt testsets/Set5/HR
+python main_test_swinir.py --task classical_sr --scale 4 --patch_size 48 --model_path model_zoo/swinir/001_classicalSR_DIV2K_s48w8_SwinIR-M_x4.pth --folder_lq testsets/Set5/LR_bicubic/X4 --folder_gt testsets/Set5/HR
+python main_test_swinir.py --task classical_sr --scale 8 --patch_size 48 --model_path model_zoo/swinir/001_classicalSR_DIV2K_s48w8_SwinIR-M_x8.pth --folder_lq testsets/Set5/LR_bicubic/X8 --folder_gt testsets/Set5/HR
+
+# (when model is trained on DIV2K+Flickr2K, use patch_size=64)
+python main_test_swinir.py --task classical_sr --scale 2 --patch_size 64 --model_path model_zoo/swinir/001_classicalSR_DF2K_s64w8_SwinIR-M_x2.pth --folder_lq testsets/Set5/LR_bicubic/X2 --folder_gt testsets/Set5/HR
+python main_test_swinir.py --task classical_sr --scale 3 --patch_size 64 --model_path model_zoo/swinir/001_classicalSR_DF2K_s64w8_SwinIR-M_x3.pth --folder_lq testsets/Set5/LR_bicubic/X3 --folder_gt testsets/Set5/HR
+python main_test_swinir.py --task classical_sr --scale 4 --patch_size 64 --model_path model_zoo/swinir/001_classicalSR_DF2K_s64w8_SwinIR-M_x4.pth --folder_lq testsets/Set5/LR_bicubic/X4 --folder_gt testsets/Set5/HR
+python main_test_swinir.py --task classical_sr --scale 8 --patch_size 64 --model_path model_zoo/swinir/001_classicalSR_DF2K_s64w8_SwinIR-M_x8.pth --folder_lq testsets/Set5/LR_bicubic/X8 --folder_gt testsets/Set5/HR
+
+
+# 002 Lightweight Image Super-Resolution (small size)
+python main_test_swinir.py --task lightweight_sr --scale 2 --model_path model_zoo/swinir/002_lightweightSR_DIV2K_s64w8_SwinIR-S_x2.pth --folder_lq testsets/Set5/LR_bicubic/X2 --folder_gt testsets/Set5/HR
+python main_test_swinir.py --task lightweight_sr --scale 3 --model_path model_zoo/swinir/002_lightweightSR_DIV2K_s64w8_SwinIR-S_x3.pth --folder_lq testsets/Set5/LR_bicubic/X3 --folder_gt testsets/Set5/HR
+python main_test_swinir.py --task lightweight_sr --scale 4 --model_path model_zoo/swinir/002_lightweightSR_DIV2K_s64w8_SwinIR-S_x4.pth --folder_lq testsets/Set5/LR_bicubic/X4 --folder_gt testsets/Set5/HR
+
+
+# 003 Real-World Image Super-Resolution
+# (middle size)
+python main_test_swinir.py --task real_sr --scale 4 --model_path model_zoo/swinir/003_realSR_BSRGAN_DFO_s64w8_SwinIR-M_x4_GAN.pth --folder_lq testsets/RealSRSet+5images
+
+# (larger size + trained on more datasets)
+# python main_test_swinir.py --task real_sr --scale 4 --large_model --model_path model_zoo/swinir/003_realSR_BSRGAN_DFOWMFC_s64w8_SwinIR-L_x4_GAN.pth --folder_lq testsets/RealSRSet+5images
+
+
+# 004 Grayscale Image Deoising (middle size)
+python main_test_swinir.py --task gray_dn --noise 15 --model_path model_zoo/swinir/004_grayDN_DFWB_s128w8_SwinIR-M_noise15.pth --folder_gt testsets/Set12
+python main_test_swinir.py --task gray_dn --noise 25 --model_path model_zoo/swinir/004_grayDN_DFWB_s128w8_SwinIR-M_noise25.pth --folder_gt testsets/Set12
+python main_test_swinir.py --task gray_dn --noise 50 --model_path model_zoo/swinir/004_grayDN_DFWB_s128w8_SwinIR-M_noise50.pth --folder_gt testsets/Set12
+
+
+# 005 Color Image Deoising (middle size)
+python main_test_swinir.py --task color_dn --noise 15 --model_path model_zoo/swinir/005_colorDN_DFWB_s128w8_SwinIR-M_noise15.pth --folder_gt testsets/McMaster
+python main_test_swinir.py --task color_dn --noise 25 --model_path model_zoo/swinir/005_colorDN_DFWB_s128w8_SwinIR-M_noise25.pth --folder_gt testsets/McMaster
+python main_test_swinir.py --task color_dn --noise 50 --model_path model_zoo/swinir/005_colorDN_DFWB_s128w8_SwinIR-M_noise50.pth --folder_gt testsets/McMaster
+
+
+# 006 JPEG Compression Artifact Reduction (middle size, using window_size=7 because JPEG encoding uses 8x8 blocks)
+python main_test_swinir.py --task jpeg_car --jpeg 10 --model_path model_zoo/swinir/006_CAR_DFWB_s126w7_SwinIR-M_jpeg10.pth --folder_gt testsets/classic5
+python main_test_swinir.py --task jpeg_car --jpeg 20 --model_path model_zoo/swinir/006_CAR_DFWB_s126w7_SwinIR-M_jpeg20.pth --folder_gt testsets/classic5
+python main_test_swinir.py --task jpeg_car --jpeg 30 --model_path model_zoo/swinir/006_CAR_DFWB_s126w7_SwinIR-M_jpeg30.pth --folder_gt testsets/classic5
+python main_test_swinir.py --task jpeg_car --jpeg 40 --model_path model_zoo/swinir/006_CAR_DFWB_s126w7_SwinIR-M_jpeg40.pth --folder_gt testsets/classic5
+
+```
+
+***All visual results of SwinIR can be downloaded [here](https://github.com/JingyunLiang/SwinIR/releases/tag/v0.0)**.
+
+*Large size real-world image SR model (`003_realSR_BSRGAN_DFOWMFC_s64w8_SwinIR-L_x4_GAN.pth`) will be released later.
+
+---
+
+## Results
+We achieved state-of-the-art performance on classical/lightweight/real-world image SR, grayscale/color image denoising and JPEG compression artifact reduction. Detailed results can be found in the [paper](https://arxiv.org/abs/2108.10257).
+
+
+Classical Image Super-Resolution (click me)
+
+
+
+
+
+
+
+Lightweight Image Super-Resolution
+
+
+
+
+
+
+Real-World Image Super-Resolution
+
+
+
+
+
+
+Grayscale Image Deoising
+
+
+
+
+
+
+Color Image Deoising
+
+
+
+
+
+
+JPEG Compression Artifact Reduction
+
+
+
+
+
+
+
+## Citation
+ @article{liang2021swinir,
+ title={SwinIR: Image Restoration Using Swin Transformer},
+ author={Liang, Jingyun and Cao, Jiezhang and Sun, Guolei and Zhang, Kai and Van Gool, Luc and Timofte, Radu},
+ journal={arXiv preprint arXiv:2108.10257},
+ year={2021}
+ }
+
+## License and Acknowledgement
+This project is released under the Apache 2.0 license. The codes are heavily based on [Swin Transformer](https://github.com/microsoft/Swin-Transformer). We also refer to codes in [KAIR](https://github.com/cszn/KAIR) and [BasicSR](https://github.com/xinntao/BasicSR). Please also follow their licenses. Thanks for their awesome works.
diff --git a/figs/SwinIR_archi.png b/figs/SwinIR_archi.png
new file mode 100644
index 000000000..a4cb6fc5e
Binary files /dev/null and b/figs/SwinIR_archi.png differ
diff --git a/figs/classic_image_sr.png b/figs/classic_image_sr.png
new file mode 100644
index 000000000..5c8f931d9
Binary files /dev/null and b/figs/classic_image_sr.png differ
diff --git a/figs/classic_image_sr_visual.png b/figs/classic_image_sr_visual.png
new file mode 100644
index 000000000..0ffa8ab8a
Binary files /dev/null and b/figs/classic_image_sr_visual.png differ
diff --git a/figs/color_image_denoising.png b/figs/color_image_denoising.png
new file mode 100644
index 000000000..a0f184145
Binary files /dev/null and b/figs/color_image_denoising.png differ
diff --git a/figs/gray_image_denoising.png b/figs/gray_image_denoising.png
new file mode 100644
index 000000000..c06cad4b0
Binary files /dev/null and b/figs/gray_image_denoising.png differ
diff --git a/figs/jepg_compress_artfact_reduction.png b/figs/jepg_compress_artfact_reduction.png
new file mode 100644
index 000000000..a5551df79
Binary files /dev/null and b/figs/jepg_compress_artfact_reduction.png differ
diff --git a/figs/lightweight_image_sr.png b/figs/lightweight_image_sr.png
new file mode 100644
index 000000000..af13c7e52
Binary files /dev/null and b/figs/lightweight_image_sr.png differ
diff --git a/figs/real_world_image_sr.png b/figs/real_world_image_sr.png
new file mode 100644
index 000000000..fadd9071d
Binary files /dev/null and b/figs/real_world_image_sr.png differ
diff --git a/main_test_swinir.py b/main_test_swinir.py
new file mode 100644
index 000000000..bf9c08eb8
--- /dev/null
+++ b/main_test_swinir.py
@@ -0,0 +1,239 @@
+import argparse
+import cv2
+import glob
+import numpy as np
+from collections import OrderedDict
+import os
+import torch
+
+from models.network_swinir import SwinIR as net
+from utils import util_calculate_psnr_ssim as util
+
+
+def main():
+ parser = argparse.ArgumentParser()
+ parser.add_argument('--task', type=str, default='color_dn', help='classical_sr, lightweight_sr, real_sr, '
+ 'gray_dn, color_dn, jpeg_car')
+ parser.add_argument('--scale', type=int, default=1, help='scale factor: 1, 2, 3, 4, 8') # 1 for dn and jpeg car
+ parser.add_argument('--noise', type=int, default=15, help='noise level: 15, 25, 50')
+ parser.add_argument('--jpeg', type=int, default=40, help='scale factor: 10, 20, 30, 40')
+ parser.add_argument('--patch_size', type=int, default=128, help='patch size used in SwinIR')
+ parser.add_argument('--large_model', action='store_true', help='use large model, only provided for real image sr')
+ parser.add_argument('--model_path', type=str,
+ default='model_zoo/swinir/001_classicalSR_DIV2K_s48w8_SwinIR-M_x2.pth')
+ parser.add_argument('--folder_lq', type=str, default=None, help='input low-quality test image folder')
+ parser.add_argument('--folder_gt', type=str, default=None, help='input ground-truth test image folder')
+ args = parser.parse_args()
+
+ device = torch.device('cuda' if torch.cuda.is_available() else 'cpu')
+ # set up model
+ print(f'loading model from {args.model_path}')
+ model = define_model(args)
+ model.eval()
+ model = model.to(device)
+
+ # setup folder and path
+ folder, save_dir, border, window_size = setup(args)
+ os.makedirs(save_dir, exist_ok=True)
+ test_results = OrderedDict()
+ test_results['psnr'] = []
+ test_results['ssim'] = []
+ test_results['psnr_y'] = []
+ test_results['ssim_y'] = []
+ test_results['psnr_b'] = []
+ psnr, ssim, psnr_y, ssim_y, psnr_b = 0, 0, 0, 0, 0
+
+ for idx, path in enumerate(sorted(glob.glob(os.path.join(folder, '*')))):
+ # read image
+ imgname, img_lq, img_gt = get_image_pair(args, path) # image to HWC-BGR, float32
+ 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
+ img_lq = torch.from_numpy(img_lq).float().unsqueeze(0).to(device) # CHW-RGB to NCHW-RGB
+
+ # inference
+ with torch.no_grad():
+ # pad input image to be a multiple of window_size
+ _, _, h_old, w_old = img_lq.size()
+ h_pad = (h_old // window_size + 1) * window_size - h_old
+ w_pad = (w_old // window_size + 1) * window_size - w_old
+ img_lq = torch.cat([img_lq, torch.flip(img_lq, [2])], 2)[:, :, :h_old + h_pad, :]
+ img_lq = torch.cat([img_lq, torch.flip(img_lq, [3])], 3)[:, :, :, :w_old + w_pad]
+ output = model(img_lq)
+ output = output[..., :h_old * args.scale, :w_old * args.scale]
+
+ # save image
+ output = output.data.squeeze().float().cpu().clamp_(0, 1).numpy()
+ if output.ndim == 3:
+ output = np.transpose(output[[2, 1, 0], :, :], (1, 2, 0)) # CHW-RGB to HCW-BGR
+ output = (output * 255.0).round().astype(np.uint8) # float32 to uint8
+ cv2.imwrite(f'{save_dir}/{imgname}_SwinIR.png', output)
+
+ # evaluate psnr/ssim/psnr_b
+ if img_gt is not None:
+ img_gt = (img_gt * 255.0).round().astype(np.uint8) # float32 to uint8
+ img_gt = img_gt[:h_old * args.scale, :w_old * args.scale, ...] # crop gt
+ img_gt = np.squeeze(img_gt)
+
+ psnr = util.calculate_psnr(output, img_gt, crop_border=border)
+ ssim = util.calculate_ssim(output, img_gt, crop_border=border)
+ test_results['psnr'].append(psnr)
+ test_results['ssim'].append(ssim)
+ if img_gt.ndim == 3: # RGB image
+ psnr_y = util.calculate_psnr(output, img_gt, crop_border=border, test_y_channel=True)
+ ssim_y = util.calculate_ssim(output, img_gt, crop_border=border, test_y_channel=True)
+ test_results['psnr_y'].append(psnr_y)
+ test_results['ssim_y'].append(ssim_y)
+ if args.task in ['jpeg_car']:
+ psnr_b = util.calculate_psnrb(output, img_gt, crop_border=border, test_y_channel=True)
+ test_results['psnr_b'].append(psnr_b)
+ print('Testing {:d} {:20s} - PSNR: {:.2f} dB; SSIM: {:.4f}; '
+ 'PSNR_Y: {:.2f} dB; SSIM_Y: {:.4f}; '
+ 'PSNR_B: {:.2f} dB.'.
+ format(idx, imgname, psnr, ssim, psnr_y, ssim_y, psnr_b))
+ else:
+ print('Testing {:d} {:20s}'.format(idx, imgname))
+
+ # summarize psnr/ssim
+ if img_gt is not None:
+ ave_psnr = sum(test_results['psnr']) / len(test_results['psnr'])
+ ave_ssim = sum(test_results['ssim']) / len(test_results['ssim'])
+ print('\n{} \n-- Average PSNR/SSIM(RGB): {:.2f} dB; {:.4f}'.format(save_dir, ave_psnr, ave_ssim))
+ if img_gt.ndim == 3:
+ ave_psnr_y = sum(test_results['psnr_y']) / len(test_results['psnr_y'])
+ ave_ssim_y = sum(test_results['ssim_y']) / len(test_results['ssim_y'])
+ print('-- Average PSNR_Y/SSIM_Y: {:.2f} dB; {:.4f}'.format(ave_psnr_y, ave_ssim_y))
+ if args.task in ['jpeg_car']:
+ ave_psnr_b = sum(test_results['psnr_b']) / len(test_results['psnr_b'])
+ print('-- Average PSNR_B: {:.2f} dB'.format(ave_psnr_b))
+
+
+def define_model(args):
+ # 001 classical image sr
+ if args.task == 'classical_sr':
+ model = net(upscale=args.scale, in_chans=3, img_size=args.patch_size, window_size=8,
+ img_range=1., depths=[6, 6, 6, 6, 6, 6], embed_dim=180, num_heads=[6, 6, 6, 6, 6, 6],
+ mlp_ratio=2, upsampler='pixelshuffle', resi_connection='1conv')
+ model.load_state_dict(torch.load(args.model_path)['params'], strict=True)
+
+ # 002 lightweight image sr
+ # use 'pixelshuffledirect' to save parameters
+ elif args.task == 'lightweight_sr':
+ model = net(upscale=args.scale, in_chans=3, img_size=64, window_size=8,
+ img_range=1., depths=[6, 6, 6, 6], embed_dim=60, num_heads=[6, 6, 6, 6],
+ mlp_ratio=2, upsampler='pixelshuffledirect', resi_connection='1conv')
+ model.load_state_dict(torch.load(args.model_path)['params'], strict=True)
+
+ # 003 real-world image sr
+ elif args.task == 'real_sr':
+ if not args.large_model:
+ # use 'nearest+conv' to avoid block artifacts
+ model = net(upscale=4, in_chans=3, img_size=64, window_size=8,
+ img_range=1., depths=[6, 6, 6, 6, 6, 6], embed_dim=180, num_heads=[6, 6, 6, 6, 6, 6],
+ mlp_ratio=2, upsampler='nearest+conv', resi_connection='1conv')
+ else:
+ # larger model size; use '3conv' to save parameters and memory; use ema for GAN training
+ model = net(upscale=4, in_chans=3, img_size=64, window_size=8,
+ img_range=1., depths=[6, 6, 6, 6, 6, 6, 6, 6, 6], embed_dim=248,
+ num_heads=[8, 8, 8, 8, 8, 8, 8, 8, 8],
+ mlp_ratio=2, upsampler='nearest+conv', resi_connection='3conv')
+ model.load_state_dict(torch.load(args.model_path)['params_ema'], strict=True) #
+
+ # 004 grayscale image denoising
+ elif args.task == 'gray_dn':
+ model = net(upscale=1, in_chans=1, img_size=128, window_size=8,
+ img_range=1., depths=[6, 6, 6, 6, 6, 6], embed_dim=180, num_heads=[6, 6, 6, 6, 6, 6],
+ mlp_ratio=2, upsampler='', resi_connection='1conv')
+ model.load_state_dict(torch.load(args.model_path)['params'], strict=True)
+
+ # 005 color image denoising
+ elif args.task == 'color_dn':
+ model = net(upscale=1, in_chans=3, img_size=128, window_size=8,
+ img_range=1., depths=[6, 6, 6, 6, 6, 6], embed_dim=180, num_heads=[6, 6, 6, 6, 6, 6],
+ mlp_ratio=2, upsampler='', resi_connection='1conv')
+ model.load_state_dict(torch.load(args.model_path)['params'], strict=True)
+
+ # 006 JPEG compression artifact reduction
+ # use window_size=7 because JPEG encoding uses 8x8; use img_range=255 because it's sligtly better than 1
+ elif args.task == 'jpeg_car':
+ model = net(upscale=1, in_chans=1, img_size=126, window_size=7,
+ img_range=255., depths=[6, 6, 6, 6, 6, 6], embed_dim=180, num_heads=[6, 6, 6, 6, 6, 6],
+ mlp_ratio=2, upsampler='', resi_connection='1conv')
+ model.load_state_dict(torch.load(args.model_path)['params'], strict=True)
+
+ return model
+
+
+def setup(args):
+ # 001 classical image sr/ 002 lightweight image sr
+ if args.task in ['classical_sr', 'lightweight_sr']:
+ save_dir = f'results/swinir_{args.task}_x{args.scale}'
+ folder = args.folder_gt
+ border = args.scale
+ window_size = 8
+
+ # 003 real-world image sr
+ elif args.task in ['real_sr']:
+ save_dir = f'results/swinir_{args.task}_x{args.scale}'
+ folder = args.folder_lq
+ border = 0
+ window_size = 8
+
+ # 004 grayscale image denoising/ 005 color image denoising
+ elif args.task in ['gray_dn', 'color_dn']:
+ save_dir = f'results/swinir_{args.task}_noise{args.noise}'
+ folder = args.folder_gt
+ border = 0
+ window_size = 8
+
+ # 006 JPEG compression artifact reduction
+ elif args.task in ['jpeg_car']:
+ save_dir = f'results/swinir_{args.task}_jpeg{args.jpeg}'
+ folder = args.folder_gt
+ border = 0
+ window_size = 7
+
+ return folder, save_dir, border, window_size
+
+
+def get_image_pair(args, path):
+ (imgname, imgext) = os.path.splitext(os.path.basename(path))
+
+ # 001 classical image sr/ 002 lightweight image sr (load lq-gt image pairs)
+ if args.task in ['classical_sr', 'lightweight_sr']:
+ img_gt = cv2.imread(path, cv2.IMREAD_COLOR).astype(np.float32) / 255.
+ img_lq = cv2.imread(f'{args.folder_lq}/{imgname}x{args.scale}{imgext}', cv2.IMREAD_COLOR).astype(
+ np.float32) / 255.
+
+ # 003 real-world image sr (load lq image only)
+ elif args.task in ['real_sr']:
+ img_gt = None
+ img_lq = cv2.imread(path, cv2.IMREAD_COLOR).astype(np.float32) / 255.
+
+ # 004 grayscale image denoising (load gt image and generate lq image on-the-fly)
+ elif args.task in ['gray_dn']:
+ img_gt = cv2.imread(path, cv2.IMREAD_GRAYSCALE).astype(np.float32) / 255.
+ np.random.seed(seed=0)
+ img_lq = img_gt + np.random.normal(0, args.noise / 255., img_gt.shape)
+ img_gt = np.expand_dims(img_gt, axis=2)
+ img_lq = np.expand_dims(img_lq, axis=2)
+
+ # 005 color image denoising (load gt image and generate lq image on-the-fly)
+ elif args.task in ['color_dn']:
+ img_gt = cv2.imread(path, cv2.IMREAD_COLOR).astype(np.float32) / 255.
+ np.random.seed(seed=0)
+ img_lq = img_gt + np.random.normal(0, args.noise / 255., img_gt.shape)
+
+ # 006 JPEG compression artifact reduction (load gt image and generate lq image on-the-fly)
+ elif args.task in ['jpeg_car']:
+ img_gt = cv2.imread(path, cv2.IMREAD_UNCHANGED)
+ if img_gt.ndim != 2:
+ img_gt = util.rgb2ycbcr(cv2.cvtColor(img_gt, cv2.COLOR_BGR2RGB), y_only=True)
+ result, encimg = cv2.imencode('.jpg', img_gt, [int(cv2.IMWRITE_JPEG_QUALITY), args.jpeg])
+ img_lq = cv2.imdecode(encimg, 0)
+ img_gt = np.expand_dims(img_gt, axis=2).astype(np.float32) / 255.
+ img_lq = np.expand_dims(img_lq, axis=2).astype(np.float32) / 255.
+
+ return imgname, img_lq, img_gt
+
+
+if __name__ == '__main__':
+ main()
diff --git a/model_zoo/README.md b/model_zoo/README.md
new file mode 100644
index 000000000..a9e5c2a4b
--- /dev/null
+++ b/model_zoo/README.md
@@ -0,0 +1,3 @@
+model_zoo
+
+The SwinIR models are available at [here](https://github.com/JingyunLiang/SwinIR/releases/tag/v0.0).
\ No newline at end of file
diff --git a/models/network_swinir.py b/models/network_swinir.py
new file mode 100644
index 000000000..c69d16a50
--- /dev/null
+++ b/models/network_swinir.py
@@ -0,0 +1,854 @@
+# -----------------------------------------------------------------------------------
+# SwinIR: Image Restoration Using Swin Transformer, https://arxiv.org/abs/2108.10257
+# Originally Written by Ze Liu, Modified by Jingyun Liang.
+# -----------------------------------------------------------------------------------
+
+import math
+import torch
+import torch.nn as nn
+import torch.utils.checkpoint as checkpoint
+from timm.models.layers import DropPath, to_2tuple, trunc_normal_
+
+
+class Mlp(nn.Module):
+ def __init__(self, in_features, hidden_features=None, out_features=None, act_layer=nn.GELU, drop=0.):
+ super().__init__()
+ out_features = out_features or in_features
+ hidden_features = hidden_features or in_features
+ self.fc1 = nn.Linear(in_features, hidden_features)
+ self.act = act_layer()
+ self.fc2 = nn.Linear(hidden_features, out_features)
+ self.drop = nn.Dropout(drop)
+
+ def forward(self, x):
+ x = self.fc1(x)
+ x = self.act(x)
+ x = self.drop(x)
+ x = self.fc2(x)
+ x = self.drop(x)
+ return x
+
+
+def window_partition(x, window_size):
+ """
+ Args:
+ x: (B, H, W, C)
+ window_size (int): window size
+
+ Returns:
+ windows: (num_windows*B, window_size, window_size, C)
+ """
+ B, H, W, C = x.shape
+ x = x.view(B, H // window_size, window_size, W // window_size, window_size, C)
+ windows = x.permute(0, 1, 3, 2, 4, 5).contiguous().view(-1, window_size, window_size, C)
+ return windows
+
+
+def window_reverse(windows, window_size, H, W):
+ """
+ Args:
+ windows: (num_windows*B, window_size, window_size, C)
+ window_size (int): Window size
+ H (int): Height of image
+ W (int): Width of image
+
+ Returns:
+ x: (B, H, W, C)
+ """
+ B = int(windows.shape[0] / (H * W / window_size / window_size))
+ x = windows.view(B, H // window_size, W // window_size, window_size, window_size, -1)
+ x = x.permute(0, 1, 3, 2, 4, 5).contiguous().view(B, H, W, -1)
+ return x
+
+
+class WindowAttention(nn.Module):
+ r""" Window based multi-head self attention (W-MSA) module with relative position bias.
+ It supports both of shifted and non-shifted window.
+
+ Args:
+ dim (int): Number of input channels.
+ window_size (tuple[int]): The height and width of the window.
+ num_heads (int): Number of attention heads.
+ qkv_bias (bool, optional): If True, add a learnable bias to query, key, value. Default: True
+ qk_scale (float | None, optional): Override default qk scale of head_dim ** -0.5 if set
+ attn_drop (float, optional): Dropout ratio of attention weight. Default: 0.0
+ proj_drop (float, optional): Dropout ratio of output. Default: 0.0
+ """
+
+ def __init__(self, dim, window_size, num_heads, qkv_bias=True, qk_scale=None, attn_drop=0., proj_drop=0.):
+
+ super().__init__()
+ self.dim = dim
+ self.window_size = window_size # Wh, Ww
+ self.num_heads = num_heads
+ head_dim = dim // num_heads
+ self.scale = qk_scale or head_dim ** -0.5
+
+ # define a parameter table of relative position bias
+ self.relative_position_bias_table = nn.Parameter(
+ torch.zeros((2 * window_size[0] - 1) * (2 * window_size[1] - 1), num_heads)) # 2*Wh-1 * 2*Ww-1, nH
+
+ # get pair-wise relative position index for each token inside the window
+ coords_h = torch.arange(self.window_size[0])
+ coords_w = torch.arange(self.window_size[1])
+ coords = torch.stack(torch.meshgrid([coords_h, coords_w])) # 2, Wh, Ww
+ coords_flatten = torch.flatten(coords, 1) # 2, Wh*Ww
+ relative_coords = coords_flatten[:, :, None] - coords_flatten[:, None, :] # 2, Wh*Ww, Wh*Ww
+ relative_coords = relative_coords.permute(1, 2, 0).contiguous() # Wh*Ww, Wh*Ww, 2
+ relative_coords[:, :, 0] += self.window_size[0] - 1 # shift to start from 0
+ relative_coords[:, :, 1] += self.window_size[1] - 1
+ relative_coords[:, :, 0] *= 2 * self.window_size[1] - 1
+ relative_position_index = relative_coords.sum(-1) # Wh*Ww, Wh*Ww
+ self.register_buffer("relative_position_index", relative_position_index)
+
+ self.qkv = nn.Linear(dim, dim * 3, bias=qkv_bias)
+ self.attn_drop = nn.Dropout(attn_drop)
+ self.proj = nn.Linear(dim, dim)
+
+ self.proj_drop = nn.Dropout(proj_drop)
+
+ trunc_normal_(self.relative_position_bias_table, std=.02)
+ self.softmax = nn.Softmax(dim=-1)
+
+ def forward(self, x, mask=None):
+ """
+ Args:
+ x: input features with shape of (num_windows*B, N, C)
+ mask: (0/-inf) mask with shape of (num_windows, Wh*Ww, Wh*Ww) or None
+ """
+ B_, N, C = x.shape
+ qkv = self.qkv(x).reshape(B_, N, 3, self.num_heads, C // self.num_heads).permute(2, 0, 3, 1, 4)
+ q, k, v = qkv[0], qkv[1], qkv[2] # make torchscript happy (cannot use tensor as tuple)
+
+ q = q * self.scale
+ attn = (q @ k.transpose(-2, -1))
+
+ relative_position_bias = self.relative_position_bias_table[self.relative_position_index.view(-1)].view(
+ self.window_size[0] * self.window_size[1], self.window_size[0] * self.window_size[1], -1) # Wh*Ww,Wh*Ww,nH
+ relative_position_bias = relative_position_bias.permute(2, 0, 1).contiguous() # nH, Wh*Ww, Wh*Ww
+ attn = attn + relative_position_bias.unsqueeze(0)
+
+ if mask is not None:
+ nW = mask.shape[0]
+ attn = attn.view(B_ // nW, nW, self.num_heads, N, N) + mask.unsqueeze(1).unsqueeze(0)
+ attn = attn.view(-1, self.num_heads, N, N)
+ attn = self.softmax(attn)
+ else:
+ attn = self.softmax(attn)
+
+ attn = self.attn_drop(attn)
+
+ x = (attn @ v).transpose(1, 2).reshape(B_, N, C)
+ x = self.proj(x)
+ x = self.proj_drop(x)
+ return x
+
+ def extra_repr(self) -> str:
+ return f'dim={self.dim}, window_size={self.window_size}, num_heads={self.num_heads}'
+
+ def flops(self, N):
+ # calculate flops for 1 window with token length of N
+ flops = 0
+ # qkv = self.qkv(x)
+ flops += N * self.dim * 3 * self.dim
+ # attn = (q @ k.transpose(-2, -1))
+ flops += self.num_heads * N * (self.dim // self.num_heads) * N
+ # x = (attn @ v)
+ flops += self.num_heads * N * N * (self.dim // self.num_heads)
+ # x = self.proj(x)
+ flops += N * self.dim * self.dim
+ return flops
+
+
+class SwinTransformerBlock(nn.Module):
+ r""" Swin Transformer Block.
+
+ Args:
+ dim (int): Number of input channels.
+ input_resolution (tuple[int]): Input resulotion.
+ num_heads (int): Number of attention heads.
+ window_size (int): Window size.
+ shift_size (int): Shift size for SW-MSA.
+ mlp_ratio (float): Ratio of mlp hidden dim to embedding dim.
+ qkv_bias (bool, optional): If True, add a learnable bias to query, key, value. Default: True
+ qk_scale (float | None, optional): Override default qk scale of head_dim ** -0.5 if set.
+ drop (float, optional): Dropout rate. Default: 0.0
+ attn_drop (float, optional): Attention dropout rate. Default: 0.0
+ drop_path (float, optional): Stochastic depth rate. Default: 0.0
+ act_layer (nn.Module, optional): Activation layer. Default: nn.GELU
+ norm_layer (nn.Module, optional): Normalization layer. Default: nn.LayerNorm
+ """
+
+ def __init__(self, dim, input_resolution, num_heads, window_size=7, shift_size=0,
+ mlp_ratio=4., qkv_bias=True, qk_scale=None, drop=0., attn_drop=0., drop_path=0.,
+ act_layer=nn.GELU, norm_layer=nn.LayerNorm):
+ super().__init__()
+ self.dim = dim
+ self.input_resolution = input_resolution
+ self.num_heads = num_heads
+ self.window_size = window_size
+ self.shift_size = shift_size
+ self.mlp_ratio = mlp_ratio
+ if min(self.input_resolution) <= self.window_size:
+ # if window size is larger than input resolution, we don't partition windows
+ self.shift_size = 0
+ self.window_size = min(self.input_resolution)
+ assert 0 <= self.shift_size < self.window_size, "shift_size must in 0-window_size"
+
+ self.norm1 = norm_layer(dim)
+ self.attn = WindowAttention(
+ dim, window_size=to_2tuple(self.window_size), num_heads=num_heads,
+ qkv_bias=qkv_bias, qk_scale=qk_scale, attn_drop=attn_drop, proj_drop=drop)
+
+ self.drop_path = DropPath(drop_path) if drop_path > 0. else nn.Identity()
+ self.norm2 = norm_layer(dim)
+ mlp_hidden_dim = int(dim * mlp_ratio)
+ self.mlp = Mlp(in_features=dim, hidden_features=mlp_hidden_dim, act_layer=act_layer, drop=drop)
+
+ if self.shift_size > 0:
+ attn_mask = self.calculate_mask(self.input_resolution)
+ else:
+ attn_mask = None
+
+ self.register_buffer("attn_mask", attn_mask)
+
+ def calculate_mask(self, x_size):
+ # calculate attention mask for SW-MSA
+ H, W = x_size
+ img_mask = torch.zeros((1, H, W, 1)) # 1 H W 1
+ h_slices = (slice(0, -self.window_size),
+ slice(-self.window_size, -self.shift_size),
+ slice(-self.shift_size, None))
+ w_slices = (slice(0, -self.window_size),
+ slice(-self.window_size, -self.shift_size),
+ slice(-self.shift_size, None))
+ cnt = 0
+ for h in h_slices:
+ for w in w_slices:
+ img_mask[:, h, w, :] = cnt
+ cnt += 1
+
+ mask_windows = window_partition(img_mask, self.window_size) # nW, window_size, window_size, 1
+ mask_windows = mask_windows.view(-1, self.window_size * self.window_size)
+ attn_mask = mask_windows.unsqueeze(1) - mask_windows.unsqueeze(2)
+ attn_mask = attn_mask.masked_fill(attn_mask != 0, float(-100.0)).masked_fill(attn_mask == 0, float(0.0))
+
+ return attn_mask
+
+ def forward(self, x, x_size):
+ H, W = x_size
+ B, L, C = x.shape
+ # assert L == H * W, "input feature has wrong size"
+
+ shortcut = x
+ x = self.norm1(x)
+ x = x.view(B, H, W, C)
+
+ # cyclic shift
+ if self.shift_size > 0:
+ shifted_x = torch.roll(x, shifts=(-self.shift_size, -self.shift_size), dims=(1, 2))
+ else:
+ shifted_x = x
+
+ # partition windows
+ x_windows = window_partition(shifted_x, self.window_size) # nW*B, window_size, window_size, C
+ x_windows = x_windows.view(-1, self.window_size * self.window_size, C) # nW*B, window_size*window_size, C
+
+ # W-MSA/SW-MSA (to be compatible for testing on images whose shapes are the multiple of window size
+ if self.input_resolution == x_size:
+ attn_windows = self.attn(x_windows, mask=self.attn_mask) # nW*B, window_size*window_size, C
+ else:
+ attn_windows = self.attn(x_windows, mask=self.calculate_mask(x_size).to(x.device))
+
+ # merge windows
+ attn_windows = attn_windows.view(-1, self.window_size, self.window_size, C)
+ shifted_x = window_reverse(attn_windows, self.window_size, H, W) # B H' W' C
+
+ # reverse cyclic shift
+ if self.shift_size > 0:
+ x = torch.roll(shifted_x, shifts=(self.shift_size, self.shift_size), dims=(1, 2))
+ else:
+ x = shifted_x
+ x = x.view(B, H * W, C)
+
+ # FFN
+ x = shortcut + self.drop_path(x)
+ x = x + self.drop_path(self.mlp(self.norm2(x)))
+
+ return x
+
+ def extra_repr(self) -> str:
+ return f"dim={self.dim}, input_resolution={self.input_resolution}, num_heads={self.num_heads}, " \
+ f"window_size={self.window_size}, shift_size={self.shift_size}, mlp_ratio={self.mlp_ratio}"
+
+ def flops(self):
+ flops = 0
+ H, W = self.input_resolution
+ # norm1
+ flops += self.dim * H * W
+ # W-MSA/SW-MSA
+ nW = H * W / self.window_size / self.window_size
+ flops += nW * self.attn.flops(self.window_size * self.window_size)
+ # mlp
+ flops += 2 * H * W * self.dim * self.dim * self.mlp_ratio
+ # norm2
+ flops += self.dim * H * W
+ return flops
+
+
+class PatchMerging(nn.Module):
+ r""" Patch Merging Layer.
+
+ Args:
+ input_resolution (tuple[int]): Resolution of input feature.
+ dim (int): Number of input channels.
+ norm_layer (nn.Module, optional): Normalization layer. Default: nn.LayerNorm
+ """
+
+ def __init__(self, input_resolution, dim, norm_layer=nn.LayerNorm):
+ super().__init__()
+ self.input_resolution = input_resolution
+ self.dim = dim
+ self.reduction = nn.Linear(4 * dim, 2 * dim, bias=False)
+ self.norm = norm_layer(4 * dim)
+
+ def forward(self, x):
+ """
+ x: B, H*W, C
+ """
+ H, W = self.input_resolution
+ B, L, C = x.shape
+ assert L == H * W, "input feature has wrong size"
+ assert H % 2 == 0 and W % 2 == 0, f"x size ({H}*{W}) are not even."
+
+ x = x.view(B, H, W, C)
+
+ x0 = x[:, 0::2, 0::2, :] # B H/2 W/2 C
+ x1 = x[:, 1::2, 0::2, :] # B H/2 W/2 C
+ x2 = x[:, 0::2, 1::2, :] # B H/2 W/2 C
+ x3 = x[:, 1::2, 1::2, :] # B H/2 W/2 C
+ x = torch.cat([x0, x1, x2, x3], -1) # B H/2 W/2 4*C
+ x = x.view(B, -1, 4 * C) # B H/2*W/2 4*C
+
+ x = self.norm(x)
+ x = self.reduction(x)
+
+ return x
+
+ def extra_repr(self) -> str:
+ return f"input_resolution={self.input_resolution}, dim={self.dim}"
+
+ def flops(self):
+ H, W = self.input_resolution
+ flops = H * W * self.dim
+ flops += (H // 2) * (W // 2) * 4 * self.dim * 2 * self.dim
+ return flops
+
+
+class BasicLayer(nn.Module):
+ """ A basic Swin Transformer layer for one stage.
+
+ Args:
+ dim (int): Number of input channels.
+ input_resolution (tuple[int]): Input resolution.
+ depth (int): Number of blocks.
+ num_heads (int): Number of attention heads.
+ window_size (int): Local window size.
+ mlp_ratio (float): Ratio of mlp hidden dim to embedding dim.
+ qkv_bias (bool, optional): If True, add a learnable bias to query, key, value. Default: True
+ qk_scale (float | None, optional): Override default qk scale of head_dim ** -0.5 if set.
+ drop (float, optional): Dropout rate. Default: 0.0
+ attn_drop (float, optional): Attention dropout rate. Default: 0.0
+ drop_path (float | tuple[float], optional): Stochastic depth rate. Default: 0.0
+ norm_layer (nn.Module, optional): Normalization layer. Default: nn.LayerNorm
+ downsample (nn.Module | None, optional): Downsample layer at the end of the layer. Default: None
+ use_checkpoint (bool): Whether to use checkpointing to save memory. Default: False.
+ """
+
+ def __init__(self, dim, input_resolution, depth, num_heads, window_size,
+ mlp_ratio=4., qkv_bias=True, qk_scale=None, drop=0., attn_drop=0.,
+ drop_path=0., norm_layer=nn.LayerNorm, downsample=None, use_checkpoint=False):
+
+ super().__init__()
+ self.dim = dim
+ self.input_resolution = input_resolution
+ self.depth = depth
+ self.use_checkpoint = use_checkpoint
+
+ # build blocks
+ self.blocks = nn.ModuleList([
+ SwinTransformerBlock(dim=dim, input_resolution=input_resolution,
+ num_heads=num_heads, window_size=window_size,
+ shift_size=0 if (i % 2 == 0) else window_size // 2,
+ mlp_ratio=mlp_ratio,
+ qkv_bias=qkv_bias, qk_scale=qk_scale,
+ drop=drop, attn_drop=attn_drop,
+ drop_path=drop_path[i] if isinstance(drop_path, list) else drop_path,
+ norm_layer=norm_layer)
+ for i in range(depth)])
+
+ # patch merging layer
+ if downsample is not None:
+ self.downsample = downsample(input_resolution, dim=dim, norm_layer=norm_layer)
+ else:
+ self.downsample = None
+
+ def forward(self, x, x_size):
+ for blk in self.blocks:
+ if self.use_checkpoint:
+ x = checkpoint.checkpoint(blk, x)
+ else:
+ x = blk(x, x_size)
+ if self.downsample is not None:
+ x = self.downsample(x)
+ return x
+
+ def extra_repr(self) -> str:
+ return f"dim={self.dim}, input_resolution={self.input_resolution}, depth={self.depth}"
+
+ def flops(self):
+ flops = 0
+ for blk in self.blocks:
+ flops += blk.flops()
+ if self.downsample is not None:
+ flops += self.downsample.flops()
+ return flops
+
+
+class RSTB(nn.Module):
+ """Residual Swin Transformer Block (RSTB).
+
+ Args:
+ dim (int): Number of input channels.
+ input_resolution (tuple[int]): Input resolution.
+ depth (int): Number of blocks.
+ num_heads (int): Number of attention heads.
+ window_size (int): Local window size.
+ mlp_ratio (float): Ratio of mlp hidden dim to embedding dim.
+ qkv_bias (bool, optional): If True, add a learnable bias to query, key, value. Default: True
+ qk_scale (float | None, optional): Override default qk scale of head_dim ** -0.5 if set.
+ drop (float, optional): Dropout rate. Default: 0.0
+ attn_drop (float, optional): Attention dropout rate. Default: 0.0
+ drop_path (float | tuple[float], optional): Stochastic depth rate. Default: 0.0
+ norm_layer (nn.Module, optional): Normalization layer. Default: nn.LayerNorm
+ downsample (nn.Module | None, optional): Downsample layer at the end of the layer. Default: None
+ use_checkpoint (bool): Whether to use checkpointing to save memory. Default: False.
+ img_size: Input image size.
+ patch_size: Patch size.
+ resi_connection: The convolutional block before residual connection.
+ """
+
+ def __init__(self, dim, input_resolution, depth, num_heads, window_size,
+ mlp_ratio=4., qkv_bias=True, qk_scale=None, drop=0., attn_drop=0.,
+ drop_path=0., norm_layer=nn.LayerNorm, downsample=None, use_checkpoint=False,
+ img_size=224, patch_size=4, resi_connection='1conv'):
+ super(RSTB, self).__init__()
+
+ self.dim = dim
+ self.input_resolution = input_resolution
+
+ self.residual_group = BasicLayer(dim=dim,
+ input_resolution=input_resolution,
+ depth=depth,
+ num_heads=num_heads,
+ window_size=window_size,
+ mlp_ratio=mlp_ratio,
+ qkv_bias=qkv_bias, qk_scale=qk_scale,
+ drop=drop, attn_drop=attn_drop,
+ drop_path=drop_path,
+ norm_layer=norm_layer,
+ downsample=downsample,
+ use_checkpoint=use_checkpoint)
+
+ if resi_connection == '1conv':
+ self.conv = nn.Conv2d(dim, dim, 3, 1, 1)
+ elif resi_connection == '3conv':
+ # to save parameters and memory
+ self.conv = nn.Sequential(nn.Conv2d(dim, dim // 4, 3, 1, 1), nn.LeakyReLU(negative_slope=0.2, inplace=True),
+ nn.Conv2d(dim // 4, dim // 4, 1, 1, 0),
+ nn.LeakyReLU(negative_slope=0.2, inplace=True),
+ nn.Conv2d(dim // 4, dim, 3, 1, 1))
+
+ self.patch_embed = PatchEmbed(
+ img_size=img_size, patch_size=patch_size, in_chans=0, embed_dim=dim,
+ norm_layer=None)
+
+ self.patch_unembed = PatchUnEmbed(
+ img_size=img_size, patch_size=patch_size, in_chans=0, embed_dim=dim,
+ norm_layer=None)
+
+ def forward(self, x, x_size):
+ return self.patch_embed(self.conv(self.patch_unembed(self.residual_group(x, x_size), x_size))) + x
+
+ def flops(self):
+ flops = 0
+ flops += self.residual_group.flops()
+ H, W = self.input_resolution
+ flops += H * W * self.dim * self.dim * 9
+ flops += self.patch_embed.flops()
+ flops += self.patch_unembed.flops()
+
+ return flops
+
+
+class PatchEmbed(nn.Module):
+ r""" Image to Patch Embedding
+
+ Args:
+ img_size (int): Image size. Default: 224.
+ patch_size (int): Patch token size. Default: 4.
+ in_chans (int): Number of input image channels. Default: 3.
+ embed_dim (int): Number of linear projection output channels. Default: 96.
+ norm_layer (nn.Module, optional): Normalization layer. Default: None
+ """
+
+ def __init__(self, img_size=224, patch_size=4, in_chans=3, embed_dim=96, norm_layer=None):
+ super().__init__()
+ img_size = to_2tuple(img_size)
+ patch_size = to_2tuple(patch_size)
+ patches_resolution = [img_size[0] // patch_size[0], img_size[1] // patch_size[1]]
+ self.img_size = img_size
+ self.patch_size = patch_size
+ self.patches_resolution = patches_resolution
+ self.num_patches = patches_resolution[0] * patches_resolution[1]
+
+ self.in_chans = in_chans
+ self.embed_dim = embed_dim
+
+ if norm_layer is not None:
+ self.norm = norm_layer(embed_dim)
+ else:
+ self.norm = None
+
+ def forward(self, x):
+ x = x.flatten(2).transpose(1, 2) # B Ph*Pw C
+ if self.norm is not None:
+ x = self.norm(x)
+ return x
+
+ def flops(self):
+ flops = 0
+ H, W = self.img_size
+ if self.norm is not None:
+ flops += H * W * self.embed_dim
+ return flops
+
+
+class PatchUnEmbed(nn.Module):
+ r""" Image to Patch Unembedding
+
+ Args:
+ img_size (int): Image size. Default: 224.
+ patch_size (int): Patch token size. Default: 4.
+ in_chans (int): Number of input image channels. Default: 3.
+ embed_dim (int): Number of linear projection output channels. Default: 96.
+ norm_layer (nn.Module, optional): Normalization layer. Default: None
+ """
+
+ def __init__(self, img_size=224, patch_size=4, in_chans=3, embed_dim=96, norm_layer=None):
+ super().__init__()
+ img_size = to_2tuple(img_size)
+ patch_size = to_2tuple(patch_size)
+ patches_resolution = [img_size[0] // patch_size[0], img_size[1] // patch_size[1]]
+ self.img_size = img_size
+ self.patch_size = patch_size
+ self.patches_resolution = patches_resolution
+ self.num_patches = patches_resolution[0] * patches_resolution[1]
+
+ self.in_chans = in_chans
+ self.embed_dim = embed_dim
+
+ def forward(self, x, x_size):
+ B, HW, C = x.shape
+ x = x.transpose(1, 2).view(B, self.embed_dim, x_size[0], x_size[1]) # B Ph*Pw C
+ return x
+
+ def flops(self):
+ flops = 0
+ return flops
+
+
+class Upsample(nn.Sequential):
+ """Upsample module.
+
+ Args:
+ scale (int): Scale factor. Supported scales: 2^n and 3.
+ num_feat (int): Channel number of intermediate features.
+ """
+
+ def __init__(self, scale, num_feat):
+ m = []
+ if (scale & (scale - 1)) == 0: # scale = 2^n
+ for _ in range(int(math.log(scale, 2))):
+ m.append(nn.Conv2d(num_feat, 4 * num_feat, 3, 1, 1))
+ m.append(nn.PixelShuffle(2))
+ elif scale == 3:
+ m.append(nn.Conv2d(num_feat, 9 * num_feat, 3, 1, 1))
+ m.append(nn.PixelShuffle(3))
+ else:
+ raise ValueError(f'scale {scale} is not supported. ' 'Supported scales: 2^n and 3.')
+ super(Upsample, self).__init__(*m)
+
+
+class UpsampleOneStep(nn.Sequential):
+ """UpsampleOneStep module (the difference with Upsample is that it always only has 1conv + 1pixelshuffle)
+ Used in lightweight SR to save parameters.
+
+ Args:
+ scale (int): Scale factor. Supported scales: 2^n and 3.
+ num_feat (int): Channel number of intermediate features.
+
+ """
+
+ def __init__(self, scale, num_feat, num_out_ch, input_resolution=None):
+ self.num_feat = num_feat
+ self.input_resolution = input_resolution
+ m = []
+ m.append(nn.Conv2d(num_feat, (scale ** 2) * num_out_ch, 3, 1, 1))
+ m.append(nn.PixelShuffle(scale))
+ super(UpsampleOneStep, self).__init__(*m)
+
+ def flops(self):
+ H, W = self.input_resolution
+ flops = H * W * self.num_feat * 3 * 9
+ return flops
+
+
+class SwinIR(nn.Module):
+ r""" SwinIR
+ A PyTorch impl of : `SwinIR: Image Restoration Using Swin Transformer`, based on Swin Transformer.
+
+ Args:
+ img_size (int | tuple(int)): Input image size. Default 64
+ patch_size (int | tuple(int)): Patch size. Default: 1
+ in_chans (int): Number of input image channels. Default: 3
+ embed_dim (int): Patch embedding dimension. Default: 96
+ depths (tuple(int)): Depth of each Swin Transformer layer.
+ num_heads (tuple(int)): Number of attention heads in different layers.
+ window_size (int): Window size. Default: 7
+ mlp_ratio (float): Ratio of mlp hidden dim to embedding dim. Default: 4
+ qkv_bias (bool): If True, add a learnable bias to query, key, value. Default: True
+ qk_scale (float): Override default qk scale of head_dim ** -0.5 if set. Default: None
+ drop_rate (float): Dropout rate. Default: 0
+ attn_drop_rate (float): Attention dropout rate. Default: 0
+ drop_path_rate (float): Stochastic depth rate. Default: 0.1
+ norm_layer (nn.Module): Normalization layer. Default: nn.LayerNorm.
+ ape (bool): If True, add absolute position embedding to the patch embedding. Default: False
+ patch_norm (bool): If True, add normalization after patch embedding. Default: True
+ use_checkpoint (bool): Whether to use checkpointing to save memory. Default: False
+ upscale: Upscale factor. 2/3/4/8 for image SR, 1 for denoising and compress artifact reduction
+ img_range: Image range. 1. or 255.
+ upsampler: The reconstruction reconstruction module. 'pixelshuffle'/'pixelshuffledirect'/'nearest+conv'/None
+ resi_connection: The convolutional block before residual connection. '1conv'/'3conv'
+ """
+
+ def __init__(self, img_size=64, patch_size=1, in_chans=3,
+ embed_dim=96, depths=[6, 6, 6, 6], num_heads=[6, 6, 6, 6],
+ window_size=7, mlp_ratio=4., qkv_bias=True, qk_scale=None,
+ drop_rate=0., attn_drop_rate=0., drop_path_rate=0.1,
+ norm_layer=nn.LayerNorm, ape=False, patch_norm=True,
+ use_checkpoint=False, upscale=2, img_range=1., upsampler='', resi_connection='1conv',
+ **kwargs):
+ super(SwinIR, self).__init__()
+ num_in_ch = in_chans
+ num_out_ch = in_chans
+ num_feat = 64
+ self.img_range = img_range
+ if in_chans == 3:
+ rgb_mean = (0.4488, 0.4371, 0.4040)
+ self.mean = torch.Tensor(rgb_mean).view(1, 3, 1, 1)
+ else:
+ self.mean = torch.zeros(1, 1, 1, 1)
+ self.upscale = upscale
+ self.upsampler = upsampler
+
+ #####################################################################################################
+ ################################### 1, shallow feature extraction ###################################
+ self.conv_first = nn.Conv2d(num_in_ch, embed_dim, 3, 1, 1)
+
+ #####################################################################################################
+ ################################### 2, deep feature extraction ######################################
+ self.num_layers = len(depths)
+ self.embed_dim = embed_dim
+ self.ape = ape
+ self.patch_norm = patch_norm
+ self.num_features = embed_dim
+ self.mlp_ratio = mlp_ratio
+
+ # split image into non-overlapping patches
+ self.patch_embed = PatchEmbed(
+ img_size=img_size, patch_size=patch_size, in_chans=embed_dim, embed_dim=embed_dim,
+ norm_layer=norm_layer if self.patch_norm else None)
+ num_patches = self.patch_embed.num_patches
+ patches_resolution = self.patch_embed.patches_resolution
+ self.patches_resolution = patches_resolution
+
+ # merge non-overlapping patches into image
+ self.patch_unembed = PatchUnEmbed(
+ img_size=img_size, patch_size=patch_size, in_chans=embed_dim, embed_dim=embed_dim,
+ norm_layer=norm_layer if self.patch_norm else None)
+
+ # absolute position embedding
+ if self.ape:
+ self.absolute_pos_embed = nn.Parameter(torch.zeros(1, num_patches, embed_dim))
+ trunc_normal_(self.absolute_pos_embed, std=.02)
+
+ self.pos_drop = nn.Dropout(p=drop_rate)
+
+ # stochastic depth
+ dpr = [x.item() for x in torch.linspace(0, drop_path_rate, sum(depths))] # stochastic depth decay rule
+
+ # build Residual Swin Transformer blocks (RSTB)
+ self.layers = nn.ModuleList()
+ for i_layer in range(self.num_layers):
+ layer = RSTB(dim=embed_dim,
+ input_resolution=(patches_resolution[0],
+ patches_resolution[1]),
+ depth=depths[i_layer],
+ num_heads=num_heads[i_layer],
+ window_size=window_size,
+ mlp_ratio=self.mlp_ratio,
+ qkv_bias=qkv_bias, qk_scale=qk_scale,
+ drop=drop_rate, attn_drop=attn_drop_rate,
+ drop_path=dpr[sum(depths[:i_layer]):sum(depths[:i_layer + 1])], # no impact on SR results
+ norm_layer=norm_layer,
+ downsample=None,
+ use_checkpoint=use_checkpoint,
+ img_size=img_size,
+ patch_size=patch_size,
+ resi_connection=resi_connection
+
+ )
+ self.layers.append(layer)
+ self.norm = norm_layer(self.num_features)
+
+ # build the last conv layer in deep feature extraction
+ if resi_connection == '1conv':
+ self.conv_after_body = nn.Conv2d(embed_dim, embed_dim, 3, 1, 1)
+ elif resi_connection == '3conv':
+ # to save parameters and memory
+ self.conv_after_body = nn.Sequential(nn.Conv2d(embed_dim, embed_dim // 4, 3, 1, 1),
+ nn.LeakyReLU(negative_slope=0.2, inplace=True),
+ nn.Conv2d(embed_dim // 4, embed_dim // 4, 1, 1, 0),
+ nn.LeakyReLU(negative_slope=0.2, inplace=True),
+ nn.Conv2d(embed_dim // 4, embed_dim, 3, 1, 1))
+
+ #####################################################################################################
+ ################################ 3, high quality image reconstruction ################################
+ if self.upsampler == 'pixelshuffle':
+ # for classical SR
+ self.conv_before_upsample = nn.Sequential(nn.Conv2d(embed_dim, num_feat, 3, 1, 1),
+ nn.LeakyReLU(inplace=True))
+ self.upsample = Upsample(upscale, num_feat)
+ self.conv_last = nn.Conv2d(num_feat, num_out_ch, 3, 1, 1)
+ elif self.upsampler == 'pixelshuffledirect':
+ # for lightweight SR (to save parameters)
+ self.upsample = UpsampleOneStep(upscale, embed_dim, num_out_ch,
+ (patches_resolution[0], patches_resolution[1]))
+ elif self.upsampler == 'nearest+conv':
+ # for real-world SR (less artifacts)
+ assert self.upscale == 4, 'only support x4 now.'
+ self.conv_before_upsample = nn.Sequential(nn.Conv2d(embed_dim, num_feat, 3, 1, 1),
+ nn.LeakyReLU(inplace=True))
+ self.conv_up1 = nn.Conv2d(num_feat, num_feat, 3, 1, 1)
+ self.conv_up2 = nn.Conv2d(num_feat, num_feat, 3, 1, 1)
+ self.conv_hr = nn.Conv2d(num_feat, num_feat, 3, 1, 1)
+ self.conv_last = nn.Conv2d(num_feat, num_out_ch, 3, 1, 1)
+ self.lrelu = nn.LeakyReLU(negative_slope=0.2, inplace=True)
+ else:
+ # for image denoising and JPEG compression artifact reduction
+ self.conv_last = nn.Conv2d(embed_dim, num_out_ch, 3, 1, 1)
+
+ self.apply(self._init_weights)
+
+ def _init_weights(self, m):
+ if isinstance(m, nn.Linear):
+ trunc_normal_(m.weight, std=.02)
+ if isinstance(m, nn.Linear) and m.bias is not None:
+ nn.init.constant_(m.bias, 0)
+ elif isinstance(m, nn.LayerNorm):
+ nn.init.constant_(m.bias, 0)
+ nn.init.constant_(m.weight, 1.0)
+
+ @torch.jit.ignore
+ def no_weight_decay(self):
+ return {'absolute_pos_embed'}
+
+ @torch.jit.ignore
+ def no_weight_decay_keywords(self):
+ return {'relative_position_bias_table'}
+
+ def forward_features(self, x):
+ x_size = (x.shape[2], x.shape[3])
+ x = self.patch_embed(x)
+ if self.ape:
+ x = x + self.absolute_pos_embed
+ x = self.pos_drop(x)
+
+ for layer in self.layers:
+ x = layer(x, x_size)
+
+ x = self.norm(x) # B L C
+ x = self.patch_unembed(x, x_size)
+
+ return x
+
+ def forward(self, x):
+ self.mean = self.mean.type_as(x)
+ x = (x - self.mean) * self.img_range
+
+ if self.upsampler == 'pixelshuffle':
+ # for classical SR
+ x = self.conv_first(x)
+ x = self.conv_after_body(self.forward_features(x)) + x
+ x = self.conv_before_upsample(x)
+ x = self.conv_last(self.upsample(x))
+ elif self.upsampler == 'pixelshuffledirect':
+ # for lightweight SR
+ x = self.conv_first(x)
+ x = self.conv_after_body(self.forward_features(x)) + x
+ x = self.upsample(x)
+ elif self.upsampler == 'nearest+conv':
+ # for real-world SR
+ x = self.conv_first(x)
+ x = self.conv_after_body(self.forward_features(x)) + x
+ x = self.conv_before_upsample(x)
+ x = self.lrelu(self.conv_up1(torch.nn.functional.interpolate(x, scale_factor=2, mode='nearest')))
+ x = self.lrelu(self.conv_up2(torch.nn.functional.interpolate(x, scale_factor=2, mode='nearest')))
+ x = self.conv_last(self.lrelu(self.conv_hr(x)))
+ else:
+ # for image denoising and JPEG compression artifact reduction
+ x_first = self.conv_first(x)
+ res = self.conv_after_body(self.forward_features(x_first)) + x_first
+ x = x + self.conv_last(res)
+
+ x = x / self.img_range + self.mean
+
+ return x
+
+ def flops(self):
+ flops = 0
+ H, W = self.patches_resolution
+ flops += H * W * 3 * self.embed_dim * 9
+ flops += self.patch_embed.flops()
+ for i, layer in enumerate(self.layers):
+ flops += layer.flops()
+ flops += H * W * 3 * self.embed_dim * self.embed_dim
+ flops += self.upsample.flops()
+ return flops
+
+
+if __name__ == '__main__':
+ upscale = 4
+ window_size = 8
+ height = (1024 // upscale // window_size + 1) * window_size
+ width = (720 // upscale // window_size + 1) * window_size
+ model = SwinIR(upscale=2, img_size=(height, width),
+ window_size=window_size, img_range=1., depths=[6, 6, 6, 6],
+ embed_dim=60, num_heads=[6, 6, 6, 6], mlp_ratio=2, upsampler='pixelshuffledirect')
+ print(model)
+ print(height, width, model.flops() / 1e9)
+
+ x = torch.randn((1, 3, height, width))
+ x = model(x)
+ print(x.shape)
diff --git a/testsets/McMaster/1.tif b/testsets/McMaster/1.tif
new file mode 100644
index 000000000..5bca1b4b1
Binary files /dev/null and b/testsets/McMaster/1.tif differ
diff --git a/testsets/McMaster/10.tif b/testsets/McMaster/10.tif
new file mode 100644
index 000000000..ff2ec209a
Binary files /dev/null and b/testsets/McMaster/10.tif differ
diff --git a/testsets/McMaster/11.tif b/testsets/McMaster/11.tif
new file mode 100644
index 000000000..1b9fdaf60
Binary files /dev/null and b/testsets/McMaster/11.tif differ
diff --git a/testsets/McMaster/12.tif b/testsets/McMaster/12.tif
new file mode 100644
index 000000000..0538086d2
Binary files /dev/null and b/testsets/McMaster/12.tif differ
diff --git a/testsets/McMaster/13.tif b/testsets/McMaster/13.tif
new file mode 100644
index 000000000..d0e71315f
Binary files /dev/null and b/testsets/McMaster/13.tif differ
diff --git a/testsets/McMaster/14.tif b/testsets/McMaster/14.tif
new file mode 100644
index 000000000..8b6373dfe
Binary files /dev/null and b/testsets/McMaster/14.tif differ
diff --git a/testsets/McMaster/15.tif b/testsets/McMaster/15.tif
new file mode 100644
index 000000000..a440fd59d
Binary files /dev/null and b/testsets/McMaster/15.tif differ
diff --git a/testsets/McMaster/16.tif b/testsets/McMaster/16.tif
new file mode 100644
index 000000000..0be20a110
Binary files /dev/null and b/testsets/McMaster/16.tif differ
diff --git a/testsets/McMaster/17.tif b/testsets/McMaster/17.tif
new file mode 100644
index 000000000..a511b63c6
Binary files /dev/null and b/testsets/McMaster/17.tif differ
diff --git a/testsets/McMaster/18.tif b/testsets/McMaster/18.tif
new file mode 100644
index 000000000..150dba194
Binary files /dev/null and b/testsets/McMaster/18.tif differ
diff --git a/testsets/McMaster/2.tif b/testsets/McMaster/2.tif
new file mode 100644
index 000000000..b3bcca636
Binary files /dev/null and b/testsets/McMaster/2.tif differ
diff --git a/testsets/McMaster/3.tif b/testsets/McMaster/3.tif
new file mode 100644
index 000000000..3bde17ccb
Binary files /dev/null and b/testsets/McMaster/3.tif differ
diff --git a/testsets/McMaster/4.tif b/testsets/McMaster/4.tif
new file mode 100644
index 000000000..ca4a94cdc
Binary files /dev/null and b/testsets/McMaster/4.tif differ
diff --git a/testsets/McMaster/5.tif b/testsets/McMaster/5.tif
new file mode 100644
index 000000000..da527c1d6
Binary files /dev/null and b/testsets/McMaster/5.tif differ
diff --git a/testsets/McMaster/6.tif b/testsets/McMaster/6.tif
new file mode 100644
index 000000000..ccc83682e
Binary files /dev/null and b/testsets/McMaster/6.tif differ
diff --git a/testsets/McMaster/7.tif b/testsets/McMaster/7.tif
new file mode 100644
index 000000000..a53de4c2d
Binary files /dev/null and b/testsets/McMaster/7.tif differ
diff --git a/testsets/McMaster/8.tif b/testsets/McMaster/8.tif
new file mode 100644
index 000000000..9265a9f3e
Binary files /dev/null and b/testsets/McMaster/8.tif differ
diff --git a/testsets/McMaster/9.tif b/testsets/McMaster/9.tif
new file mode 100644
index 000000000..42855b103
Binary files /dev/null and b/testsets/McMaster/9.tif differ
diff --git a/testsets/RealSRSet+5images/00003.png b/testsets/RealSRSet+5images/00003.png
new file mode 100644
index 000000000..00cad23ad
Binary files /dev/null and b/testsets/RealSRSet+5images/00003.png differ
diff --git a/testsets/RealSRSet+5images/0014.jpg b/testsets/RealSRSet+5images/0014.jpg
new file mode 100644
index 000000000..f59554fe3
Binary files /dev/null and b/testsets/RealSRSet+5images/0014.jpg differ
diff --git a/testsets/RealSRSet+5images/0030.jpg b/testsets/RealSRSet+5images/0030.jpg
new file mode 100644
index 000000000..61868926a
Binary files /dev/null and b/testsets/RealSRSet+5images/0030.jpg differ
diff --git a/testsets/RealSRSet+5images/ADE_val_00000114.jpg b/testsets/RealSRSet+5images/ADE_val_00000114.jpg
new file mode 100644
index 000000000..b4d9c9067
Binary files /dev/null and b/testsets/RealSRSet+5images/ADE_val_00000114.jpg differ
diff --git a/testsets/RealSRSet+5images/Lincoln.png b/testsets/RealSRSet+5images/Lincoln.png
new file mode 100644
index 000000000..de6cc4862
Binary files /dev/null and b/testsets/RealSRSet+5images/Lincoln.png differ
diff --git a/testsets/RealSRSet+5images/OST_009.png b/testsets/RealSRSet+5images/OST_009.png
new file mode 100644
index 000000000..10bbc831a
Binary files /dev/null and b/testsets/RealSRSet+5images/OST_009.png differ
diff --git a/testsets/RealSRSet+5images/building.png b/testsets/RealSRSet+5images/building.png
new file mode 100644
index 000000000..8033e8644
Binary files /dev/null and b/testsets/RealSRSet+5images/building.png differ
diff --git a/testsets/RealSRSet+5images/butterfly.png b/testsets/RealSRSet+5images/butterfly.png
new file mode 100644
index 000000000..dc486627a
Binary files /dev/null and b/testsets/RealSRSet+5images/butterfly.png differ
diff --git a/testsets/RealSRSet+5images/butterfly2.png b/testsets/RealSRSet+5images/butterfly2.png
new file mode 100644
index 000000000..f598ebd03
Binary files /dev/null and b/testsets/RealSRSet+5images/butterfly2.png differ
diff --git a/testsets/RealSRSet+5images/chip.png b/testsets/RealSRSet+5images/chip.png
new file mode 100644
index 000000000..f320bb7ac
Binary files /dev/null and b/testsets/RealSRSet+5images/chip.png differ
diff --git a/testsets/RealSRSet+5images/comic1.png b/testsets/RealSRSet+5images/comic1.png
new file mode 100644
index 000000000..d7481cccf
Binary files /dev/null and b/testsets/RealSRSet+5images/comic1.png differ
diff --git a/testsets/RealSRSet+5images/comic2.png b/testsets/RealSRSet+5images/comic2.png
new file mode 100644
index 000000000..d4357986d
Binary files /dev/null and b/testsets/RealSRSet+5images/comic2.png differ
diff --git a/testsets/RealSRSet+5images/comic3.png b/testsets/RealSRSet+5images/comic3.png
new file mode 100644
index 000000000..951c3d120
Binary files /dev/null and b/testsets/RealSRSet+5images/comic3.png differ
diff --git a/testsets/RealSRSet+5images/computer.png b/testsets/RealSRSet+5images/computer.png
new file mode 100644
index 000000000..d1a8097a1
Binary files /dev/null and b/testsets/RealSRSet+5images/computer.png differ
diff --git a/testsets/RealSRSet+5images/dog.png b/testsets/RealSRSet+5images/dog.png
new file mode 100644
index 000000000..1b5ae679e
Binary files /dev/null and b/testsets/RealSRSet+5images/dog.png differ
diff --git a/testsets/RealSRSet+5images/dped_crop00061.png b/testsets/RealSRSet+5images/dped_crop00061.png
new file mode 100644
index 000000000..028cd2fc8
Binary files /dev/null and b/testsets/RealSRSet+5images/dped_crop00061.png differ
diff --git a/testsets/RealSRSet+5images/foreman.png b/testsets/RealSRSet+5images/foreman.png
new file mode 100644
index 000000000..cf6a026c8
Binary files /dev/null and b/testsets/RealSRSet+5images/foreman.png differ
diff --git a/testsets/RealSRSet+5images/frog.png b/testsets/RealSRSet+5images/frog.png
new file mode 100644
index 000000000..35471d4cd
Binary files /dev/null and b/testsets/RealSRSet+5images/frog.png differ
diff --git a/testsets/RealSRSet+5images/oldphoto2.png b/testsets/RealSRSet+5images/oldphoto2.png
new file mode 100644
index 000000000..1669ded98
Binary files /dev/null and b/testsets/RealSRSet+5images/oldphoto2.png differ
diff --git a/testsets/RealSRSet+5images/oldphoto3.png b/testsets/RealSRSet+5images/oldphoto3.png
new file mode 100644
index 000000000..900ae605d
Binary files /dev/null and b/testsets/RealSRSet+5images/oldphoto3.png differ
diff --git a/testsets/RealSRSet+5images/oldphoto6.png b/testsets/RealSRSet+5images/oldphoto6.png
new file mode 100644
index 000000000..8d0b76d9f
Binary files /dev/null and b/testsets/RealSRSet+5images/oldphoto6.png differ
diff --git a/testsets/RealSRSet+5images/painting.png b/testsets/RealSRSet+5images/painting.png
new file mode 100644
index 000000000..12f3d5040
Binary files /dev/null and b/testsets/RealSRSet+5images/painting.png differ
diff --git a/testsets/RealSRSet+5images/pattern.png b/testsets/RealSRSet+5images/pattern.png
new file mode 100644
index 000000000..76a7348bc
Binary files /dev/null and b/testsets/RealSRSet+5images/pattern.png differ
diff --git a/testsets/RealSRSet+5images/ppt3.png b/testsets/RealSRSet+5images/ppt3.png
new file mode 100644
index 000000000..60ba3256a
Binary files /dev/null and b/testsets/RealSRSet+5images/ppt3.png differ
diff --git a/testsets/RealSRSet+5images/tiger.png b/testsets/RealSRSet+5images/tiger.png
new file mode 100644
index 000000000..eba29bf3a
Binary files /dev/null and b/testsets/RealSRSet+5images/tiger.png differ
diff --git a/testsets/Set12/01.png b/testsets/Set12/01.png
new file mode 100644
index 000000000..795f98729
Binary files /dev/null and b/testsets/Set12/01.png differ
diff --git a/testsets/Set12/02.png b/testsets/Set12/02.png
new file mode 100644
index 000000000..ecc66936e
Binary files /dev/null and b/testsets/Set12/02.png differ
diff --git a/testsets/Set12/03.png b/testsets/Set12/03.png
new file mode 100644
index 000000000..bc20886a2
Binary files /dev/null and b/testsets/Set12/03.png differ
diff --git a/testsets/Set12/04.png b/testsets/Set12/04.png
new file mode 100644
index 000000000..2a80fdb3d
Binary files /dev/null and b/testsets/Set12/04.png differ
diff --git a/testsets/Set12/05.png b/testsets/Set12/05.png
new file mode 100644
index 000000000..ece8444da
Binary files /dev/null and b/testsets/Set12/05.png differ
diff --git a/testsets/Set12/06.png b/testsets/Set12/06.png
new file mode 100644
index 000000000..72a8a6be1
Binary files /dev/null and b/testsets/Set12/06.png differ
diff --git a/testsets/Set12/07.png b/testsets/Set12/07.png
new file mode 100644
index 000000000..ea9f17d90
Binary files /dev/null and b/testsets/Set12/07.png differ
diff --git a/testsets/Set12/08.png b/testsets/Set12/08.png
new file mode 100644
index 000000000..df777bd83
Binary files /dev/null and b/testsets/Set12/08.png differ
diff --git a/testsets/Set12/09.png b/testsets/Set12/09.png
new file mode 100644
index 000000000..3b6a71bc2
Binary files /dev/null and b/testsets/Set12/09.png differ
diff --git a/testsets/Set12/10.png b/testsets/Set12/10.png
new file mode 100644
index 000000000..931cfa1f6
Binary files /dev/null and b/testsets/Set12/10.png differ
diff --git a/testsets/Set12/11.png b/testsets/Set12/11.png
new file mode 100644
index 000000000..d65b82cee
Binary files /dev/null and b/testsets/Set12/11.png differ
diff --git a/testsets/Set12/12.png b/testsets/Set12/12.png
new file mode 100644
index 000000000..b9019ad32
Binary files /dev/null and b/testsets/Set12/12.png differ
diff --git a/testsets/Set5/HR/baby.png b/testsets/Set5/HR/baby.png
new file mode 100644
index 000000000..d5b91f6b0
Binary files /dev/null and b/testsets/Set5/HR/baby.png differ
diff --git a/testsets/Set5/HR/bird.png b/testsets/Set5/HR/bird.png
new file mode 100644
index 000000000..13bf5e1bc
Binary files /dev/null and b/testsets/Set5/HR/bird.png differ
diff --git a/testsets/Set5/HR/butterfly.png b/testsets/Set5/HR/butterfly.png
new file mode 100644
index 000000000..f6acb9a57
Binary files /dev/null and b/testsets/Set5/HR/butterfly.png differ
diff --git a/testsets/Set5/HR/head.png b/testsets/Set5/HR/head.png
new file mode 100644
index 000000000..c14b1fdbc
Binary files /dev/null and b/testsets/Set5/HR/head.png differ
diff --git a/testsets/Set5/HR/woman.png b/testsets/Set5/HR/woman.png
new file mode 100644
index 000000000..e6d553825
Binary files /dev/null and b/testsets/Set5/HR/woman.png differ
diff --git a/testsets/Set5/LR_bicubic/X2/babyx2.png b/testsets/Set5/LR_bicubic/X2/babyx2.png
new file mode 100644
index 000000000..0650d46ff
Binary files /dev/null and b/testsets/Set5/LR_bicubic/X2/babyx2.png differ
diff --git a/testsets/Set5/LR_bicubic/X2/birdx2.png b/testsets/Set5/LR_bicubic/X2/birdx2.png
new file mode 100644
index 000000000..cd5603d65
Binary files /dev/null and b/testsets/Set5/LR_bicubic/X2/birdx2.png differ
diff --git a/testsets/Set5/LR_bicubic/X2/butterflyx2.png b/testsets/Set5/LR_bicubic/X2/butterflyx2.png
new file mode 100644
index 000000000..a9557514b
Binary files /dev/null and b/testsets/Set5/LR_bicubic/X2/butterflyx2.png differ
diff --git a/testsets/Set5/LR_bicubic/X2/headx2.png b/testsets/Set5/LR_bicubic/X2/headx2.png
new file mode 100644
index 000000000..26a13e279
Binary files /dev/null and b/testsets/Set5/LR_bicubic/X2/headx2.png differ
diff --git a/testsets/Set5/LR_bicubic/X2/womanx2.png b/testsets/Set5/LR_bicubic/X2/womanx2.png
new file mode 100644
index 000000000..be24dc1e4
Binary files /dev/null and b/testsets/Set5/LR_bicubic/X2/womanx2.png differ
diff --git a/testsets/Set5/LR_bicubic/X3/babyx3.png b/testsets/Set5/LR_bicubic/X3/babyx3.png
new file mode 100644
index 000000000..e6bf244e4
Binary files /dev/null and b/testsets/Set5/LR_bicubic/X3/babyx3.png differ
diff --git a/testsets/Set5/LR_bicubic/X3/birdx3.png b/testsets/Set5/LR_bicubic/X3/birdx3.png
new file mode 100644
index 000000000..d449ade59
Binary files /dev/null and b/testsets/Set5/LR_bicubic/X3/birdx3.png differ
diff --git a/testsets/Set5/LR_bicubic/X3/butterflyx3.png b/testsets/Set5/LR_bicubic/X3/butterflyx3.png
new file mode 100644
index 000000000..ecbfda94e
Binary files /dev/null and b/testsets/Set5/LR_bicubic/X3/butterflyx3.png differ
diff --git a/testsets/Set5/LR_bicubic/X3/headx3.png b/testsets/Set5/LR_bicubic/X3/headx3.png
new file mode 100644
index 000000000..8538d141f
Binary files /dev/null and b/testsets/Set5/LR_bicubic/X3/headx3.png differ
diff --git a/testsets/Set5/LR_bicubic/X3/womanx3.png b/testsets/Set5/LR_bicubic/X3/womanx3.png
new file mode 100644
index 000000000..f4312bc85
Binary files /dev/null and b/testsets/Set5/LR_bicubic/X3/womanx3.png differ
diff --git a/testsets/Set5/LR_bicubic/X4/babyx4.png b/testsets/Set5/LR_bicubic/X4/babyx4.png
new file mode 100644
index 000000000..1ecbb31fe
Binary files /dev/null and b/testsets/Set5/LR_bicubic/X4/babyx4.png differ
diff --git a/testsets/Set5/LR_bicubic/X4/birdx4.png b/testsets/Set5/LR_bicubic/X4/birdx4.png
new file mode 100644
index 000000000..f3037c864
Binary files /dev/null and b/testsets/Set5/LR_bicubic/X4/birdx4.png differ
diff --git a/testsets/Set5/LR_bicubic/X4/butterflyx4.png b/testsets/Set5/LR_bicubic/X4/butterflyx4.png
new file mode 100644
index 000000000..b55686b45
Binary files /dev/null and b/testsets/Set5/LR_bicubic/X4/butterflyx4.png differ
diff --git a/testsets/Set5/LR_bicubic/X4/headx4.png b/testsets/Set5/LR_bicubic/X4/headx4.png
new file mode 100644
index 000000000..8926d01aa
Binary files /dev/null and b/testsets/Set5/LR_bicubic/X4/headx4.png differ
diff --git a/testsets/Set5/LR_bicubic/X4/womanx4.png b/testsets/Set5/LR_bicubic/X4/womanx4.png
new file mode 100644
index 000000000..ca7de118f
Binary files /dev/null and b/testsets/Set5/LR_bicubic/X4/womanx4.png differ
diff --git a/testsets/Set5/LR_bicubic/X8/babyx8.png b/testsets/Set5/LR_bicubic/X8/babyx8.png
new file mode 100644
index 000000000..bb7230c60
Binary files /dev/null and b/testsets/Set5/LR_bicubic/X8/babyx8.png differ
diff --git a/testsets/Set5/LR_bicubic/X8/birdx8.png b/testsets/Set5/LR_bicubic/X8/birdx8.png
new file mode 100644
index 000000000..08212f8fb
Binary files /dev/null and b/testsets/Set5/LR_bicubic/X8/birdx8.png differ
diff --git a/testsets/Set5/LR_bicubic/X8/butterflyx8.png b/testsets/Set5/LR_bicubic/X8/butterflyx8.png
new file mode 100644
index 000000000..51aac3832
Binary files /dev/null and b/testsets/Set5/LR_bicubic/X8/butterflyx8.png differ
diff --git a/testsets/Set5/LR_bicubic/X8/headx8.png b/testsets/Set5/LR_bicubic/X8/headx8.png
new file mode 100644
index 000000000..f7aa8b165
Binary files /dev/null and b/testsets/Set5/LR_bicubic/X8/headx8.png differ
diff --git a/testsets/Set5/LR_bicubic/X8/womanx8.png b/testsets/Set5/LR_bicubic/X8/womanx8.png
new file mode 100644
index 000000000..f4647baaf
Binary files /dev/null and b/testsets/Set5/LR_bicubic/X8/womanx8.png differ
diff --git a/testsets/classic5/baboon.bmp b/testsets/classic5/baboon.bmp
new file mode 100644
index 000000000..597bffef5
Binary files /dev/null and b/testsets/classic5/baboon.bmp differ
diff --git a/testsets/classic5/barbara.bmp b/testsets/classic5/barbara.bmp
new file mode 100644
index 000000000..f1872c857
Binary files /dev/null and b/testsets/classic5/barbara.bmp differ
diff --git a/testsets/classic5/boats.bmp b/testsets/classic5/boats.bmp
new file mode 100644
index 000000000..84f43e824
Binary files /dev/null and b/testsets/classic5/boats.bmp differ
diff --git a/testsets/classic5/lena.bmp b/testsets/classic5/lena.bmp
new file mode 100644
index 000000000..89496feff
Binary files /dev/null and b/testsets/classic5/lena.bmp differ
diff --git a/testsets/classic5/peppers.bmp b/testsets/classic5/peppers.bmp
new file mode 100644
index 000000000..dd05a1b06
Binary files /dev/null and b/testsets/classic5/peppers.bmp differ
diff --git a/utils/util_calculate_psnr_ssim.py b/utils/util_calculate_psnr_ssim.py
new file mode 100644
index 000000000..1a8fb2716
--- /dev/null
+++ b/utils/util_calculate_psnr_ssim.py
@@ -0,0 +1,346 @@
+import cv2
+import numpy as np
+import torch
+
+
+def calculate_psnr(img1, img2, crop_border, input_order='HWC', test_y_channel=False):
+ """Calculate PSNR (Peak Signal-to-Noise Ratio).
+
+ Ref: https://en.wikipedia.org/wiki/Peak_signal-to-noise_ratio
+
+ Args:
+ img1 (ndarray): Images with range [0, 255].
+ img2 (ndarray): Images with range [0, 255].
+ crop_border (int): Cropped pixels in each edge of an image. These
+ pixels are not involved in the PSNR calculation.
+ input_order (str): Whether the input order is 'HWC' or 'CHW'.
+ Default: 'HWC'.
+ test_y_channel (bool): Test on Y channel of YCbCr. Default: False.
+
+ Returns:
+ float: psnr result.
+ """
+
+ assert img1.shape == img2.shape, (f'Image shapes are differnet: {img1.shape}, {img2.shape}.')
+ if input_order not in ['HWC', 'CHW']:
+ raise ValueError(f'Wrong input_order {input_order}. Supported input_orders are ' '"HWC" and "CHW"')
+ img1 = reorder_image(img1, input_order=input_order)
+ img2 = reorder_image(img2, input_order=input_order)
+ img1 = img1.astype(np.float64)
+ img2 = img2.astype(np.float64)
+
+ if crop_border != 0:
+ img1 = img1[crop_border:-crop_border, crop_border:-crop_border, ...]
+ img2 = img2[crop_border:-crop_border, crop_border:-crop_border, ...]
+
+ if test_y_channel:
+ img1 = to_y_channel(img1)
+ img2 = to_y_channel(img2)
+
+ mse = np.mean((img1 - img2) ** 2)
+ if mse == 0:
+ return float('inf')
+ return 20. * np.log10(255. / np.sqrt(mse))
+
+
+def _ssim(img1, img2):
+ """Calculate SSIM (structural similarity) for one channel images.
+
+ It is called by func:`calculate_ssim`.
+
+ Args:
+ img1 (ndarray): Images with range [0, 255] with order 'HWC'.
+ img2 (ndarray): Images with range [0, 255] with order 'HWC'.
+
+ Returns:
+ float: ssim result.
+ """
+
+ C1 = (0.01 * 255) ** 2
+ C2 = (0.03 * 255) ** 2
+
+ img1 = img1.astype(np.float64)
+ img2 = img2.astype(np.float64)
+ kernel = cv2.getGaussianKernel(11, 1.5)
+ window = np.outer(kernel, kernel.transpose())
+
+ mu1 = cv2.filter2D(img1, -1, window)[5:-5, 5:-5]
+ mu2 = cv2.filter2D(img2, -1, window)[5:-5, 5:-5]
+ mu1_sq = mu1 ** 2
+ mu2_sq = mu2 ** 2
+ mu1_mu2 = mu1 * mu2
+ sigma1_sq = cv2.filter2D(img1 ** 2, -1, window)[5:-5, 5:-5] - mu1_sq
+ sigma2_sq = cv2.filter2D(img2 ** 2, -1, window)[5:-5, 5:-5] - mu2_sq
+ sigma12 = cv2.filter2D(img1 * img2, -1, window)[5:-5, 5:-5] - mu1_mu2
+
+ ssim_map = ((2 * mu1_mu2 + C1) * (2 * sigma12 + C2)) / ((mu1_sq + mu2_sq + C1) * (sigma1_sq + sigma2_sq + C2))
+ return ssim_map.mean()
+
+
+def calculate_ssim(img1, img2, crop_border, input_order='HWC', test_y_channel=False):
+ """Calculate SSIM (structural similarity).
+
+ Ref:
+ Image quality assessment: From error visibility to structural similarity
+
+ The results are the same as that of the official released MATLAB code in
+ https://ece.uwaterloo.ca/~z70wang/research/ssim/.
+
+ For three-channel images, SSIM is calculated for each channel and then
+ averaged.
+
+ Args:
+ img1 (ndarray): Images with range [0, 255].
+ img2 (ndarray): Images with range [0, 255].
+ crop_border (int): Cropped pixels in each edge of an image. These
+ pixels are not involved in the SSIM calculation.
+ input_order (str): Whether the input order is 'HWC' or 'CHW'.
+ Default: 'HWC'.
+ test_y_channel (bool): Test on Y channel of YCbCr. Default: False.
+
+ Returns:
+ float: ssim result.
+ """
+
+ assert img1.shape == img2.shape, (f'Image shapes are differnet: {img1.shape}, {img2.shape}.')
+ if input_order not in ['HWC', 'CHW']:
+ raise ValueError(f'Wrong input_order {input_order}. Supported input_orders are ' '"HWC" and "CHW"')
+ img1 = reorder_image(img1, input_order=input_order)
+ img2 = reorder_image(img2, input_order=input_order)
+ img1 = img1.astype(np.float64)
+ img2 = img2.astype(np.float64)
+
+ if crop_border != 0:
+ img1 = img1[crop_border:-crop_border, crop_border:-crop_border, ...]
+ img2 = img2[crop_border:-crop_border, crop_border:-crop_border, ...]
+
+ if test_y_channel:
+ img1 = to_y_channel(img1)
+ img2 = to_y_channel(img2)
+
+ ssims = []
+ for i in range(img1.shape[2]):
+ ssims.append(_ssim(img1[..., i], img2[..., i]))
+ return np.array(ssims).mean()
+
+
+def _blocking_effect_factor(im):
+ block_size = 8
+
+ block_horizontal_positions = torch.arange(7, im.shape[3] - 1, 8)
+ block_vertical_positions = torch.arange(7, im.shape[2] - 1, 8)
+
+ horizontal_block_difference = (
+ (im[:, :, :, block_horizontal_positions] - im[:, :, :, block_horizontal_positions + 1]) ** 2).sum(
+ 3).sum(2).sum(1)
+ vertical_block_difference = (
+ (im[:, :, block_vertical_positions, :] - im[:, :, block_vertical_positions + 1, :]) ** 2).sum(3).sum(
+ 2).sum(1)
+
+ nonblock_horizontal_positions = np.setdiff1d(torch.arange(0, im.shape[3] - 1), block_horizontal_positions)
+ nonblock_vertical_positions = np.setdiff1d(torch.arange(0, im.shape[2] - 1), block_vertical_positions)
+
+ horizontal_nonblock_difference = (
+ (im[:, :, :, nonblock_horizontal_positions] - im[:, :, :, nonblock_horizontal_positions + 1]) ** 2).sum(
+ 3).sum(2).sum(1)
+ vertical_nonblock_difference = (
+ (im[:, :, nonblock_vertical_positions, :] - im[:, :, nonblock_vertical_positions + 1, :]) ** 2).sum(
+ 3).sum(2).sum(1)
+
+ n_boundary_horiz = im.shape[2] * (im.shape[3] // block_size - 1)
+ n_boundary_vert = im.shape[3] * (im.shape[2] // block_size - 1)
+ boundary_difference = (horizontal_block_difference + vertical_block_difference) / (
+ n_boundary_horiz + n_boundary_vert)
+
+ n_nonboundary_horiz = im.shape[2] * (im.shape[3] - 1) - n_boundary_horiz
+ n_nonboundary_vert = im.shape[3] * (im.shape[2] - 1) - n_boundary_vert
+ nonboundary_difference = (horizontal_nonblock_difference + vertical_nonblock_difference) / (
+ n_nonboundary_horiz + n_nonboundary_vert)
+
+ scaler = np.log2(block_size) / np.log2(min([im.shape[2], im.shape[3]]))
+ bef = scaler * (boundary_difference - nonboundary_difference)
+
+ bef[boundary_difference <= nonboundary_difference] = 0
+ return bef
+
+
+def calculate_psnrb(img1, img2, crop_border, input_order='HWC', test_y_channel=False):
+ """Calculate PSNR-B (Peak Signal-to-Noise Ratio).
+
+ Ref: Quality assessment of deblocked images, for JPEG image deblocking evaluation
+ # https://gitlab.com/Queuecumber/quantization-guided-ac/-/blob/master/metrics/psnrb.py
+
+ Args:
+ img1 (ndarray): Images with range [0, 255].
+ img2 (ndarray): Images with range [0, 255].
+ crop_border (int): Cropped pixels in each edge of an image. These
+ pixels are not involved in the PSNR calculation.
+ input_order (str): Whether the input order is 'HWC' or 'CHW'.
+ Default: 'HWC'.
+ test_y_channel (bool): Test on Y channel of YCbCr. Default: False.
+
+ Returns:
+ float: psnr result.
+ """
+
+ assert img1.shape == img2.shape, (f'Image shapes are differnet: {img1.shape}, {img2.shape}.')
+ if input_order not in ['HWC', 'CHW']:
+ raise ValueError(f'Wrong input_order {input_order}. Supported input_orders are ' '"HWC" and "CHW"')
+ img1 = reorder_image(img1, input_order=input_order)
+ img2 = reorder_image(img2, input_order=input_order)
+ img1 = img1.astype(np.float64)
+ img2 = img2.astype(np.float64)
+
+ if crop_border != 0:
+ img1 = img1[crop_border:-crop_border, crop_border:-crop_border, ...]
+ img2 = img2[crop_border:-crop_border, crop_border:-crop_border, ...]
+
+ if test_y_channel:
+ img1 = to_y_channel(img1)
+ img2 = to_y_channel(img2)
+
+ # follow https://gitlab.com/Queuecumber/quantization-guided-ac/-/blob/master/metrics/psnrb.py
+ img1 = torch.from_numpy(img1).permute(2, 0, 1).unsqueeze(0) / 255.
+ img2 = torch.from_numpy(img2).permute(2, 0, 1).unsqueeze(0) / 255.
+
+ total = 0
+ for c in range(img1.shape[1]):
+ mse = torch.nn.functional.mse_loss(img1[:, c:c + 1, :, :], img2[:, c:c + 1, :, :], reduction='none')
+ bef = _blocking_effect_factor(img1[:, c:c + 1, :, :])
+
+ mse = mse.view(mse.shape[0], -1).mean(1)
+ total += 10 * torch.log10(1 / (mse + bef))
+
+ return float(total) / img1.shape[1]
+
+
+def reorder_image(img, input_order='HWC'):
+ """Reorder images to 'HWC' order.
+
+ If the input_order is (h, w), return (h, w, 1);
+ If the input_order is (c, h, w), return (h, w, c);
+ If the input_order is (h, w, c), return as it is.
+
+ Args:
+ img (ndarray): Input image.
+ input_order (str): Whether the input order is 'HWC' or 'CHW'.
+ If the input image shape is (h, w), input_order will not have
+ effects. Default: 'HWC'.
+
+ Returns:
+ ndarray: reordered image.
+ """
+
+ if input_order not in ['HWC', 'CHW']:
+ raise ValueError(f'Wrong input_order {input_order}. Supported input_orders are ' "'HWC' and 'CHW'")
+ if len(img.shape) == 2:
+ img = img[..., None]
+ if input_order == 'CHW':
+ img = img.transpose(1, 2, 0)
+ return img
+
+
+def to_y_channel(img):
+ """Change to Y channel of YCbCr.
+
+ Args:
+ img (ndarray): Images with range [0, 255].
+
+ Returns:
+ (ndarray): Images with range [0, 255] (float type) without round.
+ """
+ img = img.astype(np.float32) / 255.
+ if img.ndim == 3 and img.shape[2] == 3:
+ img = bgr2ycbcr(img, y_only=True)
+ img = img[..., None]
+ return img * 255.
+
+
+def _convert_input_type_range(img):
+ """Convert the type and range of the input image.
+
+ It converts the input image to np.float32 type and range of [0, 1].
+ It is mainly used for pre-processing the input image in colorspace
+ convertion functions such as rgb2ycbcr and ycbcr2rgb.
+
+ Args:
+ img (ndarray): The input image. It accepts:
+ 1. np.uint8 type with range [0, 255];
+ 2. np.float32 type with range [0, 1].
+
+ Returns:
+ (ndarray): The converted image with type of np.float32 and range of
+ [0, 1].
+ """
+ img_type = img.dtype
+ img = img.astype(np.float32)
+ if img_type == np.float32:
+ pass
+ elif img_type == np.uint8:
+ img /= 255.
+ else:
+ raise TypeError('The img type should be np.float32 or np.uint8, ' f'but got {img_type}')
+ return img
+
+
+def _convert_output_type_range(img, dst_type):
+ """Convert the type and range of the image according to dst_type.
+
+ It converts the image to desired type and range. If `dst_type` is np.uint8,
+ images will be converted to np.uint8 type with range [0, 255]. If
+ `dst_type` is np.float32, it converts the image to np.float32 type with
+ range [0, 1].
+ It is mainly used for post-processing images in colorspace convertion
+ functions such as rgb2ycbcr and ycbcr2rgb.
+
+ Args:
+ img (ndarray): The image to be converted with np.float32 type and
+ range [0, 255].
+ dst_type (np.uint8 | np.float32): If dst_type is np.uint8, it
+ converts the image to np.uint8 type with range [0, 255]. If
+ dst_type is np.float32, it converts the image to np.float32 type
+ with range [0, 1].
+
+ Returns:
+ (ndarray): The converted image with desired type and range.
+ """
+ if dst_type not in (np.uint8, np.float32):
+ raise TypeError('The dst_type should be np.float32 or np.uint8, ' f'but got {dst_type}')
+ if dst_type == np.uint8:
+ img = img.round()
+ else:
+ img /= 255.
+ return img.astype(dst_type)
+
+
+def bgr2ycbcr(img, y_only=False):
+ """Convert a BGR image to YCbCr image.
+
+ The bgr version of rgb2ycbcr.
+ It implements the ITU-R BT.601 conversion for standard-definition
+ television. See more details in
+ https://en.wikipedia.org/wiki/YCbCr#ITU-R_BT.601_conversion.
+
+ It differs from a similar function in cv2.cvtColor: `BGR <-> YCrCb`.
+ In OpenCV, it implements a JPEG conversion. See more details in
+ https://en.wikipedia.org/wiki/YCbCr#JPEG_conversion.
+
+ Args:
+ img (ndarray): The input image. It accepts:
+ 1. np.uint8 type with range [0, 255];
+ 2. np.float32 type with range [0, 1].
+ y_only (bool): Whether to only return Y channel. Default: False.
+
+ Returns:
+ ndarray: The converted YCbCr image. The output image has the same type
+ and range as input image.
+ """
+ img_type = img.dtype
+ img = _convert_input_type_range(img)
+ if y_only:
+ out_img = np.dot(img, [24.966, 128.553, 65.481]) + 16.0
+ else:
+ out_img = np.matmul(
+ img, [[24.966, 112.0, -18.214], [128.553, -74.203, -93.786], [65.481, -37.797, 112.0]]) + [16, 128, 128]
+ out_img = _convert_output_type_range(out_img, img_type)
+ return out_img