├── LICENSE ├── README.md ├── figs ├── 00003.png ├── 00003_BSRGAN.png ├── 00080.png ├── 00080_BSRGAN.png ├── 00081.png ├── 00081_BSRGAN.png ├── comic_03.png ├── comic_03_BSRGAN.png ├── comparison.png ├── degradationmodel.png ├── v1.png ├── v2.png └── v3.png ├── main_download_pretrained_models.py ├── main_test_bsrgan.py ├── model_zoo └── README.md ├── models └── network_rrdbnet.py ├── testsets ├── BSRGAN │ ├── Lincoln_BSRGAN.png │ ├── building_BSRGAN.png │ ├── butterfly2_BSRGAN.png │ ├── butterfly_BSRGAN.png │ ├── chip_BSRGAN.png │ ├── comic1_BSRGAN.png │ ├── comic2_BSRGAN.png │ ├── comic3_BSRGAN.png │ ├── computer_BSRGAN.png │ ├── dog_BSRGAN.png │ ├── dped_crop00061_BSRGAN.png │ ├── foreman_BSRGAN.png │ ├── frog_BSRGAN.png │ ├── oldphoto2_BSRGAN.png │ ├── oldphoto3_BSRGAN.png │ ├── oldphoto6_BSRGAN.png │ ├── painting_BSRGAN.png │ ├── pattern_BSRGAN.png │ ├── ppt3_BSRGAN.png │ └── tiger_BSRGAN.png ├── ESRGAN │ ├── Lincoln_ESRGAN.png │ ├── building_ESRGAN.png │ ├── butterfly2_ESRGAN.png │ ├── butterfly_ESRGAN.png │ ├── chip_ESRGAN.png │ ├── comic1_ESRGAN.png │ ├── comic2_ESRGAN.png │ ├── comic3_ESRGAN.png │ ├── computer_ESRGAN.png │ ├── dog_ESRGAN.png │ ├── dped_crop00061_ESRGAN.png │ ├── foreman_ESRGAN.png │ ├── frog_ESRGAN.png │ ├── oldphoto2_ESRGAN.png │ ├── oldphoto3_ESRGAN.png │ ├── oldphoto6_ESRGAN.png │ ├── painting_ESRGAN.png │ ├── pattern_ESRGAN.png │ ├── ppt3_ESRGAN.png │ └── tiger_ESRGAN.png ├── README.md ├── RealSRSet │ ├── Lincoln.png │ ├── building.png │ ├── butterfly.png │ ├── butterfly2.png │ ├── chip.png │ ├── comic1.png │ ├── comic2.png │ ├── comic3.png │ ├── computer.png │ ├── dog.png │ ├── dped_crop00061.png │ ├── foreman.png │ ├── frog.png │ ├── oldphoto2.png │ ├── oldphoto3.png │ ├── oldphoto6.png │ ├── painting.png │ ├── pattern.png │ ├── ppt3.png │ └── tiger.png └── RealSR_JPEG │ ├── Lincoln_RealSR_JPEG.png │ ├── building_RealSR_JPEG.png │ ├── butterfly2_RealSR_JPEG.png │ ├── butterfly_RealSR_JPEG.png │ ├── chip_RealSR_JPEG.png │ ├── comic1_RealSR_JPEG.png │ ├── comic2_RealSR_JPEG.png │ ├── comic3_RealSR_JPEG.png │ ├── computer_RealSR_JPEG.png │ ├── dog_RealSR_JPEG.png │ ├── dped_crop00061_RealSR_JPEG.png │ ├── foreman_RealSR_JPEG.png │ ├── frog_RealSR_JPEG.png │ ├── oldphoto2_RealSR_JPEG.png │ ├── oldphoto3_RealSR_JPEG.png │ ├── oldphoto6_RealSR_JPEG.png │ ├── painting_RealSR_JPEG.png │ ├── pattern_RealSR_JPEG.png │ ├── ppt3_RealSR_JPEG.png │ └── tiger_RealSR_JPEG.png └── utils ├── README.md ├── test.png ├── utils_blindsr.py ├── utils_googledownload.py ├── utils_image.py ├── utils_logger.py └── utils_model.py /LICENSE: -------------------------------------------------------------------------------- 1 | Apache License 2 | Version 2.0, January 2004 3 | http://www.apache.org/licenses/ 4 | 5 | TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION 6 | 7 | 1. Definitions. 8 | 9 | "License" shall mean the terms and conditions for use, reproduction, 10 | and distribution as defined by Sections 1 through 9 of this document. 11 | 12 | "Licensor" shall mean the copyright owner or entity authorized by 13 | the copyright owner that is granting the License. 14 | 15 | "Legal Entity" shall mean the union of the acting entity and all 16 | other entities that control, are controlled by, or are under common 17 | control with that entity. For the purposes of this definition, 18 | "control" means (i) the power, direct or indirect, to cause the 19 | direction or management of such entity, whether by contract or 20 | otherwise, or (ii) ownership of fifty percent (50%) or more of the 21 | outstanding shares, or (iii) beneficial ownership of such entity. 22 | 23 | "You" (or "Your") shall mean an individual or Legal Entity 24 | exercising permissions granted by this License. 25 | 26 | "Source" form shall mean the preferred form for making modifications, 27 | including but not limited to software source code, documentation 28 | source, and configuration files. 29 | 30 | "Object" form shall mean any form resulting from mechanical 31 | transformation or translation of a Source form, including but 32 | not limited to compiled object code, generated documentation, 33 | and conversions to other media types. 34 | 35 | "Work" shall mean the work of authorship, whether in Source or 36 | Object form, made available under the License, as indicated by a 37 | copyright notice that is included in or attached to the work 38 | (an example is provided in the Appendix below). 39 | 40 | "Derivative Works" shall mean any work, whether in Source or Object 41 | form, that is based on (or derived from) the Work and for which the 42 | editorial revisions, annotations, elaborations, or other modifications 43 | represent, as a whole, an original work of authorship. For the purposes 44 | of this License, Derivative Works shall not include works that remain 45 | separable from, or merely link (or bind by name) to the interfaces of, 46 | the Work and Derivative Works thereof. 47 | 48 | "Contribution" shall mean any work of authorship, including 49 | the original version of the Work and any modifications or additions 50 | to that Work or Derivative Works thereof, that is intentionally 51 | submitted to Licensor for inclusion in the Work by the copyright owner 52 | or by an individual or Legal Entity authorized to submit on behalf of 53 | the copyright owner. For the purposes of this definition, "submitted" 54 | means any form of electronic, verbal, or written communication sent 55 | to the Licensor or its representatives, including but not limited to 56 | communication on electronic mailing lists, source code control systems, 57 | and issue tracking systems that are managed by, or on behalf of, the 58 | Licensor for the purpose of discussing and improving the Work, but 59 | excluding communication that is conspicuously marked or otherwise 60 | designated in writing by the copyright owner as "Not a Contribution." 61 | 62 | "Contributor" shall mean Licensor and any individual or Legal Entity 63 | on behalf of whom a Contribution has been received by Licensor and 64 | subsequently incorporated within the Work. 65 | 66 | 2. Grant of Copyright License. Subject to the terms and conditions of 67 | this License, each Contributor hereby grants to You a perpetual, 68 | worldwide, non-exclusive, no-charge, royalty-free, irrevocable 69 | copyright license to reproduce, prepare Derivative Works of, 70 | publicly display, publicly perform, sublicense, and distribute the 71 | Work and such Derivative Works in Source or Object form. 72 | 73 | 3. Grant of Patent License. Subject to the terms and conditions of 74 | this License, each Contributor hereby grants to You a perpetual, 75 | worldwide, non-exclusive, no-charge, royalty-free, irrevocable 76 | (except as stated in this section) patent license to make, have made, 77 | use, offer to sell, sell, import, and otherwise transfer the Work, 78 | where such license applies only to those patent claims licensable 79 | by such Contributor that are necessarily infringed by their 80 | Contribution(s) alone or by combination of their Contribution(s) 81 | with the Work to which such Contribution(s) was submitted. If You 82 | institute patent litigation against any entity (including a 83 | cross-claim or counterclaim in a lawsuit) alleging that the Work 84 | or a Contribution incorporated within the Work constitutes direct 85 | or contributory patent infringement, then any patent licenses 86 | granted to You under this License for that Work shall terminate 87 | as of the date such litigation is filed. 88 | 89 | 4. Redistribution. You may reproduce and distribute copies of the 90 | Work or Derivative Works thereof in any medium, with or without 91 | modifications, and in Source or Object form, provided that You 92 | meet the following conditions: 93 | 94 | (a) You must give any other recipients of the Work or 95 | Derivative Works a copy of this License; and 96 | 97 | (b) You must cause any modified files to carry prominent notices 98 | stating that You changed the files; and 99 | 100 | (c) You must retain, in the Source form of any Derivative Works 101 | that You distribute, all copyright, patent, trademark, and 102 | attribution notices from the Source form of the Work, 103 | excluding those notices that do not pertain to any part of 104 | the Derivative Works; and 105 | 106 | (d) If the Work includes a "NOTICE" text file as part of its 107 | distribution, then any Derivative Works that You distribute must 108 | include a readable copy of the attribution notices contained 109 | within such NOTICE file, excluding those notices that do not 110 | pertain to any part of the Derivative Works, in at least one 111 | of the following places: within a NOTICE text file distributed 112 | as part of the Derivative Works; within the Source form or 113 | documentation, if provided along with the Derivative Works; or, 114 | within a display generated by the Derivative Works, if and 115 | wherever such third-party notices normally appear. The contents 116 | of the NOTICE file are for informational purposes only and 117 | do not modify the License. You may add Your own attribution 118 | notices within Derivative Works that You distribute, alongside 119 | or as an addendum to the NOTICE text from the Work, provided 120 | that such additional attribution notices cannot be construed 121 | as modifying the License. 122 | 123 | You may add Your own copyright statement to Your modifications and 124 | may provide additional or different license terms and conditions 125 | for use, reproduction, or distribution of Your modifications, or 126 | for any such Derivative Works as a whole, provided Your use, 127 | reproduction, and distribution of the Work otherwise complies with 128 | the conditions stated in this License. 129 | 130 | 5. Submission of Contributions. Unless You explicitly state otherwise, 131 | any Contribution intentionally submitted for inclusion in the Work 132 | by You to the Licensor shall be under the terms and conditions of 133 | this License, without any additional terms or conditions. 134 | Notwithstanding the above, nothing herein shall supersede or modify 135 | the terms of any separate license agreement you may have executed 136 | with Licensor regarding such Contributions. 137 | 138 | 6. Trademarks. This License does not grant permission to use the trade 139 | names, trademarks, service marks, or product names of the Licensor, 140 | except as required for reasonable and customary use in describing the 141 | origin of the Work and reproducing the content of the NOTICE file. 142 | 143 | 7. Disclaimer of Warranty. Unless required by applicable law or 144 | agreed to in writing, Licensor provides the Work (and each 145 | Contributor provides its Contributions) on an "AS IS" BASIS, 146 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or 147 | implied, including, without limitation, any warranties or conditions 148 | of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A 149 | PARTICULAR PURPOSE. You are solely responsible for determining the 150 | appropriateness of using or redistributing the Work and assume any 151 | risks associated with Your exercise of permissions under this License. 152 | 153 | 8. Limitation of Liability. In no event and under no legal theory, 154 | whether in tort (including negligence), contract, or otherwise, 155 | unless required by applicable law (such as deliberate and grossly 156 | negligent acts) or agreed to in writing, shall any Contributor be 157 | liable to You for damages, including any direct, indirect, special, 158 | incidental, or consequential damages of any character arising as a 159 | result of this License or out of the use or inability to use the 160 | Work (including but not limited to damages for loss of goodwill, 161 | work stoppage, computer failure or malfunction, or any and all 162 | other commercial damages or losses), even if such Contributor 163 | has been advised of the possibility of such damages. 164 | 165 | 9. Accepting Warranty or Additional Liability. While redistributing 166 | the Work or Derivative Works thereof, You may choose to offer, 167 | and charge a fee for, acceptance of support, warranty, indemnity, 168 | or other liability obligations and/or rights consistent with this 169 | License. However, in accepting such obligations, You may act only 170 | on Your own behalf and on Your sole responsibility, not on behalf 171 | of any other Contributor, and only if You agree to indemnify, 172 | defend, and hold each Contributor harmless for any liability 173 | incurred by, or claims asserted against, such Contributor by reason 174 | of your accepting any such warranty or additional liability. 175 | 176 | END OF TERMS AND CONDITIONS 177 | 178 | APPENDIX: How to apply the Apache License to your work. 179 | 180 | To apply the Apache License to your work, attach the following 181 | boilerplate notice, with the fields enclosed by brackets "[]" 182 | replaced with your own identifying information. (Don't include 183 | the brackets!) The text should be enclosed in the appropriate 184 | comment syntax for the file format. We also recommend that a 185 | file or class name and description of purpose be included on the 186 | same "printed page" as the copyright notice for easier 187 | identification within third-party archives. 188 | 189 | Copyright 2022 Kai Zhang (cskaizhang@gmail.com, https://cszn.github.io/). All rights reserved. 190 | 191 | Licensed under the Apache License, Version 2.0 (the "License"); 192 | you may not use this file except in compliance with the License. 193 | You may obtain a copy of the License at 194 | 195 | http://www.apache.org/licenses/LICENSE-2.0 196 | 197 | Unless required by applicable law or agreed to in writing, software 198 | distributed under the License is distributed on an "AS IS" BASIS, 199 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 200 | See the License for the specific language governing permissions and 201 | limitations under the License. 202 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | # [Designing a Practical Degradation Model for Deep Blind Image Super-Resolution](https://arxiv.org/pdf/2103.14006.pdf) 2 | 3 | ![visitors](https://visitor-badge.glitch.me/badge?page_id=cszn/BSRGAN) 4 | 5 | [Kai Zhang](https://cszn.github.io/), Jingyun Liang, [Luc Van Gool](https://vision.ee.ethz.ch/people-details.OTAyMzM=.TGlzdC8zMjQ4LC0xOTcxNDY1MTc4.html), [Radu Timofte](http://people.ee.ethz.ch/~timofter/) 6 | _[Computer Vision Lab](https://vision.ee.ethz.ch/the-institute.html), ETH Zurich, Switzerland_ 7 | 8 | [[Paper](https://arxiv.org/abs/2103.14006)] [[Code](https://github.com/cszn/BSRGAN/blob/main/main_test_bsrgan.py)] [[Training Code](https://github.com/cszn/KAIR)] 9 | 10 | _**Our new work for real image denoising ---> [https://github.com/cszn/SCUNet](https://github.com/cszn/SCUNet)**_ 11 | 12 | _**Our work is the beginning rather than the end of real image super-resolution.**_ 13 | 14 | _______ 15 | - **_News (2021-08-31)_**: We upload the training code. 16 | - **_News (2021-08-24)_**: We upload the BSRGAN degradation model. 17 | ```python 18 | from utils import utils_blindsr as blindsr 19 | img_lq, img_hq = blindsr.degradation_bsrgan(img, sf=4, lq_patchsize=72) 20 | ``` 21 | - **_News (2021-07-23)_**: After rejection by CVPR 2021, our paper is accepted by ICCV 2021. For the sake of fairness, we will not update the trained models in our camera-ready version. However, we may update the trained models in github. 22 | - **_News (2021-05-18)_**: Add trained BSRGAN model for scale factor 2. 23 | - **_News (2021-04)_**: Our degradation model for face image enhancement: [https://github.com/vvictoryuki/BSRGAN_implementation](https://github.com/vvictoryuki/BSRGAN_implementation) 24 | 25 | 26 | Training 27 | ---------- 28 | 1. Download [KAIR](https://github.com/cszn/KAIR): `git clone https://github.com/cszn/KAIR.git` 29 | 2. Put your training high-quality images into `trainsets/trainH` or set `"dataroot_H": "trainsets/trainH"` 30 | 3. Train BSRNet 31 | 1. Modify [train_bsrgan_x4_psnr.json](https://github.com/cszn/KAIR/blob/master/options/train_bsrgan_x4_psnr.json) e.g., `"gpu_ids": [0]`, `"dataloader_batch_size": 4` 32 | 2. Training with `DataParallel` 33 | ```bash 34 | python main_train_psnr.py --opt options/train_bsrgan_x4_psnr.json 35 | ``` 36 | 2. Training with `DistributedDataParallel` - 4 GPUs 37 | ```bash 38 | python -m torch.distributed.launch --nproc_per_node=4 --master_port=1234 main_train_psnr.py --opt options/train_bsrgan_x4_psnr.json --dist True 39 | ``` 40 | 4. Train BSRGAN 41 | 1. Put BSRNet model (e.g., '400000_G.pth') into `superresolution/bsrgan_x4_gan/models` 42 | 2. Modify [train_bsrgan_x4_gan.json](https://github.com/cszn/KAIR/blob/master/options/train_bsrgan_x4_gan.json) e.g., `"gpu_ids": [0]`, `"dataloader_batch_size": 4` 43 | 3. Training with `DataParallel` 44 | ```bash 45 | python main_train_gan.py --opt options/train_bsrgan_x4_gan.json 46 | ``` 47 | 3. Training with `DistributedDataParallel` - 4 GPUs 48 | ```bash 49 | python -m torch.distributed.launch --nproc_per_node=4 --master_port=1234 main_train_gan.py --opt options/train_bsrgan_x4_gan.json --dist True 50 | ``` 51 | 5. Test BSRGAN model `'xxxxxx_E.pth'` by modified `main_test_bsrgan.py` 52 | 1. `'xxxxxx_E.pth'` is more stable than `'xxxxxx_G.pth'` 53 | 54 | 55 | _______ 56 | ✨ _**Some visual examples**_: [oldphoto2](https://imgsli.com/NDgzMjU); [butterfly](https://imgsli.com/NDgyNjY); [comic](https://imgsli.com/NDgyNzg); [oldphoto3](https://imgsli.com/NDgyNzk); [oldphoto6](https://imgsli.com/NDgyODA); [comic_01](https://imgsli.com/NDgzNTg); [comic_03](https://imgsli.com/NDgzNTk); [comic_04](https://imgsli.com/NDgzNTY) 57 | 58 | [](https://imgsli.com/NDgzMjU) [](https://imgsli.com/NDgyNzk) 59 | [](https://imgsli.com/NDgzNDk) 60 | ___________ 61 | 62 | * [Testing code](#testing-code) 63 | * [Main idea](#main-idea) 64 | * [Comparison](#comparison) 65 | * [More visual results on RealSRSet dataset](#more-visual-results-on-realsrset-dataset) 66 | * [Visual results on DPED dataset](#visual-results-on-dped-dataset) 67 | * [Citation](#citation) 68 | * [Acknowledgments](#acknowledgments) 69 | 70 | Testing code 71 | ---------- 72 | 73 | * [main_test_bsrgan.py](main_test_bsrgan.py) 74 | * [model_zoo](model_zoo) (_Download the following models from [Google drive](https://drive.google.com/drive/folders/13kfr3qny7S2xwG9h7v95F5mkWs0OmU0D?usp=sharing) or [腾讯微云](https://share.weiyun.com/5qO32s3)_). 75 | * Proposed: 76 | * BSRGAN.pth [[Google drive]](https://drive.google.com/drive/folders/13kfr3qny7S2xwG9h7v95F5mkWs0OmU0D?usp=sharing) [[腾讯微云]](https://share.weiyun.com/7GPI8p7x)🌱 77 | * BSRNet.pth [[Google drive]](https://drive.google.com/drive/folders/13kfr3qny7S2xwG9h7v95F5mkWs0OmU0D?usp=sharing) [[腾讯微云]](https://share.weiyun.com/VOFW5Ela)🌱 78 | * Compared methods: 79 | * RRDB.pth ---> [original link](https://github.com/xinntao/ESRGAN) 80 | * ESRGAN.pth ---> [original link](https://github.com/xinntao/ESRGAN) 81 | * FSSR_DPED.pth ---> [original link](https://github.com/ManuelFritsche/real-world-sr) 82 | * FSSR_DPED.pth ---> [original link](https://github.com/ManuelFritsche/real-world-sr) 83 | * RealSR_DPED.pth ---> [original link](https://github.com/jixiaozhong/RealSR) 84 | * RealSR_JPEG.pth ---> [original link](https://github.com/jixiaozhong/RealSR) 85 | 86 | 87 | Main idea 88 | ---------- 89 | 90 | 91 | 92 | __Design a new degradation model to synthesize LR images for training:__ 93 | 94 | * **_1) Make the blur, downsampling and noise more practical_** 95 | * **_Blur:_** _two convolutions with isotropic and anisotropic Gaussian kernels from both the HR space and LR space_ 96 | * **_Downsampling:_** _nearest, bilinear, bicubic, down-up-sampling_ 97 | * **_Noise:_** _Gaussian noise, JPEG compression noise, processed camera sensor noise_ 98 | * **_2) Degradation shuffle:_** _instead of using the commonly-used blur/downsampling/noise-addition pipeline, we perform randomly shuffled degradations to synthesize LR images_ 99 | 100 | __Some notes on the proposed degradation model:__ 101 | 102 | * *The degradation model is mainly designed to synthesize degraded LR images. Its most direct application is to train a deep blind super-resolver with paired LR/HR images. In particular, the degradation model can be performed on a large dataset of HR images to produce unlimited perfectly aligned training images, which typically do not suffer from the limited data issue of laboriously collected paired data and the misalignment issue of unpaired training data.* 103 | 104 | * *The degradation model tends to be unsuited to model a degraded LR image as it involves too many degradation parameters and also adopts a random shuffle strategy.* 105 | 106 | * *The degradation model can produce some degradation cases that rarely happen in real-world scenarios, while this can still be expected to improve the generalization ability of the trained deep blind super-resolver.* 107 | 108 | * *A DNN with large capacity has the ability to handle different degradations via a single model. This has been validated multiple times. For example, DnCNN is able 109 | to handle SISR with different scale factors, JPEG compression deblocking with different quality factors and denoising for a wide range of noise levels, while still having a performance comparable to VDSR for SISR. It is worth noting that even when the super-resolver reduces the performance for unrealistic bicubic downsampling, it is still a preferred choice for real SISR.* 110 | 111 | * *One can conveniently modify the degradation model by changing the degradation parameter settings and adding more reasonable degradation 112 | types to improve the practicability for a certain application.* 113 | 114 | 115 | 116 | 117 | Comparison 118 | ---------- 119 | 120 | 121 | 122 | 123 | *These no-reference IQA metrics, i.e., NIQE, NRQM and PI, do not always match perceptual visual quality [1] and the IQA metric should be updated with new SISR methods [2]. We further argue that the IQA metric for SISR should also be updated with new image degradation types, which we leave for future work.* 124 | 125 | ``` 126 | [1] "NTIRE 2020 challenge on real-world image super-resolution: Methods and results." CVPRW, 2020. 127 | [2] "PIPAL: a large-scale image quality assessment dataset for perceptual image restoration." ECCV, 2020. 128 | ``` 129 | 130 | 131 | 132 | More visual results on [RealSRSet](testsets/RealSRSet) dataset 133 | ---------- 134 | 135 | 136 | **Left**: [real images](https://github.com/cszn/BSRNet/tree/main/testsets/RealSRSet) **|** **Right**: [super-resolved images with scale factor 4](https://github.com/cszn/BSRNet/tree/main/testsets/BSRGAN) 137 | 138 | 139 | 140 | 141 | 142 | 143 | 144 | 145 | 146 | 147 | 148 | 149 | 150 | 151 | 152 | 153 | 154 | 155 | 156 | 157 | 158 | 159 | 160 | 161 | 162 | 163 | 164 | 165 | Visual results on DPED dataset 166 | ---------- 167 | 168 | 169 | 170 | 171 | 172 | 173 | 174 | *Without using any prior information of DPED dataset for training, our BSRGAN still performs well.* 175 | 176 | 177 | 178 | 179 | Citation 180 | ---------- 181 | ```BibTex 182 | @inproceedings{zhang2021designing, 183 | title={Designing a Practical Degradation Model for Deep Blind Image Super-Resolution}, 184 | author={Zhang, Kai and Liang, Jingyun and Van Gool, Luc and Timofte, Radu}, 185 | booktitle={IEEE International Conference on Computer Vision}, 186 | pages={4791--4800}, 187 | year={2021} 188 | } 189 | ``` 190 | 191 | 192 | Acknowledgments 193 | ---------- 194 | This work was partly supported by the ETH Zurich Fund (OK), a Huawei Technologies Oy (Finland) project, and an Amazon AWS grant. 195 | 196 | 197 | 198 | -------------------------------------------------------------------------------- /figs/00003.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/cszn/BSRGAN/5ce1a9c6ae292f30ccfce4b597ecb73c70401733/figs/00003.png -------------------------------------------------------------------------------- /figs/00003_BSRGAN.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/cszn/BSRGAN/5ce1a9c6ae292f30ccfce4b597ecb73c70401733/figs/00003_BSRGAN.png -------------------------------------------------------------------------------- /figs/00080.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/cszn/BSRGAN/5ce1a9c6ae292f30ccfce4b597ecb73c70401733/figs/00080.png -------------------------------------------------------------------------------- /figs/00080_BSRGAN.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/cszn/BSRGAN/5ce1a9c6ae292f30ccfce4b597ecb73c70401733/figs/00080_BSRGAN.png -------------------------------------------------------------------------------- /figs/00081.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/cszn/BSRGAN/5ce1a9c6ae292f30ccfce4b597ecb73c70401733/figs/00081.png -------------------------------------------------------------------------------- /figs/00081_BSRGAN.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/cszn/BSRGAN/5ce1a9c6ae292f30ccfce4b597ecb73c70401733/figs/00081_BSRGAN.png -------------------------------------------------------------------------------- /figs/comic_03.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/cszn/BSRGAN/5ce1a9c6ae292f30ccfce4b597ecb73c70401733/figs/comic_03.png -------------------------------------------------------------------------------- /figs/comic_03_BSRGAN.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/cszn/BSRGAN/5ce1a9c6ae292f30ccfce4b597ecb73c70401733/figs/comic_03_BSRGAN.png -------------------------------------------------------------------------------- /figs/comparison.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/cszn/BSRGAN/5ce1a9c6ae292f30ccfce4b597ecb73c70401733/figs/comparison.png -------------------------------------------------------------------------------- /figs/degradationmodel.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/cszn/BSRGAN/5ce1a9c6ae292f30ccfce4b597ecb73c70401733/figs/degradationmodel.png -------------------------------------------------------------------------------- /figs/v1.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/cszn/BSRGAN/5ce1a9c6ae292f30ccfce4b597ecb73c70401733/figs/v1.png -------------------------------------------------------------------------------- /figs/v2.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/cszn/BSRGAN/5ce1a9c6ae292f30ccfce4b597ecb73c70401733/figs/v2.png -------------------------------------------------------------------------------- /figs/v3.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/cszn/BSRGAN/5ce1a9c6ae292f30ccfce4b597ecb73c70401733/figs/v3.png -------------------------------------------------------------------------------- /main_download_pretrained_models.py: -------------------------------------------------------------------------------- 1 | import argparse 2 | import os 3 | import requests 4 | import re 5 | 6 | 7 | """ 8 | How to use: 9 | 10 | download BSRGAN models: 11 | python main_download_pretrained_models.py --models "BSRGAN" --model_dir "model_zoo" 12 | 13 | ------------------------------------------------------------------ 14 | 15 | download 'BSRGAN.pth' 16 | python main_download_pretrained_models.py --models "BSRGAN.pth" --model_dir "model_zoo" 17 | 18 | """ 19 | 20 | 21 | def download_pretrained_model(model_dir='model_zoo', model_name='dncnn3.pth'): 22 | if os.path.exists(os.path.join(model_dir, model_name)): 23 | print(f'already exists, skip downloading [{model_name}]') 24 | else: 25 | os.makedirs(model_dir, exist_ok=True) 26 | if 'SwinIR' in model_name: 27 | url = 'https://github.com/JingyunLiang/SwinIR/releases/download/v0.0/{}'.format(model_name) 28 | else: 29 | url = 'https://github.com/cszn/KAIR/releases/download/v1.0/{}'.format(model_name) 30 | r = requests.get(url, allow_redirects=True) 31 | print(f'downloading [{model_dir}/{model_name}] ...') 32 | open(os.path.join(model_dir, model_name), 'wb').write(r.content) 33 | print('done!') 34 | 35 | 36 | if __name__ == '__main__': 37 | parser = argparse.ArgumentParser() 38 | parser.add_argument('--models', 39 | type=lambda s: re.split(' |, ', s), 40 | default = "dncnn3.pth", 41 | help='comma or space delimited list of characters, e.g., "DnCNN", "DnCNN BSRGAN.pth", "dncnn_15.pth dncnn_50.pth"') 42 | parser.add_argument('--model_dir', type=str, default='model_zoo', help='path of model_zoo') 43 | args = parser.parse_args() 44 | 45 | print(f'trying to download {args.models}') 46 | 47 | method_model_zoo = {'DnCNN': ['dncnn_15.pth', 'dncnn_25.pth', 'dncnn_50.pth', 'dncnn3.pth', 'dncnn_color_blind.pth', 'dncnn_gray_blind.pth'], 48 | 'SRMD': ['srmdnf_x2.pth', 'srmdnf_x3.pth', 'srmdnf_x4.pth', 'srmd_x2.pth', 'srmd_x3.pth', 'srmd_x4.pth'], 49 | 'DPSR': ['dpsr_x2.pth', 'dpsr_x3.pth', 'dpsr_x4.pth', 'dpsr_x4_gan.pth'], 50 | 'FFDNet': ['ffdnet_color.pth', 'ffdnet_gray.pth', 'ffdnet_color_clip.pth', 'ffdnet_gray_clip.pth'], 51 | 'USRNet': ['usrgan.pth', 'usrgan_tiny.pth', 'usrnet.pth', 'usrnet_tiny.pth'], 52 | 'DPIR': ['drunet_gray.pth', 'drunet_color.pth', 'drunet_deblocking_color.pth', 'drunet_deblocking_grayscale.pth'], 53 | 'BSRGAN': ['BSRGAN.pth', 'BSRNet.pth', 'BSRGANx2.pth'], 54 | 'IRCNN': ['ircnn_color.pth', 'ircnn_gray.pth'], 55 | 'SwinIR': ['001_classicalSR_DF2K_s64w8_SwinIR-M_x2.pth', '001_classicalSR_DF2K_s64w8_SwinIR-M_x3.pth', 56 | '001_classicalSR_DF2K_s64w8_SwinIR-M_x4.pth', '001_classicalSR_DF2K_s64w8_SwinIR-M_x8.pth', 57 | '001_classicalSR_DIV2K_s48w8_SwinIR-M_x2.pth', '001_classicalSR_DIV2K_s48w8_SwinIR-M_x3.pth', 58 | '001_classicalSR_DIV2K_s48w8_SwinIR-M_x4.pth', '001_classicalSR_DIV2K_s48w8_SwinIR-M_x8.pth', 59 | '002_lightweightSR_DIV2K_s64w8_SwinIR-S_x2.pth', '002_lightweightSR_DIV2K_s64w8_SwinIR-S_x3.pth', 60 | '002_lightweightSR_DIV2K_s64w8_SwinIR-S_x4.pth', '003_realSR_BSRGAN_DFO_s64w8_SwinIR-M_x4_GAN.pth', 61 | '003_realSR_BSRGAN_DFO_s64w8_SwinIR-M_x4_PSNR.pth', '004_grayDN_DFWB_s128w8_SwinIR-M_noise15.pth', 62 | '004_grayDN_DFWB_s128w8_SwinIR-M_noise25.pth', '004_grayDN_DFWB_s128w8_SwinIR-M_noise50.pth', 63 | '005_colorDN_DFWB_s128w8_SwinIR-M_noise15.pth', '005_colorDN_DFWB_s128w8_SwinIR-M_noise25.pth', 64 | '005_colorDN_DFWB_s128w8_SwinIR-M_noise50.pth', '006_CAR_DFWB_s126w7_SwinIR-M_jpeg10.pth', 65 | '006_CAR_DFWB_s126w7_SwinIR-M_jpeg20.pth', '006_CAR_DFWB_s126w7_SwinIR-M_jpeg30.pth', 66 | '006_CAR_DFWB_s126w7_SwinIR-M_jpeg40.pth'], 67 | 'others': ['msrresnet_x4_psnr.pth', 'msrresnet_x4_gan.pth', 'imdn_x4.pth', 'RRDB.pth', 'ESRGAN.pth', 68 | 'FSSR_DPED.pth', 'FSSR_JPEG.pth', 'RealSR_DPED.pth', 'RealSR_JPEG.pth'] 69 | } 70 | 71 | method_zoo = list(method_model_zoo.keys()) 72 | model_zoo = [] 73 | for b in list(method_model_zoo.values()): 74 | model_zoo += b 75 | 76 | if 'all' in args.models: 77 | for method in method_zoo: 78 | for model_name in method_model_zoo[method]: 79 | download_pretrained_model(args.model_dir, model_name) 80 | else: 81 | for method_model in args.models: 82 | if method_model in method_zoo: # method, need for loop 83 | for model_name in method_model_zoo[method_model]: 84 | if 'SwinIR' in model_name: 85 | download_pretrained_model(os.path.join(args.model_dir, 'swinir'), model_name) 86 | else: 87 | download_pretrained_model(args.model_dir, model_name) 88 | elif method_model in model_zoo: # model, do not need for loop 89 | if 'SwinIR' in method_model: 90 | download_pretrained_model(os.path.join(args.model_dir, 'swinir'), method_model) 91 | else: 92 | download_pretrained_model(args.model_dir, method_model) 93 | else: 94 | print(f'Do not find {method_model} from the pre-trained model zoo!') 95 | 96 | 97 | 98 | 99 | 100 | 101 | 102 | 103 | 104 | -------------------------------------------------------------------------------- /main_test_bsrgan.py: -------------------------------------------------------------------------------- 1 | import os.path 2 | import logging 3 | import torch 4 | 5 | from utils import utils_logger 6 | from utils import utils_image as util 7 | # from utils import utils_model 8 | from models.network_rrdbnet import RRDBNet as net 9 | 10 | 11 | """ 12 | Spyder (Python 3.6-3.7) 13 | PyTorch 1.4.0-1.8.1 14 | Windows 10 or Linux 15 | Kai Zhang (cskaizhang@gmail.com) 16 | github: https://github.com/cszn/BSRGAN 17 | https://github.com/cszn/KAIR 18 | If you have any question, please feel free to contact with me. 19 | Kai Zhang (e-mail: cskaizhang@gmail.com) 20 | by Kai Zhang ( March/2020 --> March/2021 --> ) 21 | This work was previously submitted to CVPR2021. 22 | 23 | # -------------------------------------------- 24 | @inproceedings{zhang2021designing, 25 | title={Designing a Practical Degradation Model for Deep Blind Image Super-Resolution}, 26 | author={Zhang, Kai and Liang, Jingyun and Van Gool, Luc and Timofte, Radu}, 27 | booktitle={arxiv}, 28 | year={2021} 29 | } 30 | # -------------------------------------------- 31 | 32 | """ 33 | 34 | 35 | def main(): 36 | 37 | utils_logger.logger_info('blind_sr_log', log_path='blind_sr_log.log') 38 | logger = logging.getLogger('blind_sr_log') 39 | 40 | # print(torch.__version__) # pytorch version 41 | # print(torch.version.cuda) # cuda version 42 | # print(torch.backends.cudnn.version()) # cudnn version 43 | 44 | testsets = 'testsets' # fixed, set path of testsets 45 | testset_Ls = ['RealSRSet'] # ['RealSRSet','DPED'] 46 | 47 | model_names = ['RRDB','ESRGAN','FSSR_DPED','FSSR_JPEG','RealSR_DPED','RealSR_JPEG'] 48 | model_names = ['BSRGAN'] # 'BSRGANx2' for scale factor 2 49 | 50 | 51 | 52 | save_results = True 53 | sf = 4 54 | device = torch.device('cuda' if torch.cuda.is_available() else 'cpu') 55 | 56 | for model_name in model_names: 57 | if model_name in ['BSRGANx2']: 58 | sf = 2 59 | model_path = os.path.join('model_zoo', model_name+'.pth') # set model path 60 | logger.info('{:>16s} : {:s}'.format('Model Name', model_name)) 61 | 62 | # torch.cuda.set_device(0) # set GPU ID 63 | logger.info('{:>16s} : {:16s} : {:s}'.format('Input Path', L_path)) 92 | logger.info('{:>16s} : {:s}'.format('Output Path', E_path)) 93 | idx = 0 94 | 95 | for img in util.get_image_paths(L_path): 96 | 97 | # -------------------------------- 98 | # (1) img_L 99 | # -------------------------------- 100 | idx += 1 101 | img_name, ext = os.path.splitext(os.path.basename(img)) 102 | logger.info('{:->4d} --> {: x{: {: [original link](https://github.com/xinntao/ESRGAN) 9 | * ESRGAN.pth ---> [original link](https://github.com/xinntao/ESRGAN) 10 | * FSSR_DPED.pth ---> [original link](https://github.com/ManuelFritsche/real-world-sr) 11 | * FSSR_DPED.pth ---> [original link](https://github.com/ManuelFritsche/real-world-sr) 12 | * RealSR_DPED.pth ---> [original link](https://github.com/jixiaozhong/RealSR) 13 | * RealSR_JPEG.pth ---> [original link](https://github.com/jixiaozhong/RealSR) 14 | 15 | 16 | * Github download link: https://github.com/cszn/KAIR/releases/tag/v1.0 17 | * Google drive download link: [https://drive.google.com/drive/folders/13kfr3qny7S2xwG9h7v95F5mkWs0OmU0D?usp=sharing](https://drive.google.com/drive/folders/13kfr3qny7S2xwG9h7v95F5mkWs0OmU0D?usp=sharing) 18 | 19 | * 腾讯微云下载链接: [https://share.weiyun.com/5qO32s3](https://share.weiyun.com/5qO32s3) 20 | -------------------------------------------------------------------------------- /models/network_rrdbnet.py: -------------------------------------------------------------------------------- 1 | import functools 2 | import torch 3 | import torch.nn as nn 4 | import torch.nn.functional as F 5 | import torch.nn.init as init 6 | 7 | 8 | def initialize_weights(net_l, scale=1): 9 | if not isinstance(net_l, list): 10 | net_l = [net_l] 11 | for net in net_l: 12 | for m in net.modules(): 13 | if isinstance(m, nn.Conv2d): 14 | init.kaiming_normal_(m.weight, a=0, mode='fan_in') 15 | m.weight.data *= scale # for residual block 16 | if m.bias is not None: 17 | m.bias.data.zero_() 18 | elif isinstance(m, nn.Linear): 19 | init.kaiming_normal_(m.weight, a=0, mode='fan_in') 20 | m.weight.data *= scale 21 | if m.bias is not None: 22 | m.bias.data.zero_() 23 | elif isinstance(m, nn.BatchNorm2d): 24 | init.constant_(m.weight, 1) 25 | init.constant_(m.bias.data, 0.0) 26 | 27 | 28 | def make_layer(block, n_layers): 29 | layers = [] 30 | for _ in range(n_layers): 31 | layers.append(block()) 32 | return nn.Sequential(*layers) 33 | 34 | 35 | class ResidualDenseBlock_5C(nn.Module): 36 | def __init__(self, nf=64, gc=32, bias=True): 37 | super(ResidualDenseBlock_5C, self).__init__() 38 | # gc: growth channel, i.e. intermediate channels 39 | self.conv1 = nn.Conv2d(nf, gc, 3, 1, 1, bias=bias) 40 | self.conv2 = nn.Conv2d(nf + gc, gc, 3, 1, 1, bias=bias) 41 | self.conv3 = nn.Conv2d(nf + 2 * gc, gc, 3, 1, 1, bias=bias) 42 | self.conv4 = nn.Conv2d(nf + 3 * gc, gc, 3, 1, 1, bias=bias) 43 | self.conv5 = nn.Conv2d(nf + 4 * gc, nf, 3, 1, 1, bias=bias) 44 | self.lrelu = nn.LeakyReLU(negative_slope=0.2, inplace=True) 45 | 46 | # initialization 47 | initialize_weights([self.conv1, self.conv2, self.conv3, self.conv4, self.conv5], 0.1) 48 | 49 | def forward(self, x): 50 | x1 = self.lrelu(self.conv1(x)) 51 | x2 = self.lrelu(self.conv2(torch.cat((x, x1), 1))) 52 | x3 = self.lrelu(self.conv3(torch.cat((x, x1, x2), 1))) 53 | x4 = self.lrelu(self.conv4(torch.cat((x, x1, x2, x3), 1))) 54 | x5 = self.conv5(torch.cat((x, x1, x2, x3, x4), 1)) 55 | return x5 * 0.2 + x 56 | 57 | 58 | class RRDB(nn.Module): 59 | '''Residual in Residual Dense Block''' 60 | 61 | def __init__(self, nf, gc=32): 62 | super(RRDB, self).__init__() 63 | self.RDB1 = ResidualDenseBlock_5C(nf, gc) 64 | self.RDB2 = ResidualDenseBlock_5C(nf, gc) 65 | self.RDB3 = ResidualDenseBlock_5C(nf, gc) 66 | 67 | def forward(self, x): 68 | out = self.RDB1(x) 69 | out = self.RDB2(out) 70 | out = self.RDB3(out) 71 | return out * 0.2 + x 72 | 73 | 74 | class RRDBNet(nn.Module): 75 | def __init__(self, in_nc=3, out_nc=3, nf=64, nb=23, gc=32, sf=4): 76 | super(RRDBNet, self).__init__() 77 | RRDB_block_f = functools.partial(RRDB, nf=nf, gc=gc) 78 | self.sf = sf 79 | print([in_nc, out_nc, nf, nb, gc, sf]) 80 | 81 | self.conv_first = nn.Conv2d(in_nc, nf, 3, 1, 1, bias=True) 82 | self.RRDB_trunk = make_layer(RRDB_block_f, nb) 83 | self.trunk_conv = nn.Conv2d(nf, nf, 3, 1, 1, bias=True) 84 | #### upsampling 85 | self.upconv1 = nn.Conv2d(nf, nf, 3, 1, 1, bias=True) 86 | if self.sf==4: 87 | self.upconv2 = nn.Conv2d(nf, nf, 3, 1, 1, bias=True) 88 | self.HRconv = nn.Conv2d(nf, nf, 3, 1, 1, bias=True) 89 | self.conv_last = nn.Conv2d(nf, out_nc, 3, 1, 1, bias=True) 90 | 91 | self.lrelu = nn.LeakyReLU(negative_slope=0.2, inplace=True) 92 | 93 | def forward(self, x): 94 | fea = self.conv_first(x) 95 | trunk = self.trunk_conv(self.RRDB_trunk(fea)) 96 | fea = fea + trunk 97 | 98 | fea = self.lrelu(self.upconv1(F.interpolate(fea, scale_factor=2, mode='nearest'))) 99 | if self.sf==4: 100 | fea = self.lrelu(self.upconv2(F.interpolate(fea, scale_factor=2, mode='nearest'))) 101 | out = self.conv_last(self.lrelu(self.HRconv(fea))) 102 | 103 | return out 104 | -------------------------------------------------------------------------------- /testsets/BSRGAN/Lincoln_BSRGAN.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/cszn/BSRGAN/5ce1a9c6ae292f30ccfce4b597ecb73c70401733/testsets/BSRGAN/Lincoln_BSRGAN.png -------------------------------------------------------------------------------- /testsets/BSRGAN/building_BSRGAN.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/cszn/BSRGAN/5ce1a9c6ae292f30ccfce4b597ecb73c70401733/testsets/BSRGAN/building_BSRGAN.png -------------------------------------------------------------------------------- /testsets/BSRGAN/butterfly2_BSRGAN.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/cszn/BSRGAN/5ce1a9c6ae292f30ccfce4b597ecb73c70401733/testsets/BSRGAN/butterfly2_BSRGAN.png -------------------------------------------------------------------------------- /testsets/BSRGAN/butterfly_BSRGAN.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/cszn/BSRGAN/5ce1a9c6ae292f30ccfce4b597ecb73c70401733/testsets/BSRGAN/butterfly_BSRGAN.png -------------------------------------------------------------------------------- /testsets/BSRGAN/chip_BSRGAN.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/cszn/BSRGAN/5ce1a9c6ae292f30ccfce4b597ecb73c70401733/testsets/BSRGAN/chip_BSRGAN.png -------------------------------------------------------------------------------- /testsets/BSRGAN/comic1_BSRGAN.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/cszn/BSRGAN/5ce1a9c6ae292f30ccfce4b597ecb73c70401733/testsets/BSRGAN/comic1_BSRGAN.png -------------------------------------------------------------------------------- /testsets/BSRGAN/comic2_BSRGAN.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/cszn/BSRGAN/5ce1a9c6ae292f30ccfce4b597ecb73c70401733/testsets/BSRGAN/comic2_BSRGAN.png -------------------------------------------------------------------------------- /testsets/BSRGAN/comic3_BSRGAN.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/cszn/BSRGAN/5ce1a9c6ae292f30ccfce4b597ecb73c70401733/testsets/BSRGAN/comic3_BSRGAN.png -------------------------------------------------------------------------------- /testsets/BSRGAN/computer_BSRGAN.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/cszn/BSRGAN/5ce1a9c6ae292f30ccfce4b597ecb73c70401733/testsets/BSRGAN/computer_BSRGAN.png -------------------------------------------------------------------------------- /testsets/BSRGAN/dog_BSRGAN.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/cszn/BSRGAN/5ce1a9c6ae292f30ccfce4b597ecb73c70401733/testsets/BSRGAN/dog_BSRGAN.png -------------------------------------------------------------------------------- /testsets/BSRGAN/dped_crop00061_BSRGAN.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/cszn/BSRGAN/5ce1a9c6ae292f30ccfce4b597ecb73c70401733/testsets/BSRGAN/dped_crop00061_BSRGAN.png -------------------------------------------------------------------------------- /testsets/BSRGAN/foreman_BSRGAN.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/cszn/BSRGAN/5ce1a9c6ae292f30ccfce4b597ecb73c70401733/testsets/BSRGAN/foreman_BSRGAN.png -------------------------------------------------------------------------------- /testsets/BSRGAN/frog_BSRGAN.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/cszn/BSRGAN/5ce1a9c6ae292f30ccfce4b597ecb73c70401733/testsets/BSRGAN/frog_BSRGAN.png -------------------------------------------------------------------------------- /testsets/BSRGAN/oldphoto2_BSRGAN.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/cszn/BSRGAN/5ce1a9c6ae292f30ccfce4b597ecb73c70401733/testsets/BSRGAN/oldphoto2_BSRGAN.png -------------------------------------------------------------------------------- /testsets/BSRGAN/oldphoto3_BSRGAN.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/cszn/BSRGAN/5ce1a9c6ae292f30ccfce4b597ecb73c70401733/testsets/BSRGAN/oldphoto3_BSRGAN.png -------------------------------------------------------------------------------- /testsets/BSRGAN/oldphoto6_BSRGAN.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/cszn/BSRGAN/5ce1a9c6ae292f30ccfce4b597ecb73c70401733/testsets/BSRGAN/oldphoto6_BSRGAN.png -------------------------------------------------------------------------------- /testsets/BSRGAN/painting_BSRGAN.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/cszn/BSRGAN/5ce1a9c6ae292f30ccfce4b597ecb73c70401733/testsets/BSRGAN/painting_BSRGAN.png -------------------------------------------------------------------------------- /testsets/BSRGAN/pattern_BSRGAN.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/cszn/BSRGAN/5ce1a9c6ae292f30ccfce4b597ecb73c70401733/testsets/BSRGAN/pattern_BSRGAN.png -------------------------------------------------------------------------------- /testsets/BSRGAN/ppt3_BSRGAN.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/cszn/BSRGAN/5ce1a9c6ae292f30ccfce4b597ecb73c70401733/testsets/BSRGAN/ppt3_BSRGAN.png -------------------------------------------------------------------------------- /testsets/BSRGAN/tiger_BSRGAN.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/cszn/BSRGAN/5ce1a9c6ae292f30ccfce4b597ecb73c70401733/testsets/BSRGAN/tiger_BSRGAN.png -------------------------------------------------------------------------------- /testsets/ESRGAN/Lincoln_ESRGAN.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/cszn/BSRGAN/5ce1a9c6ae292f30ccfce4b597ecb73c70401733/testsets/ESRGAN/Lincoln_ESRGAN.png -------------------------------------------------------------------------------- /testsets/ESRGAN/building_ESRGAN.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/cszn/BSRGAN/5ce1a9c6ae292f30ccfce4b597ecb73c70401733/testsets/ESRGAN/building_ESRGAN.png -------------------------------------------------------------------------------- /testsets/ESRGAN/butterfly2_ESRGAN.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/cszn/BSRGAN/5ce1a9c6ae292f30ccfce4b597ecb73c70401733/testsets/ESRGAN/butterfly2_ESRGAN.png -------------------------------------------------------------------------------- /testsets/ESRGAN/butterfly_ESRGAN.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/cszn/BSRGAN/5ce1a9c6ae292f30ccfce4b597ecb73c70401733/testsets/ESRGAN/butterfly_ESRGAN.png -------------------------------------------------------------------------------- /testsets/ESRGAN/chip_ESRGAN.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/cszn/BSRGAN/5ce1a9c6ae292f30ccfce4b597ecb73c70401733/testsets/ESRGAN/chip_ESRGAN.png -------------------------------------------------------------------------------- /testsets/ESRGAN/comic1_ESRGAN.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/cszn/BSRGAN/5ce1a9c6ae292f30ccfce4b597ecb73c70401733/testsets/ESRGAN/comic1_ESRGAN.png -------------------------------------------------------------------------------- /testsets/ESRGAN/comic2_ESRGAN.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/cszn/BSRGAN/5ce1a9c6ae292f30ccfce4b597ecb73c70401733/testsets/ESRGAN/comic2_ESRGAN.png -------------------------------------------------------------------------------- /testsets/ESRGAN/comic3_ESRGAN.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/cszn/BSRGAN/5ce1a9c6ae292f30ccfce4b597ecb73c70401733/testsets/ESRGAN/comic3_ESRGAN.png -------------------------------------------------------------------------------- /testsets/ESRGAN/computer_ESRGAN.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/cszn/BSRGAN/5ce1a9c6ae292f30ccfce4b597ecb73c70401733/testsets/ESRGAN/computer_ESRGAN.png -------------------------------------------------------------------------------- /testsets/ESRGAN/dog_ESRGAN.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/cszn/BSRGAN/5ce1a9c6ae292f30ccfce4b597ecb73c70401733/testsets/ESRGAN/dog_ESRGAN.png -------------------------------------------------------------------------------- /testsets/ESRGAN/dped_crop00061_ESRGAN.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/cszn/BSRGAN/5ce1a9c6ae292f30ccfce4b597ecb73c70401733/testsets/ESRGAN/dped_crop00061_ESRGAN.png -------------------------------------------------------------------------------- /testsets/ESRGAN/foreman_ESRGAN.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/cszn/BSRGAN/5ce1a9c6ae292f30ccfce4b597ecb73c70401733/testsets/ESRGAN/foreman_ESRGAN.png -------------------------------------------------------------------------------- /testsets/ESRGAN/frog_ESRGAN.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/cszn/BSRGAN/5ce1a9c6ae292f30ccfce4b597ecb73c70401733/testsets/ESRGAN/frog_ESRGAN.png -------------------------------------------------------------------------------- /testsets/ESRGAN/oldphoto2_ESRGAN.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/cszn/BSRGAN/5ce1a9c6ae292f30ccfce4b597ecb73c70401733/testsets/ESRGAN/oldphoto2_ESRGAN.png -------------------------------------------------------------------------------- /testsets/ESRGAN/oldphoto3_ESRGAN.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/cszn/BSRGAN/5ce1a9c6ae292f30ccfce4b597ecb73c70401733/testsets/ESRGAN/oldphoto3_ESRGAN.png -------------------------------------------------------------------------------- /testsets/ESRGAN/oldphoto6_ESRGAN.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/cszn/BSRGAN/5ce1a9c6ae292f30ccfce4b597ecb73c70401733/testsets/ESRGAN/oldphoto6_ESRGAN.png -------------------------------------------------------------------------------- /testsets/ESRGAN/painting_ESRGAN.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/cszn/BSRGAN/5ce1a9c6ae292f30ccfce4b597ecb73c70401733/testsets/ESRGAN/painting_ESRGAN.png -------------------------------------------------------------------------------- /testsets/ESRGAN/pattern_ESRGAN.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/cszn/BSRGAN/5ce1a9c6ae292f30ccfce4b597ecb73c70401733/testsets/ESRGAN/pattern_ESRGAN.png -------------------------------------------------------------------------------- /testsets/ESRGAN/ppt3_ESRGAN.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/cszn/BSRGAN/5ce1a9c6ae292f30ccfce4b597ecb73c70401733/testsets/ESRGAN/ppt3_ESRGAN.png -------------------------------------------------------------------------------- /testsets/ESRGAN/tiger_ESRGAN.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/cszn/BSRGAN/5ce1a9c6ae292f30ccfce4b597ecb73c70401733/testsets/ESRGAN/tiger_ESRGAN.png -------------------------------------------------------------------------------- /testsets/README.md: -------------------------------------------------------------------------------- 1 | 2 | 3 | [RealSRSet](RealSRSet): 20 real low-resolution images 4 | 5 | RRDB/[ESRGAN](ESRGAN): https://github.com/xinntao/ESRGAN 6 | 7 | IKC: https://github.com/yuanjunchai/IKC 8 | 9 | FSSR_DPED/FSSR_JPEG: https://github.com/ManuelFritsche/real-world-sr 10 | 11 | RealSR_DPED/[RealSR_JPEG](RealSR_JPEG): https://github.com/jixiaozhong/RealSR 12 | 13 | BSRNet/[BSRGAN](BSRGAN): the trained models with the proposed degradation 14 | -------------------------------------------------------------------------------- /testsets/RealSRSet/Lincoln.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/cszn/BSRGAN/5ce1a9c6ae292f30ccfce4b597ecb73c70401733/testsets/RealSRSet/Lincoln.png -------------------------------------------------------------------------------- /testsets/RealSRSet/building.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/cszn/BSRGAN/5ce1a9c6ae292f30ccfce4b597ecb73c70401733/testsets/RealSRSet/building.png -------------------------------------------------------------------------------- /testsets/RealSRSet/butterfly.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/cszn/BSRGAN/5ce1a9c6ae292f30ccfce4b597ecb73c70401733/testsets/RealSRSet/butterfly.png -------------------------------------------------------------------------------- /testsets/RealSRSet/butterfly2.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/cszn/BSRGAN/5ce1a9c6ae292f30ccfce4b597ecb73c70401733/testsets/RealSRSet/butterfly2.png -------------------------------------------------------------------------------- /testsets/RealSRSet/chip.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/cszn/BSRGAN/5ce1a9c6ae292f30ccfce4b597ecb73c70401733/testsets/RealSRSet/chip.png -------------------------------------------------------------------------------- /testsets/RealSRSet/comic1.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/cszn/BSRGAN/5ce1a9c6ae292f30ccfce4b597ecb73c70401733/testsets/RealSRSet/comic1.png -------------------------------------------------------------------------------- /testsets/RealSRSet/comic2.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/cszn/BSRGAN/5ce1a9c6ae292f30ccfce4b597ecb73c70401733/testsets/RealSRSet/comic2.png -------------------------------------------------------------------------------- /testsets/RealSRSet/comic3.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/cszn/BSRGAN/5ce1a9c6ae292f30ccfce4b597ecb73c70401733/testsets/RealSRSet/comic3.png -------------------------------------------------------------------------------- /testsets/RealSRSet/computer.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/cszn/BSRGAN/5ce1a9c6ae292f30ccfce4b597ecb73c70401733/testsets/RealSRSet/computer.png -------------------------------------------------------------------------------- /testsets/RealSRSet/dog.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/cszn/BSRGAN/5ce1a9c6ae292f30ccfce4b597ecb73c70401733/testsets/RealSRSet/dog.png -------------------------------------------------------------------------------- /testsets/RealSRSet/dped_crop00061.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/cszn/BSRGAN/5ce1a9c6ae292f30ccfce4b597ecb73c70401733/testsets/RealSRSet/dped_crop00061.png -------------------------------------------------------------------------------- /testsets/RealSRSet/foreman.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/cszn/BSRGAN/5ce1a9c6ae292f30ccfce4b597ecb73c70401733/testsets/RealSRSet/foreman.png -------------------------------------------------------------------------------- /testsets/RealSRSet/frog.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/cszn/BSRGAN/5ce1a9c6ae292f30ccfce4b597ecb73c70401733/testsets/RealSRSet/frog.png -------------------------------------------------------------------------------- /testsets/RealSRSet/oldphoto2.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/cszn/BSRGAN/5ce1a9c6ae292f30ccfce4b597ecb73c70401733/testsets/RealSRSet/oldphoto2.png -------------------------------------------------------------------------------- /testsets/RealSRSet/oldphoto3.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/cszn/BSRGAN/5ce1a9c6ae292f30ccfce4b597ecb73c70401733/testsets/RealSRSet/oldphoto3.png -------------------------------------------------------------------------------- /testsets/RealSRSet/oldphoto6.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/cszn/BSRGAN/5ce1a9c6ae292f30ccfce4b597ecb73c70401733/testsets/RealSRSet/oldphoto6.png -------------------------------------------------------------------------------- /testsets/RealSRSet/painting.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/cszn/BSRGAN/5ce1a9c6ae292f30ccfce4b597ecb73c70401733/testsets/RealSRSet/painting.png -------------------------------------------------------------------------------- /testsets/RealSRSet/pattern.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/cszn/BSRGAN/5ce1a9c6ae292f30ccfce4b597ecb73c70401733/testsets/RealSRSet/pattern.png -------------------------------------------------------------------------------- /testsets/RealSRSet/ppt3.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/cszn/BSRGAN/5ce1a9c6ae292f30ccfce4b597ecb73c70401733/testsets/RealSRSet/ppt3.png -------------------------------------------------------------------------------- /testsets/RealSRSet/tiger.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/cszn/BSRGAN/5ce1a9c6ae292f30ccfce4b597ecb73c70401733/testsets/RealSRSet/tiger.png -------------------------------------------------------------------------------- /testsets/RealSR_JPEG/Lincoln_RealSR_JPEG.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/cszn/BSRGAN/5ce1a9c6ae292f30ccfce4b597ecb73c70401733/testsets/RealSR_JPEG/Lincoln_RealSR_JPEG.png -------------------------------------------------------------------------------- /testsets/RealSR_JPEG/building_RealSR_JPEG.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/cszn/BSRGAN/5ce1a9c6ae292f30ccfce4b597ecb73c70401733/testsets/RealSR_JPEG/building_RealSR_JPEG.png -------------------------------------------------------------------------------- /testsets/RealSR_JPEG/butterfly2_RealSR_JPEG.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/cszn/BSRGAN/5ce1a9c6ae292f30ccfce4b597ecb73c70401733/testsets/RealSR_JPEG/butterfly2_RealSR_JPEG.png -------------------------------------------------------------------------------- /testsets/RealSR_JPEG/butterfly_RealSR_JPEG.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/cszn/BSRGAN/5ce1a9c6ae292f30ccfce4b597ecb73c70401733/testsets/RealSR_JPEG/butterfly_RealSR_JPEG.png -------------------------------------------------------------------------------- /testsets/RealSR_JPEG/chip_RealSR_JPEG.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/cszn/BSRGAN/5ce1a9c6ae292f30ccfce4b597ecb73c70401733/testsets/RealSR_JPEG/chip_RealSR_JPEG.png -------------------------------------------------------------------------------- /testsets/RealSR_JPEG/comic1_RealSR_JPEG.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/cszn/BSRGAN/5ce1a9c6ae292f30ccfce4b597ecb73c70401733/testsets/RealSR_JPEG/comic1_RealSR_JPEG.png -------------------------------------------------------------------------------- /testsets/RealSR_JPEG/comic2_RealSR_JPEG.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/cszn/BSRGAN/5ce1a9c6ae292f30ccfce4b597ecb73c70401733/testsets/RealSR_JPEG/comic2_RealSR_JPEG.png -------------------------------------------------------------------------------- /testsets/RealSR_JPEG/comic3_RealSR_JPEG.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/cszn/BSRGAN/5ce1a9c6ae292f30ccfce4b597ecb73c70401733/testsets/RealSR_JPEG/comic3_RealSR_JPEG.png -------------------------------------------------------------------------------- /testsets/RealSR_JPEG/computer_RealSR_JPEG.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/cszn/BSRGAN/5ce1a9c6ae292f30ccfce4b597ecb73c70401733/testsets/RealSR_JPEG/computer_RealSR_JPEG.png -------------------------------------------------------------------------------- /testsets/RealSR_JPEG/dog_RealSR_JPEG.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/cszn/BSRGAN/5ce1a9c6ae292f30ccfce4b597ecb73c70401733/testsets/RealSR_JPEG/dog_RealSR_JPEG.png -------------------------------------------------------------------------------- /testsets/RealSR_JPEG/dped_crop00061_RealSR_JPEG.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/cszn/BSRGAN/5ce1a9c6ae292f30ccfce4b597ecb73c70401733/testsets/RealSR_JPEG/dped_crop00061_RealSR_JPEG.png -------------------------------------------------------------------------------- /testsets/RealSR_JPEG/foreman_RealSR_JPEG.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/cszn/BSRGAN/5ce1a9c6ae292f30ccfce4b597ecb73c70401733/testsets/RealSR_JPEG/foreman_RealSR_JPEG.png -------------------------------------------------------------------------------- /testsets/RealSR_JPEG/frog_RealSR_JPEG.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/cszn/BSRGAN/5ce1a9c6ae292f30ccfce4b597ecb73c70401733/testsets/RealSR_JPEG/frog_RealSR_JPEG.png -------------------------------------------------------------------------------- /testsets/RealSR_JPEG/oldphoto2_RealSR_JPEG.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/cszn/BSRGAN/5ce1a9c6ae292f30ccfce4b597ecb73c70401733/testsets/RealSR_JPEG/oldphoto2_RealSR_JPEG.png -------------------------------------------------------------------------------- /testsets/RealSR_JPEG/oldphoto3_RealSR_JPEG.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/cszn/BSRGAN/5ce1a9c6ae292f30ccfce4b597ecb73c70401733/testsets/RealSR_JPEG/oldphoto3_RealSR_JPEG.png -------------------------------------------------------------------------------- /testsets/RealSR_JPEG/oldphoto6_RealSR_JPEG.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/cszn/BSRGAN/5ce1a9c6ae292f30ccfce4b597ecb73c70401733/testsets/RealSR_JPEG/oldphoto6_RealSR_JPEG.png -------------------------------------------------------------------------------- /testsets/RealSR_JPEG/painting_RealSR_JPEG.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/cszn/BSRGAN/5ce1a9c6ae292f30ccfce4b597ecb73c70401733/testsets/RealSR_JPEG/painting_RealSR_JPEG.png -------------------------------------------------------------------------------- /testsets/RealSR_JPEG/pattern_RealSR_JPEG.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/cszn/BSRGAN/5ce1a9c6ae292f30ccfce4b597ecb73c70401733/testsets/RealSR_JPEG/pattern_RealSR_JPEG.png -------------------------------------------------------------------------------- /testsets/RealSR_JPEG/ppt3_RealSR_JPEG.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/cszn/BSRGAN/5ce1a9c6ae292f30ccfce4b597ecb73c70401733/testsets/RealSR_JPEG/ppt3_RealSR_JPEG.png -------------------------------------------------------------------------------- /testsets/RealSR_JPEG/tiger_RealSR_JPEG.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/cszn/BSRGAN/5ce1a9c6ae292f30ccfce4b597ecb73c70401733/testsets/RealSR_JPEG/tiger_RealSR_JPEG.png -------------------------------------------------------------------------------- /utils/README.md: -------------------------------------------------------------------------------- 1 | 2 | # How to use the degradation model: 3 | ```python 4 | from utils import utils_blindsr as blindsr 5 | img_lq, img_hq = blindsr.degradation_bsrgan_plus(img, sf=4, shuffle_prob=0.1, use_sharp=True, lq_patchsize=64) 6 | ``` 7 | 8 | -------------------------------------------------------------------------------- /utils/test.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/cszn/BSRGAN/5ce1a9c6ae292f30ccfce4b597ecb73c70401733/utils/test.png -------------------------------------------------------------------------------- /utils/utils_blindsr.py: -------------------------------------------------------------------------------- 1 | # -*- coding: utf-8 -*- 2 | import numpy as np 3 | import cv2 4 | import torch 5 | 6 | from utils import utils_image as util 7 | 8 | import random 9 | from scipy import ndimage 10 | import scipy 11 | import scipy.stats as ss 12 | from scipy.interpolate import interp2d 13 | from scipy.linalg import orth 14 | 15 | 16 | 17 | 18 | """ 19 | # -------------------------------------------- 20 | # Super-Resolution 21 | # -------------------------------------------- 22 | # 23 | # Kai Zhang (cskaizhang@gmail.com) 24 | # https://github.com/cszn 25 | # From 2019/03--2021/08 26 | # -------------------------------------------- 27 | """ 28 | 29 | def modcrop_np(img, sf): 30 | ''' 31 | Args: 32 | img: numpy image, WxH or WxHxC 33 | sf: scale factor 34 | 35 | Return: 36 | cropped image 37 | ''' 38 | w, h = img.shape[:2] 39 | im = np.copy(img) 40 | return im[:w - w % sf, :h - h % sf, ...] 41 | 42 | 43 | """ 44 | # -------------------------------------------- 45 | # anisotropic Gaussian kernels 46 | # -------------------------------------------- 47 | """ 48 | def analytic_kernel(k): 49 | """Calculate the X4 kernel from the X2 kernel (for proof see appendix in paper)""" 50 | k_size = k.shape[0] 51 | # Calculate the big kernels size 52 | big_k = np.zeros((3 * k_size - 2, 3 * k_size - 2)) 53 | # Loop over the small kernel to fill the big one 54 | for r in range(k_size): 55 | for c in range(k_size): 56 | big_k[2 * r:2 * r + k_size, 2 * c:2 * c + k_size] += k[r, c] * k 57 | # Crop the edges of the big kernel to ignore very small values and increase run time of SR 58 | crop = k_size // 2 59 | cropped_big_k = big_k[crop:-crop, crop:-crop] 60 | # Normalize to 1 61 | return cropped_big_k / cropped_big_k.sum() 62 | 63 | 64 | def anisotropic_Gaussian(ksize=15, theta=np.pi, l1=6, l2=6): 65 | """ generate an anisotropic Gaussian kernel 66 | Args: 67 | ksize : e.g., 15, kernel size 68 | theta : [0, pi], rotation angle range 69 | l1 : [0.1,50], scaling of eigenvalues 70 | l2 : [0.1,l1], scaling of eigenvalues 71 | If l1 = l2, will get an isotropic Gaussian kernel. 72 | 73 | Returns: 74 | k : kernel 75 | """ 76 | 77 | v = np.dot(np.array([[np.cos(theta), -np.sin(theta)], [np.sin(theta), np.cos(theta)]]), np.array([1., 0.])) 78 | V = np.array([[v[0], v[1]], [v[1], -v[0]]]) 79 | D = np.array([[l1, 0], [0, l2]]) 80 | Sigma = np.dot(np.dot(V, D), np.linalg.inv(V)) 81 | k = gm_blur_kernel(mean=[0, 0], cov=Sigma, size=ksize) 82 | 83 | return k 84 | 85 | 86 | def gm_blur_kernel(mean, cov, size=15): 87 | center = size / 2.0 + 0.5 88 | k = np.zeros([size, size]) 89 | for y in range(size): 90 | for x in range(size): 91 | cy = y - center + 1 92 | cx = x - center + 1 93 | k[y, x] = ss.multivariate_normal.pdf([cx, cy], mean=mean, cov=cov) 94 | 95 | k = k / np.sum(k) 96 | return k 97 | 98 | 99 | def shift_pixel(x, sf, upper_left=True): 100 | """shift pixel for super-resolution with different scale factors 101 | Args: 102 | x: WxHxC or WxH 103 | sf: scale factor 104 | upper_left: shift direction 105 | """ 106 | h, w = x.shape[:2] 107 | shift = (sf-1)*0.5 108 | xv, yv = np.arange(0, w, 1.0), np.arange(0, h, 1.0) 109 | if upper_left: 110 | x1 = xv + shift 111 | y1 = yv + shift 112 | else: 113 | x1 = xv - shift 114 | y1 = yv - shift 115 | 116 | x1 = np.clip(x1, 0, w-1) 117 | y1 = np.clip(y1, 0, h-1) 118 | 119 | if x.ndim == 2: 120 | x = interp2d(xv, yv, x)(x1, y1) 121 | if x.ndim == 3: 122 | for i in range(x.shape[-1]): 123 | x[:, :, i] = interp2d(xv, yv, x[:, :, i])(x1, y1) 124 | 125 | return x 126 | 127 | 128 | def blur(x, k): 129 | ''' 130 | x: image, NxcxHxW 131 | k: kernel, Nx1xhxw 132 | ''' 133 | n, c = x.shape[:2] 134 | p1, p2 = (k.shape[-2]-1)//2, (k.shape[-1]-1)//2 135 | x = torch.nn.functional.pad(x, pad=(p1, p2, p1, p2), mode='replicate') 136 | k = k.repeat(1,c,1,1) 137 | k = k.view(-1, 1, k.shape[2], k.shape[3]) 138 | x = x.view(1, -1, x.shape[2], x.shape[3]) 139 | x = torch.nn.functional.conv2d(x, k, bias=None, stride=1, padding=0, groups=n*c) 140 | x = x.view(n, c, x.shape[2], x.shape[3]) 141 | 142 | return x 143 | 144 | 145 | 146 | def gen_kernel(k_size=np.array([15, 15]), scale_factor=np.array([4, 4]), min_var=0.6, max_var=10., noise_level=0): 147 | """" 148 | # modified version of https://github.com/assafshocher/BlindSR_dataset_generator 149 | # Kai Zhang 150 | # min_var = 0.175 * sf # variance of the gaussian kernel will be sampled between min_var and max_var 151 | # max_var = 2.5 * sf 152 | """ 153 | # Set random eigen-vals (lambdas) and angle (theta) for COV matrix 154 | lambda_1 = min_var + np.random.rand() * (max_var - min_var) 155 | lambda_2 = min_var + np.random.rand() * (max_var - min_var) 156 | theta = np.random.rand() * np.pi # random theta 157 | noise = -noise_level + np.random.rand(*k_size) * noise_level * 2 158 | 159 | # Set COV matrix using Lambdas and Theta 160 | LAMBDA = np.diag([lambda_1, lambda_2]) 161 | Q = np.array([[np.cos(theta), -np.sin(theta)], 162 | [np.sin(theta), np.cos(theta)]]) 163 | SIGMA = Q @ LAMBDA @ Q.T 164 | INV_SIGMA = np.linalg.inv(SIGMA)[None, None, :, :] 165 | 166 | # Set expectation position (shifting kernel for aligned image) 167 | MU = k_size // 2 - 0.5*(scale_factor - 1) # - 0.5 * (scale_factor - k_size % 2) 168 | MU = MU[None, None, :, None] 169 | 170 | # Create meshgrid for Gaussian 171 | [X,Y] = np.meshgrid(range(k_size[0]), range(k_size[1])) 172 | Z = np.stack([X, Y], 2)[:, :, :, None] 173 | 174 | # Calcualte Gaussian for every pixel of the kernel 175 | ZZ = Z-MU 176 | ZZ_t = ZZ.transpose(0,1,3,2) 177 | raw_kernel = np.exp(-0.5 * np.squeeze(ZZ_t @ INV_SIGMA @ ZZ)) * (1 + noise) 178 | 179 | # shift the kernel so it will be centered 180 | #raw_kernel_centered = kernel_shift(raw_kernel, scale_factor) 181 | 182 | # Normalize the kernel and return 183 | #kernel = raw_kernel_centered / np.sum(raw_kernel_centered) 184 | kernel = raw_kernel / np.sum(raw_kernel) 185 | return kernel 186 | 187 | 188 | def fspecial_gaussian(hsize, sigma): 189 | hsize = [hsize, hsize] 190 | siz = [(hsize[0]-1.0)/2.0, (hsize[1]-1.0)/2.0] 191 | std = sigma 192 | [x, y] = np.meshgrid(np.arange(-siz[1], siz[1]+1), np.arange(-siz[0], siz[0]+1)) 193 | arg = -(x*x + y*y)/(2*std*std) 194 | h = np.exp(arg) 195 | h[h < scipy.finfo(float).eps * h.max()] = 0 196 | sumh = h.sum() 197 | if sumh != 0: 198 | h = h/sumh 199 | return h 200 | 201 | 202 | def fspecial_laplacian(alpha): 203 | alpha = max([0, min([alpha,1])]) 204 | h1 = alpha/(alpha+1) 205 | h2 = (1-alpha)/(alpha+1) 206 | h = [[h1, h2, h1], [h2, -4/(alpha+1), h2], [h1, h2, h1]] 207 | h = np.array(h) 208 | return h 209 | 210 | 211 | def fspecial(filter_type, *args, **kwargs): 212 | ''' 213 | python code from: 214 | https://github.com/ronaldosena/imagens-medicas-2/blob/40171a6c259edec7827a6693a93955de2bd39e76/Aulas/aula_2_-_uniform_filter/matlab_fspecial.py 215 | ''' 216 | if filter_type == 'gaussian': 217 | return fspecial_gaussian(*args, **kwargs) 218 | if filter_type == 'laplacian': 219 | return fspecial_laplacian(*args, **kwargs) 220 | 221 | """ 222 | # -------------------------------------------- 223 | # degradation models 224 | # -------------------------------------------- 225 | """ 226 | 227 | 228 | def bicubic_degradation(x, sf=3): 229 | ''' 230 | Args: 231 | x: HxWxC image, [0, 1] 232 | sf: down-scale factor 233 | 234 | Return: 235 | bicubicly downsampled LR image 236 | ''' 237 | x = util.imresize_np(x, scale=1/sf) 238 | return x 239 | 240 | 241 | def srmd_degradation(x, k, sf=3): 242 | ''' blur + bicubic downsampling 243 | 244 | Args: 245 | x: HxWxC image, [0, 1] 246 | k: hxw, double 247 | sf: down-scale factor 248 | 249 | Return: 250 | downsampled LR image 251 | 252 | Reference: 253 | @inproceedings{zhang2018learning, 254 | title={Learning a single convolutional super-resolution network for multiple degradations}, 255 | author={Zhang, Kai and Zuo, Wangmeng and Zhang, Lei}, 256 | booktitle={IEEE Conference on Computer Vision and Pattern Recognition}, 257 | pages={3262--3271}, 258 | year={2018} 259 | } 260 | ''' 261 | x = ndimage.filters.convolve(x, np.expand_dims(k, axis=2), mode='wrap') # 'nearest' | 'mirror' 262 | x = bicubic_degradation(x, sf=sf) 263 | return x 264 | 265 | 266 | def dpsr_degradation(x, k, sf=3): 267 | 268 | ''' bicubic downsampling + blur 269 | 270 | Args: 271 | x: HxWxC image, [0, 1] 272 | k: hxw, double 273 | sf: down-scale factor 274 | 275 | Return: 276 | downsampled LR image 277 | 278 | Reference: 279 | @inproceedings{zhang2019deep, 280 | title={Deep Plug-and-Play Super-Resolution for Arbitrary Blur Kernels}, 281 | author={Zhang, Kai and Zuo, Wangmeng and Zhang, Lei}, 282 | booktitle={IEEE Conference on Computer Vision and Pattern Recognition}, 283 | pages={1671--1681}, 284 | year={2019} 285 | } 286 | ''' 287 | x = bicubic_degradation(x, sf=sf) 288 | x = ndimage.filters.convolve(x, np.expand_dims(k, axis=2), mode='wrap') 289 | return x 290 | 291 | 292 | def classical_degradation(x, k, sf=3): 293 | ''' blur + downsampling 294 | 295 | Args: 296 | x: HxWxC image, [0, 1]/[0, 255] 297 | k: hxw, double 298 | sf: down-scale factor 299 | 300 | Return: 301 | downsampled LR image 302 | ''' 303 | x = ndimage.filters.convolve(x, np.expand_dims(k, axis=2), mode='wrap') 304 | #x = filters.correlate(x, np.expand_dims(np.flip(k), axis=2)) 305 | st = 0 306 | return x[st::sf, st::sf, ...] 307 | 308 | 309 | def add_sharpening(img, weight=0.5, radius=50, threshold=10): 310 | """USM sharpening. borrowed from real-ESRGAN 311 | Input image: I; Blurry image: B. 312 | 1. K = I + weight * (I - B) 313 | 2. Mask = 1 if abs(I - B) > threshold, else: 0 314 | 3. Blur mask: 315 | 4. Out = Mask * K + (1 - Mask) * I 316 | Args: 317 | img (Numpy array): Input image, HWC, BGR; float32, [0, 1]. 318 | weight (float): Sharp weight. Default: 1. 319 | radius (float): Kernel size of Gaussian blur. Default: 50. 320 | threshold (int): 321 | """ 322 | if radius % 2 == 0: 323 | radius += 1 324 | blur = cv2.GaussianBlur(img, (radius, radius), 0) 325 | residual = img - blur 326 | mask = np.abs(residual) * 255 > threshold 327 | mask = mask.astype('float32') 328 | soft_mask = cv2.GaussianBlur(mask, (radius, radius), 0) 329 | 330 | K = img + weight * residual 331 | K = np.clip(K, 0, 1) 332 | return soft_mask * K + (1 - soft_mask) * img 333 | 334 | 335 | def add_blur(img, sf=4): 336 | wd2 = 4.0 + sf 337 | wd = 2.0 + 0.2*sf 338 | if random.random() < 0.5: 339 | l1 = wd2*random.random() 340 | l2 = wd2*random.random() 341 | k = anisotropic_Gaussian(ksize=2*random.randint(2,11)+3, theta=random.random()*np.pi, l1=l1, l2=l2) 342 | else: 343 | k = fspecial('gaussian', 2*random.randint(2,11)+3, wd*random.random()) 344 | img = ndimage.filters.convolve(img, np.expand_dims(k, axis=2), mode='mirror') 345 | 346 | return img 347 | 348 | 349 | def add_resize(img, sf=4): 350 | rnum = np.random.rand() 351 | if rnum > 0.8: # up 352 | sf1 = random.uniform(1, 2) 353 | elif rnum < 0.7: # down 354 | sf1 = random.uniform(0.5/sf, 1) 355 | else: 356 | sf1 = 1.0 357 | img = cv2.resize(img, (int(sf1*img.shape[1]), int(sf1*img.shape[0])), interpolation=random.choice([1, 2, 3])) 358 | img = np.clip(img, 0.0, 1.0) 359 | 360 | return img 361 | 362 | 363 | def add_Gaussian_noise(img, noise_level1=2, noise_level2=25): 364 | noise_level = random.randint(noise_level1, noise_level2) 365 | rnum = np.random.rand() 366 | if rnum > 0.6: # add color Gaussian noise 367 | img += np.random.normal(0, noise_level/255.0, img.shape).astype(np.float32) 368 | elif rnum < 0.4: # add grayscale Gaussian noise 369 | img += np.random.normal(0, noise_level/255.0, (*img.shape[:2], 1)).astype(np.float32) 370 | else: # add noise 371 | L = noise_level2/255. 372 | D = np.diag(np.random.rand(3)) 373 | U = orth(np.random.rand(3,3)) 374 | conv = np.dot(np.dot(np.transpose(U), D), U) 375 | img += np.random.multivariate_normal([0,0,0], np.abs(L**2*conv), img.shape[:2]).astype(np.float32) 376 | img = np.clip(img, 0.0, 1.0) 377 | return img 378 | 379 | 380 | def add_speckle_noise(img, noise_level1=2, noise_level2=25): 381 | noise_level = random.randint(noise_level1, noise_level2) 382 | img = np.clip(img, 0.0, 1.0) 383 | rnum = random.random() 384 | if rnum > 0.6: 385 | img += img*np.random.normal(0, noise_level/255.0, img.shape).astype(np.float32) 386 | elif rnum < 0.4: 387 | img += img*np.random.normal(0, noise_level/255.0, (*img.shape[:2], 1)).astype(np.float32) 388 | else: 389 | L = noise_level2/255. 390 | D = np.diag(np.random.rand(3)) 391 | U = orth(np.random.rand(3,3)) 392 | conv = np.dot(np.dot(np.transpose(U), D), U) 393 | img += img*np.random.multivariate_normal([0,0,0], np.abs(L**2*conv), img.shape[:2]).astype(np.float32) 394 | img = np.clip(img, 0.0, 1.0) 395 | return img 396 | 397 | 398 | def add_Poisson_noise(img): 399 | img = np.clip((img * 255.0).round(), 0, 255) / 255. 400 | vals = 10**(2*random.random()+2.0) # [2, 4] 401 | if random.random() < 0.5: 402 | img = np.random.poisson(img * vals).astype(np.float32) / vals 403 | else: 404 | img_gray = np.dot(img[...,:3], [0.299, 0.587, 0.114]) 405 | img_gray = np.clip((img_gray * 255.0).round(), 0, 255) / 255. 406 | noise_gray = np.random.poisson(img_gray * vals).astype(np.float32) / vals - img_gray 407 | img += noise_gray[:, :, np.newaxis] 408 | img = np.clip(img, 0.0, 1.0) 409 | return img 410 | 411 | 412 | def add_JPEG_noise(img): 413 | quality_factor = random.randint(30, 95) 414 | img = cv2.cvtColor(util.single2uint(img), cv2.COLOR_RGB2BGR) 415 | result, encimg = cv2.imencode('.jpg', img, [int(cv2.IMWRITE_JPEG_QUALITY), quality_factor]) 416 | img = cv2.imdecode(encimg, 1) 417 | img = cv2.cvtColor(util.uint2single(img), cv2.COLOR_BGR2RGB) 418 | return img 419 | 420 | 421 | def random_crop(lq, hq, sf=4, lq_patchsize=64): 422 | h, w = lq.shape[:2] 423 | rnd_h = random.randint(0, h-lq_patchsize) 424 | rnd_w = random.randint(0, w-lq_patchsize) 425 | lq = lq[rnd_h:rnd_h + lq_patchsize, rnd_w:rnd_w + lq_patchsize, :] 426 | 427 | rnd_h_H, rnd_w_H = int(rnd_h * sf), int(rnd_w * sf) 428 | hq = hq[rnd_h_H:rnd_h_H + lq_patchsize*sf, rnd_w_H:rnd_w_H + lq_patchsize*sf, :] 429 | return lq, hq 430 | 431 | 432 | def degradation_bsrgan(img, sf=4, lq_patchsize=72, isp_model=None): 433 | """ 434 | This is the degradation model of BSRGAN from the paper 435 | "Designing a Practical Degradation Model for Deep Blind Image Super-Resolution" 436 | ---------- 437 | img: HXWXC, [0, 1], its size should be large than (lq_patchsizexsf)x(lq_patchsizexsf) 438 | sf: scale factor 439 | isp_model: camera ISP model 440 | 441 | Returns 442 | ------- 443 | img: low-quality patch, size: lq_patchsizeXlq_patchsizeXC, range: [0, 1] 444 | hq: corresponding high-quality patch, size: (lq_patchsizexsf)X(lq_patchsizexsf)XC, range: [0, 1] 445 | """ 446 | isp_prob, jpeg_prob, scale2_prob = 0.25, 0.9, 0.25 447 | sf_ori = sf 448 | 449 | h1, w1 = img.shape[:2] 450 | img = img.copy()[:h1 - h1 % sf, :w1 - w1 % sf, ...] # mod crop 451 | h, w = img.shape[:2] 452 | 453 | if h < lq_patchsize*sf or w < lq_patchsize*sf: 454 | raise ValueError(f'img size ({h1}X{w1}) is too small!') 455 | 456 | hq = img.copy() 457 | 458 | if sf == 4 and random.random() < scale2_prob: # downsample1 459 | if np.random.rand() < 0.5: 460 | img = cv2.resize(img, (int(1/2*img.shape[1]), int(1/2*img.shape[0])), interpolation=random.choice([1,2,3])) 461 | else: 462 | img = util.imresize_np(img, 1/2, True) 463 | img = np.clip(img, 0.0, 1.0) 464 | sf = 2 465 | 466 | shuffle_order = random.sample(range(7), 7) 467 | idx1, idx2 = shuffle_order.index(2), shuffle_order.index(3) 468 | if idx1 > idx2: # keep downsample3 last 469 | shuffle_order[idx1], shuffle_order[idx2] = shuffle_order[idx2], shuffle_order[idx1] 470 | 471 | for i in shuffle_order: 472 | 473 | if i == 0: 474 | img = add_blur(img, sf=sf) 475 | 476 | elif i == 1: 477 | img = add_blur(img, sf=sf) 478 | 479 | elif i == 2: 480 | a, b = img.shape[1], img.shape[0] 481 | # downsample2 482 | if random.random() < 0.75: 483 | sf1 = random.uniform(1,2*sf) 484 | img = cv2.resize(img, (int(1/sf1*img.shape[1]), int(1/sf1*img.shape[0])), interpolation=random.choice([1,2,3])) 485 | else: 486 | k = fspecial('gaussian', 25, random.uniform(0.1, 0.6*sf)) 487 | k_shifted = shift_pixel(k, sf) 488 | k_shifted = k_shifted/k_shifted.sum() # blur with shifted kernel 489 | img = ndimage.filters.convolve(img, np.expand_dims(k_shifted, axis=2), mode='mirror') 490 | img = img[0::sf, 0::sf, ...] # nearest downsampling 491 | img = np.clip(img, 0.0, 1.0) 492 | 493 | elif i == 3: 494 | # downsample3 495 | img = cv2.resize(img, (int(1/sf*a), int(1/sf*b)), interpolation=random.choice([1,2,3])) 496 | img = np.clip(img, 0.0, 1.0) 497 | 498 | elif i == 4: 499 | # add Gaussian noise 500 | img = add_Gaussian_noise(img, noise_level1=2, noise_level2=25) 501 | 502 | elif i == 5: 503 | # add JPEG noise 504 | if random.random() < jpeg_prob: 505 | img = add_JPEG_noise(img) 506 | 507 | elif i == 6: 508 | # add processed camera sensor noise 509 | if random.random() < isp_prob and isp_model is not None: 510 | with torch.no_grad(): 511 | img, hq = isp_model.forward(img.copy(), hq) 512 | 513 | # add final JPEG compression noise 514 | img = add_JPEG_noise(img) 515 | 516 | # random crop 517 | img, hq = random_crop(img, hq, sf_ori, lq_patchsize) 518 | 519 | return img, hq 520 | 521 | 522 | 523 | 524 | def degradation_bsrgan_plus(img, sf=4, shuffle_prob=0.5, use_sharp=True, lq_patchsize=64, isp_model=None): 525 | """ 526 | This is an extended degradation model by combining 527 | the degradation models of BSRGAN and Real-ESRGAN 528 | ---------- 529 | img: HXWXC, [0, 1], its size should be large than (lq_patchsizexsf)x(lq_patchsizexsf) 530 | sf: scale factor 531 | use_shuffle: the degradation shuffle 532 | use_sharp: sharpening the img 533 | 534 | Returns 535 | ------- 536 | img: low-quality patch, size: lq_patchsizeXlq_patchsizeXC, range: [0, 1] 537 | hq: corresponding high-quality patch, size: (lq_patchsizexsf)X(lq_patchsizexsf)XC, range: [0, 1] 538 | """ 539 | 540 | h1, w1 = img.shape[:2] 541 | img = img.copy()[:h1 - h1 % sf, :w1 - w1 % sf, ...] # mod crop 542 | h, w = img.shape[:2] 543 | 544 | if h < lq_patchsize*sf or w < lq_patchsize*sf: 545 | raise ValueError(f'img size ({h1}X{w1}) is too small!') 546 | 547 | if use_sharp: 548 | img = add_sharpening(img) 549 | hq = img.copy() 550 | 551 | if random.random() < shuffle_prob: 552 | shuffle_order = random.sample(range(13), 13) 553 | else: 554 | shuffle_order = list(range(13)) 555 | # local shuffle for noise, JPEG is always the last one 556 | shuffle_order[2:6] = random.sample(shuffle_order[2:6], len(range(2, 6))) 557 | shuffle_order[9:13] = random.sample(shuffle_order[9:13], len(range(9, 13))) 558 | 559 | poisson_prob, speckle_prob, isp_prob = 0.1, 0.1, 0.1 560 | 561 | for i in shuffle_order: 562 | if i == 0: 563 | img = add_blur(img, sf=sf) 564 | elif i == 1: 565 | img = add_resize(img, sf=sf) 566 | elif i == 2: 567 | img = add_Gaussian_noise(img, noise_level1=2, noise_level2=25) 568 | elif i == 3: 569 | if random.random() < poisson_prob: 570 | img = add_Poisson_noise(img) 571 | elif i == 4: 572 | if random.random() < speckle_prob: 573 | img = add_speckle_noise(img) 574 | elif i == 5: 575 | if random.random() < isp_prob and isp_model is not None: 576 | with torch.no_grad(): 577 | img, hq = isp_model.forward(img.copy(), hq) 578 | elif i == 6: 579 | img = add_JPEG_noise(img) 580 | elif i == 7: 581 | img = add_blur(img, sf=sf) 582 | elif i == 8: 583 | img = add_resize(img, sf=sf) 584 | elif i == 9: 585 | img = add_Gaussian_noise(img, noise_level1=2, noise_level2=25) 586 | elif i == 10: 587 | if random.random() < poisson_prob: 588 | img = add_Poisson_noise(img) 589 | elif i == 11: 590 | if random.random() < speckle_prob: 591 | img = add_speckle_noise(img) 592 | elif i == 12: 593 | if random.random() < isp_prob and isp_model is not None: 594 | with torch.no_grad(): 595 | img, hq = isp_model.forward(img.copy(), hq) 596 | else: 597 | print('check the shuffle!') 598 | 599 | # resize to desired size 600 | img = cv2.resize(img, (int(1/sf*hq.shape[1]), int(1/sf*hq.shape[0])), interpolation=random.choice([1, 2, 3])) 601 | 602 | # add final JPEG compression noise 603 | img = add_JPEG_noise(img) 604 | 605 | # random crop 606 | img, hq = random_crop(img, hq, sf, lq_patchsize) 607 | 608 | return img, hq 609 | 610 | 611 | 612 | if __name__ == '__main__': 613 | img = util.imread_uint('utils/test.png', 3) 614 | img = util.uint2single(img) 615 | sf = 4 616 | 617 | for i in range(20): 618 | img_lq, img_hq = degradation_bsrgan(img, sf=sf, lq_patchsize=72) 619 | print(i) 620 | lq_nearest = cv2.resize(util.single2uint(img_lq), (int(sf*img_lq.shape[1]), int(sf*img_lq.shape[0])), interpolation=0) 621 | img_concat = np.concatenate([lq_nearest, util.single2uint(img_hq)], axis=1) 622 | util.imsave(img_concat, str(i)+'.png') 623 | 624 | # for i in range(10): 625 | # img_lq, img_hq = degradation_bsrgan_plus(img, sf=sf, shuffle_prob=0.1, use_sharp=True, lq_patchsize=64) 626 | # print(i) 627 | # lq_nearest = cv2.resize(util.single2uint(img_lq), (int(sf*img_lq.shape[1]), int(sf*img_lq.shape[0])), interpolation=0) 628 | # img_concat = np.concatenate([lq_nearest, util.single2uint(img_hq)], axis=1) 629 | # util.imsave(img_concat, str(i)+'.png') 630 | 631 | # run utils/utils_blindsr.py 632 | -------------------------------------------------------------------------------- /utils/utils_googledownload.py: -------------------------------------------------------------------------------- 1 | import math 2 | import requests 3 | from tqdm import tqdm 4 | 5 | 6 | ''' 7 | borrowed from 8 | https://github.com/xinntao/BasicSR/blob/28883e15eedc3381d23235ff3cf7c454c4be87e6/basicsr/utils/download_util.py 9 | ''' 10 | 11 | 12 | def sizeof_fmt(size, suffix='B'): 13 | """Get human readable file size. 14 | Args: 15 | size (int): File size. 16 | suffix (str): Suffix. Default: 'B'. 17 | Return: 18 | str: Formated file siz. 19 | """ 20 | for unit in ['', 'K', 'M', 'G', 'T', 'P', 'E', 'Z']: 21 | if abs(size) < 1024.0: 22 | return f'{size:3.1f} {unit}{suffix}' 23 | size /= 1024.0 24 | return f'{size:3.1f} Y{suffix}' 25 | 26 | 27 | def download_file_from_google_drive(file_id, save_path): 28 | """Download files from google drive. 29 | Ref: 30 | https://stackoverflow.com/questions/25010369/wget-curl-large-file-from-google-drive # noqa E501 31 | Args: 32 | file_id (str): File id. 33 | save_path (str): Save path. 34 | """ 35 | 36 | session = requests.Session() 37 | URL = 'https://docs.google.com/uc?export=download' 38 | params = {'id': file_id} 39 | 40 | response = session.get(URL, params=params, stream=True) 41 | token = get_confirm_token(response) 42 | if token: 43 | params['confirm'] = token 44 | response = session.get(URL, params=params, stream=True) 45 | 46 | # get file size 47 | response_file_size = session.get( 48 | URL, params=params, stream=True, headers={'Range': 'bytes=0-2'}) 49 | if 'Content-Range' in response_file_size.headers: 50 | file_size = int( 51 | response_file_size.headers['Content-Range'].split('/')[1]) 52 | else: 53 | file_size = None 54 | 55 | save_response_content(response, save_path, file_size) 56 | 57 | 58 | def get_confirm_token(response): 59 | for key, value in response.cookies.items(): 60 | if key.startswith('download_warning'): 61 | return value 62 | return None 63 | 64 | 65 | def save_response_content(response, 66 | destination, 67 | file_size=None, 68 | chunk_size=32768): 69 | if file_size is not None: 70 | pbar = tqdm(total=math.ceil(file_size / chunk_size), unit='chunk') 71 | 72 | readable_file_size = sizeof_fmt(file_size) 73 | else: 74 | pbar = None 75 | 76 | with open(destination, 'wb') as f: 77 | downloaded_size = 0 78 | for chunk in response.iter_content(chunk_size): 79 | downloaded_size += chunk_size 80 | if pbar is not None: 81 | pbar.update(1) 82 | pbar.set_description(f'Download {sizeof_fmt(downloaded_size)} ' 83 | f'/ {readable_file_size}') 84 | if chunk: # filter out keep-alive new chunks 85 | f.write(chunk) 86 | if pbar is not None: 87 | pbar.close() 88 | 89 | 90 | if __name__ == "__main__": 91 | file_id = '1WNULM1e8gRNvsngVscsQ8tpaOqJ4mYtv' 92 | save_path = 'BSRGAN.pth' 93 | download_file_from_google_drive(file_id, save_path) 94 | -------------------------------------------------------------------------------- /utils/utils_image.py: -------------------------------------------------------------------------------- 1 | import os 2 | import math 3 | import random 4 | import numpy as np 5 | import torch 6 | import cv2 7 | from torchvision.utils import make_grid 8 | from datetime import datetime 9 | # import torchvision.transforms as transforms 10 | import matplotlib.pyplot as plt 11 | from mpl_toolkits.mplot3d import Axes3D 12 | os.environ["KMP_DUPLICATE_LIB_OK"]="TRUE" 13 | 14 | 15 | ''' 16 | # -------------------------------------------- 17 | # Kai Zhang (github: https://github.com/cszn) 18 | # 03/Mar/2019 19 | # -------------------------------------------- 20 | # https://github.com/twhui/SRGAN-pyTorch 21 | # https://github.com/xinntao/BasicSR 22 | # -------------------------------------------- 23 | ''' 24 | 25 | 26 | IMG_EXTENSIONS = ['.jpg', '.JPG', '.jpeg', '.JPEG', '.png', '.PNG', '.ppm', '.PPM', '.bmp', '.BMP', '.tif'] 27 | 28 | 29 | def is_image_file(filename): 30 | return any(filename.endswith(extension) for extension in IMG_EXTENSIONS) 31 | 32 | 33 | def get_timestamp(): 34 | return datetime.now().strftime('%y%m%d-%H%M%S') 35 | 36 | 37 | def imshow(x, title=None, cbar=False, figsize=None): 38 | plt.figure(figsize=figsize) 39 | plt.imshow(np.squeeze(x), interpolation='nearest', cmap='gray') 40 | if title: 41 | plt.title(title) 42 | if cbar: 43 | plt.colorbar() 44 | plt.show() 45 | 46 | 47 | def surf(Z, cmap='rainbow', figsize=None): 48 | plt.figure(figsize=figsize) 49 | ax3 = plt.axes(projection='3d') 50 | 51 | w, h = Z.shape[:2] 52 | xx = np.arange(0,w,1) 53 | yy = np.arange(0,h,1) 54 | X, Y = np.meshgrid(xx, yy) 55 | ax3.plot_surface(X,Y,Z,cmap=cmap) 56 | #ax3.contour(X,Y,Z, zdim='z',offset=-2,cmap=cmap) 57 | plt.show() 58 | 59 | 60 | ''' 61 | # -------------------------------------------- 62 | # get image pathes 63 | # -------------------------------------------- 64 | ''' 65 | 66 | 67 | def get_image_paths(dataroot): 68 | paths = None # return None if dataroot is None 69 | if dataroot is not None: 70 | paths = sorted(_get_paths_from_images(dataroot)) 71 | return paths 72 | 73 | 74 | def _get_paths_from_images(path): 75 | assert os.path.isdir(path), '{:s} is not a valid directory'.format(path) 76 | images = [] 77 | for dirpath, _, fnames in sorted(os.walk(path)): 78 | for fname in sorted(fnames): 79 | if is_image_file(fname): 80 | img_path = os.path.join(dirpath, fname) 81 | images.append(img_path) 82 | assert images, '{:s} has no valid image file'.format(path) 83 | return images 84 | 85 | 86 | ''' 87 | # -------------------------------------------- 88 | # split large images into small images 89 | # -------------------------------------------- 90 | ''' 91 | 92 | 93 | def patches_from_image(img, p_size=512, p_overlap=64, p_max=800): 94 | w, h = img.shape[:2] 95 | patches = [] 96 | if w > p_max and h > p_max: 97 | w1 = list(np.arange(0, w-p_size, p_size-p_overlap, dtype=np.int)) 98 | h1 = list(np.arange(0, h-p_size, p_size-p_overlap, dtype=np.int)) 99 | w1.append(w-p_size) 100 | h1.append(h-p_size) 101 | # print(w1) 102 | # print(h1) 103 | for i in w1: 104 | for j in h1: 105 | patches.append(img[i:i+p_size, j:j+p_size,:]) 106 | else: 107 | patches.append(img) 108 | 109 | return patches 110 | 111 | 112 | def imssave(imgs, img_path): 113 | """ 114 | imgs: list, N images of size WxHxC 115 | """ 116 | img_name, ext = os.path.splitext(os.path.basename(img_path)) 117 | 118 | for i, img in enumerate(imgs): 119 | if img.ndim == 3: 120 | img = img[:, :, [2, 1, 0]] 121 | new_path = os.path.join(os.path.dirname(img_path), img_name+str('_s{:04d}'.format(i))+'.png') 122 | cv2.imwrite(new_path, img) 123 | 124 | 125 | def split_imageset(original_dataroot, taget_dataroot, n_channels=3, p_size=800, p_overlap=96, p_max=1000): 126 | """ 127 | split the large images from original_dataroot into small overlapped images with size (p_size)x(p_size), 128 | and save them into taget_dataroot; only the images with larger size than (p_max)x(p_max) 129 | will be splitted. 130 | 131 | Args: 132 | original_dataroot: 133 | taget_dataroot: 134 | p_size: size of small images 135 | p_overlap: patch size in training is a good choice 136 | p_max: images with smaller size than (p_max)x(p_max) keep unchanged. 137 | """ 138 | paths = get_image_paths(original_dataroot) 139 | for img_path in paths: 140 | # img_name, ext = os.path.splitext(os.path.basename(img_path)) 141 | img = imread_uint(img_path, n_channels=n_channels) 142 | patches = patches_from_image(img, p_size, p_overlap, p_max) 143 | imssave(patches, os.path.join(taget_dataroot,os.path.basename(img_path))) 144 | #if original_dataroot == taget_dataroot: 145 | #del img_path 146 | 147 | ''' 148 | # -------------------------------------------- 149 | # makedir 150 | # -------------------------------------------- 151 | ''' 152 | 153 | 154 | def mkdir(path): 155 | if not os.path.exists(path): 156 | os.makedirs(path) 157 | 158 | 159 | def mkdirs(paths): 160 | if isinstance(paths, str): 161 | mkdir(paths) 162 | else: 163 | for path in paths: 164 | mkdir(path) 165 | 166 | 167 | def mkdir_and_rename(path): 168 | if os.path.exists(path): 169 | new_name = path + '_archived_' + get_timestamp() 170 | print('Path already exists. Rename it to [{:s}]'.format(new_name)) 171 | os.rename(path, new_name) 172 | os.makedirs(path) 173 | 174 | 175 | ''' 176 | # -------------------------------------------- 177 | # read image from path 178 | # opencv is fast, but read BGR numpy image 179 | # -------------------------------------------- 180 | ''' 181 | 182 | 183 | # -------------------------------------------- 184 | # get uint8 image of size HxWxn_channles (RGB) 185 | # -------------------------------------------- 186 | def imread_uint(path, n_channels=3): 187 | # input: path 188 | # output: HxWx3(RGB or GGG), or HxWx1 (G) 189 | if n_channels == 1: 190 | img = cv2.imread(path, 0) # cv2.IMREAD_GRAYSCALE 191 | img = np.expand_dims(img, axis=2) # HxWx1 192 | elif n_channels == 3: 193 | img = cv2.imread(path, cv2.IMREAD_UNCHANGED) # BGR or G 194 | if img.ndim == 2: 195 | img = cv2.cvtColor(img, cv2.COLOR_GRAY2RGB) # GGG 196 | else: 197 | img = cv2.cvtColor(img, cv2.COLOR_BGR2RGB) # RGB 198 | return img 199 | 200 | 201 | # -------------------------------------------- 202 | # matlab's imwrite 203 | # -------------------------------------------- 204 | def imsave(img, img_path): 205 | img = np.squeeze(img) 206 | if img.ndim == 3: 207 | img = img[:, :, [2, 1, 0]] 208 | cv2.imwrite(img_path, img) 209 | 210 | def imwrite(img, img_path): 211 | img = np.squeeze(img) 212 | if img.ndim == 3: 213 | img = img[:, :, [2, 1, 0]] 214 | cv2.imwrite(img_path, img) 215 | 216 | 217 | 218 | # -------------------------------------------- 219 | # get single image of size HxWxn_channles (BGR) 220 | # -------------------------------------------- 221 | def read_img(path): 222 | # read image by cv2 223 | # return: Numpy float32, HWC, BGR, [0,1] 224 | img = cv2.imread(path, cv2.IMREAD_UNCHANGED) # cv2.IMREAD_GRAYSCALE 225 | img = img.astype(np.float32) / 255. 226 | if img.ndim == 2: 227 | img = np.expand_dims(img, axis=2) 228 | # some images have 4 channels 229 | if img.shape[2] > 3: 230 | img = img[:, :, :3] 231 | return img 232 | 233 | 234 | ''' 235 | # -------------------------------------------- 236 | # image format conversion 237 | # -------------------------------------------- 238 | # numpy(single) <---> numpy(unit) 239 | # numpy(single) <---> tensor 240 | # numpy(unit) <---> tensor 241 | # -------------------------------------------- 242 | ''' 243 | 244 | 245 | # -------------------------------------------- 246 | # numpy(single) [0, 1] <---> numpy(unit) 247 | # -------------------------------------------- 248 | 249 | 250 | def uint2single(img): 251 | 252 | return np.float32(img/255.) 253 | 254 | 255 | def single2uint(img): 256 | 257 | return np.uint8((img.clip(0, 1)*255.).round()) 258 | 259 | 260 | def uint162single(img): 261 | 262 | return np.float32(img/65535.) 263 | 264 | 265 | def single2uint16(img): 266 | 267 | return np.uint16((img.clip(0, 1)*65535.).round()) 268 | 269 | 270 | # -------------------------------------------- 271 | # numpy(unit) (HxWxC or HxW) <---> tensor 272 | # -------------------------------------------- 273 | 274 | 275 | # convert uint to 4-dimensional torch tensor 276 | def uint2tensor4(img): 277 | if img.ndim == 2: 278 | img = np.expand_dims(img, axis=2) 279 | return torch.from_numpy(np.ascontiguousarray(img)).permute(2, 0, 1).float().div(255.).unsqueeze(0) 280 | 281 | 282 | # convert uint to 3-dimensional torch tensor 283 | def uint2tensor3(img): 284 | if img.ndim == 2: 285 | img = np.expand_dims(img, axis=2) 286 | return torch.from_numpy(np.ascontiguousarray(img)).permute(2, 0, 1).float().div(255.) 287 | 288 | 289 | # convert 2/3/4-dimensional torch tensor to uint 290 | def tensor2uint(img): 291 | img = img.data.squeeze().float().clamp_(0, 1).cpu().numpy() 292 | if img.ndim == 3: 293 | img = np.transpose(img, (1, 2, 0)) 294 | return np.uint8((img*255.0).round()) 295 | 296 | 297 | # -------------------------------------------- 298 | # numpy(single) (HxWxC) <---> tensor 299 | # -------------------------------------------- 300 | 301 | 302 | # convert single (HxWxC) to 3-dimensional torch tensor 303 | def single2tensor3(img): 304 | return torch.from_numpy(np.ascontiguousarray(img)).permute(2, 0, 1).float() 305 | 306 | 307 | # convert single (HxWxC) to 4-dimensional torch tensor 308 | def single2tensor4(img): 309 | return torch.from_numpy(np.ascontiguousarray(img)).permute(2, 0, 1).float().unsqueeze(0) 310 | 311 | 312 | # convert torch tensor to single 313 | def tensor2single(img): 314 | img = img.data.squeeze().float().cpu().numpy() 315 | if img.ndim == 3: 316 | img = np.transpose(img, (1, 2, 0)) 317 | 318 | return img 319 | 320 | # convert torch tensor to single 321 | def tensor2single3(img): 322 | img = img.data.squeeze().float().cpu().numpy() 323 | if img.ndim == 3: 324 | img = np.transpose(img, (1, 2, 0)) 325 | elif img.ndim == 2: 326 | img = np.expand_dims(img, axis=2) 327 | return img 328 | 329 | 330 | def single2tensor5(img): 331 | return torch.from_numpy(np.ascontiguousarray(img)).permute(2, 0, 1, 3).float().unsqueeze(0) 332 | 333 | 334 | def single32tensor5(img): 335 | return torch.from_numpy(np.ascontiguousarray(img)).float().unsqueeze(0).unsqueeze(0) 336 | 337 | 338 | def single42tensor4(img): 339 | return torch.from_numpy(np.ascontiguousarray(img)).permute(2, 0, 1, 3).float() 340 | 341 | 342 | # from skimage.io import imread, imsave 343 | def tensor2img(tensor, out_type=np.uint8, min_max=(0, 1)): 344 | ''' 345 | Converts a torch Tensor into an image Numpy array of BGR channel order 346 | Input: 4D(B,(3/1),H,W), 3D(C,H,W), or 2D(H,W), any range, RGB channel order 347 | Output: 3D(H,W,C) or 2D(H,W), [0,255], np.uint8 (default) 348 | ''' 349 | tensor = tensor.squeeze().float().cpu().clamp_(*min_max) # squeeze first, then clamp 350 | tensor = (tensor - min_max[0]) / (min_max[1] - min_max[0]) # to range [0,1] 351 | n_dim = tensor.dim() 352 | if n_dim == 4: 353 | n_img = len(tensor) 354 | img_np = make_grid(tensor, nrow=int(math.sqrt(n_img)), normalize=False).numpy() 355 | img_np = np.transpose(img_np[[2, 1, 0], :, :], (1, 2, 0)) # HWC, BGR 356 | elif n_dim == 3: 357 | img_np = tensor.numpy() 358 | img_np = np.transpose(img_np[[2, 1, 0], :, :], (1, 2, 0)) # HWC, BGR 359 | elif n_dim == 2: 360 | img_np = tensor.numpy() 361 | else: 362 | raise TypeError( 363 | 'Only support 4D, 3D and 2D tensor. But received with dimension: {:d}'.format(n_dim)) 364 | if out_type == np.uint8: 365 | img_np = (img_np * 255.0).round() 366 | # Important. Unlike matlab, numpy.unit8() WILL NOT round by default. 367 | return img_np.astype(out_type) 368 | 369 | 370 | ''' 371 | # -------------------------------------------- 372 | # Augmentation, flipe and/or rotate 373 | # -------------------------------------------- 374 | # The following two are enough. 375 | # (1) augmet_img: numpy image of WxHxC or WxH 376 | # (2) augment_img_tensor4: tensor image 1xCxWxH 377 | # -------------------------------------------- 378 | ''' 379 | 380 | 381 | def augment_img(img, mode=0): 382 | '''Kai Zhang (github: https://github.com/cszn) 383 | ''' 384 | if mode == 0: 385 | return img 386 | elif mode == 1: 387 | return np.flipud(np.rot90(img)) 388 | elif mode == 2: 389 | return np.flipud(img) 390 | elif mode == 3: 391 | return np.rot90(img, k=3) 392 | elif mode == 4: 393 | return np.flipud(np.rot90(img, k=2)) 394 | elif mode == 5: 395 | return np.rot90(img) 396 | elif mode == 6: 397 | return np.rot90(img, k=2) 398 | elif mode == 7: 399 | return np.flipud(np.rot90(img, k=3)) 400 | 401 | 402 | def augment_img_tensor4(img, mode=0): 403 | '''Kai Zhang (github: https://github.com/cszn) 404 | ''' 405 | if mode == 0: 406 | return img 407 | elif mode == 1: 408 | return img.rot90(1, [2, 3]).flip([2]) 409 | elif mode == 2: 410 | return img.flip([2]) 411 | elif mode == 3: 412 | return img.rot90(3, [2, 3]) 413 | elif mode == 4: 414 | return img.rot90(2, [2, 3]).flip([2]) 415 | elif mode == 5: 416 | return img.rot90(1, [2, 3]) 417 | elif mode == 6: 418 | return img.rot90(2, [2, 3]) 419 | elif mode == 7: 420 | return img.rot90(3, [2, 3]).flip([2]) 421 | 422 | 423 | def augment_img_tensor(img, mode=0): 424 | '''Kai Zhang (github: https://github.com/cszn) 425 | ''' 426 | img_size = img.size() 427 | img_np = img.data.cpu().numpy() 428 | if len(img_size) == 3: 429 | img_np = np.transpose(img_np, (1, 2, 0)) 430 | elif len(img_size) == 4: 431 | img_np = np.transpose(img_np, (2, 3, 1, 0)) 432 | img_np = augment_img(img_np, mode=mode) 433 | img_tensor = torch.from_numpy(np.ascontiguousarray(img_np)) 434 | if len(img_size) == 3: 435 | img_tensor = img_tensor.permute(2, 0, 1) 436 | elif len(img_size) == 4: 437 | img_tensor = img_tensor.permute(3, 2, 0, 1) 438 | 439 | return img_tensor.type_as(img) 440 | 441 | 442 | def augment_img_np3(img, mode=0): 443 | if mode == 0: 444 | return img 445 | elif mode == 1: 446 | return img.transpose(1, 0, 2) 447 | elif mode == 2: 448 | return img[::-1, :, :] 449 | elif mode == 3: 450 | img = img[::-1, :, :] 451 | img = img.transpose(1, 0, 2) 452 | return img 453 | elif mode == 4: 454 | return img[:, ::-1, :] 455 | elif mode == 5: 456 | img = img[:, ::-1, :] 457 | img = img.transpose(1, 0, 2) 458 | return img 459 | elif mode == 6: 460 | img = img[:, ::-1, :] 461 | img = img[::-1, :, :] 462 | return img 463 | elif mode == 7: 464 | img = img[:, ::-1, :] 465 | img = img[::-1, :, :] 466 | img = img.transpose(1, 0, 2) 467 | return img 468 | 469 | 470 | def augment_imgs(img_list, hflip=True, rot=True): 471 | # horizontal flip OR rotate 472 | hflip = hflip and random.random() < 0.5 473 | vflip = rot and random.random() < 0.5 474 | rot90 = rot and random.random() < 0.5 475 | 476 | def _augment(img): 477 | if hflip: 478 | img = img[:, ::-1, :] 479 | if vflip: 480 | img = img[::-1, :, :] 481 | if rot90: 482 | img = img.transpose(1, 0, 2) 483 | return img 484 | 485 | return [_augment(img) for img in img_list] 486 | 487 | 488 | ''' 489 | # -------------------------------------------- 490 | # modcrop and shave 491 | # -------------------------------------------- 492 | ''' 493 | 494 | 495 | def modcrop(img_in, scale): 496 | # img_in: Numpy, HWC or HW 497 | img = np.copy(img_in) 498 | if img.ndim == 2: 499 | H, W = img.shape 500 | H_r, W_r = H % scale, W % scale 501 | img = img[:H - H_r, :W - W_r] 502 | elif img.ndim == 3: 503 | H, W, C = img.shape 504 | H_r, W_r = H % scale, W % scale 505 | img = img[:H - H_r, :W - W_r, :] 506 | else: 507 | raise ValueError('Wrong img ndim: [{:d}].'.format(img.ndim)) 508 | return img 509 | 510 | 511 | def shave(img_in, border=0): 512 | # img_in: Numpy, HWC or HW 513 | img = np.copy(img_in) 514 | h, w = img.shape[:2] 515 | img = img[border:h-border, border:w-border] 516 | return img 517 | 518 | 519 | ''' 520 | # -------------------------------------------- 521 | # image processing process on numpy image 522 | # channel_convert(in_c, tar_type, img_list): 523 | # rgb2ycbcr(img, only_y=True): 524 | # bgr2ycbcr(img, only_y=True): 525 | # ycbcr2rgb(img): 526 | # -------------------------------------------- 527 | ''' 528 | 529 | 530 | def rgb2ycbcr(img, only_y=True): 531 | '''same as matlab rgb2ycbcr 532 | only_y: only return Y channel 533 | Input: 534 | uint8, [0, 255] 535 | float, [0, 1] 536 | ''' 537 | in_img_type = img.dtype 538 | img.astype(np.float32) 539 | if in_img_type != np.uint8: 540 | img *= 255. 541 | # convert 542 | if only_y: 543 | rlt = np.dot(img, [65.481, 128.553, 24.966]) / 255.0 + 16.0 544 | else: 545 | rlt = np.matmul(img, [[65.481, -37.797, 112.0], [128.553, -74.203, -93.786], 546 | [24.966, 112.0, -18.214]]) / 255.0 + [16, 128, 128] 547 | if in_img_type == np.uint8: 548 | rlt = rlt.round() 549 | else: 550 | rlt /= 255. 551 | return rlt.astype(in_img_type) 552 | 553 | 554 | def ycbcr2rgb(img): 555 | '''same as matlab ycbcr2rgb 556 | Input: 557 | uint8, [0, 255] 558 | float, [0, 1] 559 | ''' 560 | in_img_type = img.dtype 561 | img.astype(np.float32) 562 | if in_img_type != np.uint8: 563 | img *= 255. 564 | # convert 565 | rlt = np.matmul(img, [[0.00456621, 0.00456621, 0.00456621], [0, -0.00153632, 0.00791071], 566 | [0.00625893, -0.00318811, 0]]) * 255.0 + [-222.921, 135.576, -276.836] 567 | if in_img_type == np.uint8: 568 | rlt = rlt.round() 569 | else: 570 | rlt /= 255. 571 | return rlt.astype(in_img_type) 572 | 573 | 574 | def bgr2ycbcr(img, only_y=True): 575 | '''bgr version of rgb2ycbcr 576 | only_y: only return Y channel 577 | Input: 578 | uint8, [0, 255] 579 | float, [0, 1] 580 | ''' 581 | in_img_type = img.dtype 582 | img.astype(np.float32) 583 | if in_img_type != np.uint8: 584 | img *= 255. 585 | # convert 586 | if only_y: 587 | rlt = np.dot(img, [24.966, 128.553, 65.481]) / 255.0 + 16.0 588 | else: 589 | rlt = np.matmul(img, [[24.966, 112.0, -18.214], [128.553, -74.203, -93.786], 590 | [65.481, -37.797, 112.0]]) / 255.0 + [16, 128, 128] 591 | if in_img_type == np.uint8: 592 | rlt = rlt.round() 593 | else: 594 | rlt /= 255. 595 | return rlt.astype(in_img_type) 596 | 597 | 598 | def channel_convert(in_c, tar_type, img_list): 599 | # conversion among BGR, gray and y 600 | if in_c == 3 and tar_type == 'gray': # BGR to gray 601 | gray_list = [cv2.cvtColor(img, cv2.COLOR_BGR2GRAY) for img in img_list] 602 | return [np.expand_dims(img, axis=2) for img in gray_list] 603 | elif in_c == 3 and tar_type == 'y': # BGR to y 604 | y_list = [bgr2ycbcr(img, only_y=True) for img in img_list] 605 | return [np.expand_dims(img, axis=2) for img in y_list] 606 | elif in_c == 1 and tar_type == 'RGB': # gray/y to BGR 607 | return [cv2.cvtColor(img, cv2.COLOR_GRAY2BGR) for img in img_list] 608 | else: 609 | return img_list 610 | 611 | 612 | ''' 613 | # -------------------------------------------- 614 | # metric, PSNR and SSIM 615 | # -------------------------------------------- 616 | ''' 617 | 618 | 619 | # -------------------------------------------- 620 | # PSNR 621 | # -------------------------------------------- 622 | def calculate_psnr(img1, img2, border=0): 623 | # img1 and img2 have range [0, 255] 624 | #img1 = img1.squeeze() 625 | #img2 = img2.squeeze() 626 | if not img1.shape == img2.shape: 627 | raise ValueError('Input images must have the same dimensions.') 628 | h, w = img1.shape[:2] 629 | img1 = img1[border:h-border, border:w-border] 630 | img2 = img2[border:h-border, border:w-border] 631 | 632 | img1 = img1.astype(np.float64) 633 | img2 = img2.astype(np.float64) 634 | mse = np.mean((img1 - img2)**2) 635 | if mse == 0: 636 | return float('inf') 637 | return 20 * math.log10(255.0 / math.sqrt(mse)) 638 | 639 | 640 | # -------------------------------------------- 641 | # SSIM 642 | # -------------------------------------------- 643 | def calculate_ssim(img1, img2, border=0): 644 | '''calculate SSIM 645 | the same outputs as MATLAB's 646 | img1, img2: [0, 255] 647 | ''' 648 | #img1 = img1.squeeze() 649 | #img2 = img2.squeeze() 650 | if not img1.shape == img2.shape: 651 | raise ValueError('Input images must have the same dimensions.') 652 | h, w = img1.shape[:2] 653 | img1 = img1[border:h-border, border:w-border] 654 | img2 = img2[border:h-border, border:w-border] 655 | 656 | if img1.ndim == 2: 657 | return ssim(img1, img2) 658 | elif img1.ndim == 3: 659 | if img1.shape[2] == 3: 660 | ssims = [] 661 | for i in range(3): 662 | ssims.append(ssim(img1[:,:,i], img2[:,:,i])) 663 | return np.array(ssims).mean() 664 | elif img1.shape[2] == 1: 665 | return ssim(np.squeeze(img1), np.squeeze(img2)) 666 | else: 667 | raise ValueError('Wrong input image dimensions.') 668 | 669 | 670 | def ssim(img1, img2): 671 | C1 = (0.01 * 255)**2 672 | C2 = (0.03 * 255)**2 673 | 674 | img1 = img1.astype(np.float64) 675 | img2 = img2.astype(np.float64) 676 | kernel = cv2.getGaussianKernel(11, 1.5) 677 | window = np.outer(kernel, kernel.transpose()) 678 | 679 | mu1 = cv2.filter2D(img1, -1, window)[5:-5, 5:-5] # valid 680 | mu2 = cv2.filter2D(img2, -1, window)[5:-5, 5:-5] 681 | mu1_sq = mu1**2 682 | mu2_sq = mu2**2 683 | mu1_mu2 = mu1 * mu2 684 | sigma1_sq = cv2.filter2D(img1**2, -1, window)[5:-5, 5:-5] - mu1_sq 685 | sigma2_sq = cv2.filter2D(img2**2, -1, window)[5:-5, 5:-5] - mu2_sq 686 | sigma12 = cv2.filter2D(img1 * img2, -1, window)[5:-5, 5:-5] - mu1_mu2 687 | 688 | ssim_map = ((2 * mu1_mu2 + C1) * (2 * sigma12 + C2)) / ((mu1_sq + mu2_sq + C1) * 689 | (sigma1_sq + sigma2_sq + C2)) 690 | return ssim_map.mean() 691 | 692 | 693 | ''' 694 | # -------------------------------------------- 695 | # matlab's bicubic imresize (numpy and torch) [0, 1] 696 | # -------------------------------------------- 697 | ''' 698 | 699 | 700 | # matlab 'imresize' function, now only support 'bicubic' 701 | def cubic(x): 702 | absx = torch.abs(x) 703 | absx2 = absx**2 704 | absx3 = absx**3 705 | return (1.5*absx3 - 2.5*absx2 + 1) * ((absx <= 1).type_as(absx)) + \ 706 | (-0.5*absx3 + 2.5*absx2 - 4*absx + 2) * (((absx > 1)*(absx <= 2)).type_as(absx)) 707 | 708 | 709 | def calculate_weights_indices(in_length, out_length, scale, kernel, kernel_width, antialiasing): 710 | if (scale < 1) and (antialiasing): 711 | # Use a modified kernel to simultaneously interpolate and antialias- larger kernel width 712 | kernel_width = kernel_width / scale 713 | 714 | # Output-space coordinates 715 | x = torch.linspace(1, out_length, out_length) 716 | 717 | # Input-space coordinates. Calculate the inverse mapping such that 0.5 718 | # in output space maps to 0.5 in input space, and 0.5+scale in output 719 | # space maps to 1.5 in input space. 720 | u = x / scale + 0.5 * (1 - 1 / scale) 721 | 722 | # What is the left-most pixel that can be involved in the computation? 723 | left = torch.floor(u - kernel_width / 2) 724 | 725 | # What is the maximum number of pixels that can be involved in the 726 | # computation? Note: it's OK to use an extra pixel here; if the 727 | # corresponding weights are all zero, it will be eliminated at the end 728 | # of this function. 729 | P = math.ceil(kernel_width) + 2 730 | 731 | # The indices of the input pixels involved in computing the k-th output 732 | # pixel are in row k of the indices matrix. 733 | indices = left.view(out_length, 1).expand(out_length, P) + torch.linspace(0, P - 1, P).view( 734 | 1, P).expand(out_length, P) 735 | 736 | # The weights used to compute the k-th output pixel are in row k of the 737 | # weights matrix. 738 | distance_to_center = u.view(out_length, 1).expand(out_length, P) - indices 739 | # apply cubic kernel 740 | if (scale < 1) and (antialiasing): 741 | weights = scale * cubic(distance_to_center * scale) 742 | else: 743 | weights = cubic(distance_to_center) 744 | # Normalize the weights matrix so that each row sums to 1. 745 | weights_sum = torch.sum(weights, 1).view(out_length, 1) 746 | weights = weights / weights_sum.expand(out_length, P) 747 | 748 | # If a column in weights is all zero, get rid of it. only consider the first and last column. 749 | weights_zero_tmp = torch.sum((weights == 0), 0) 750 | if not math.isclose(weights_zero_tmp[0], 0, rel_tol=1e-6): 751 | indices = indices.narrow(1, 1, P - 2) 752 | weights = weights.narrow(1, 1, P - 2) 753 | if not math.isclose(weights_zero_tmp[-1], 0, rel_tol=1e-6): 754 | indices = indices.narrow(1, 0, P - 2) 755 | weights = weights.narrow(1, 0, P - 2) 756 | weights = weights.contiguous() 757 | indices = indices.contiguous() 758 | sym_len_s = -indices.min() + 1 759 | sym_len_e = indices.max() - in_length 760 | indices = indices + sym_len_s - 1 761 | return weights, indices, int(sym_len_s), int(sym_len_e) 762 | 763 | 764 | # -------------------------------------------- 765 | # imresize for tensor image [0, 1] 766 | # -------------------------------------------- 767 | def imresize(img, scale, antialiasing=True): 768 | # Now the scale should be the same for H and W 769 | # input: img: pytorch tensor, CHW or HW [0,1] 770 | # output: CHW or HW [0,1] w/o round 771 | need_squeeze = True if img.dim() == 2 else False 772 | if need_squeeze: 773 | img.unsqueeze_(0) 774 | in_C, in_H, in_W = img.size() 775 | out_C, out_H, out_W = in_C, math.ceil(in_H * scale), math.ceil(in_W * scale) 776 | kernel_width = 4 777 | kernel = 'cubic' 778 | 779 | # Return the desired dimension order for performing the resize. The 780 | # strategy is to perform the resize first along the dimension with the 781 | # smallest scale factor. 782 | # Now we do not support this. 783 | 784 | # get weights and indices 785 | weights_H, indices_H, sym_len_Hs, sym_len_He = calculate_weights_indices( 786 | in_H, out_H, scale, kernel, kernel_width, antialiasing) 787 | weights_W, indices_W, sym_len_Ws, sym_len_We = calculate_weights_indices( 788 | in_W, out_W, scale, kernel, kernel_width, antialiasing) 789 | # process H dimension 790 | # symmetric copying 791 | img_aug = torch.FloatTensor(in_C, in_H + sym_len_Hs + sym_len_He, in_W) 792 | img_aug.narrow(1, sym_len_Hs, in_H).copy_(img) 793 | 794 | sym_patch = img[:, :sym_len_Hs, :] 795 | inv_idx = torch.arange(sym_patch.size(1) - 1, -1, -1).long() 796 | sym_patch_inv = sym_patch.index_select(1, inv_idx) 797 | img_aug.narrow(1, 0, sym_len_Hs).copy_(sym_patch_inv) 798 | 799 | sym_patch = img[:, -sym_len_He:, :] 800 | inv_idx = torch.arange(sym_patch.size(1) - 1, -1, -1).long() 801 | sym_patch_inv = sym_patch.index_select(1, inv_idx) 802 | img_aug.narrow(1, sym_len_Hs + in_H, sym_len_He).copy_(sym_patch_inv) 803 | 804 | out_1 = torch.FloatTensor(in_C, out_H, in_W) 805 | kernel_width = weights_H.size(1) 806 | for i in range(out_H): 807 | idx = int(indices_H[i][0]) 808 | for j in range(out_C): 809 | out_1[j, i, :] = img_aug[j, idx:idx + kernel_width, :].transpose(0, 1).mv(weights_H[i]) 810 | 811 | # process W dimension 812 | # symmetric copying 813 | out_1_aug = torch.FloatTensor(in_C, out_H, in_W + sym_len_Ws + sym_len_We) 814 | out_1_aug.narrow(2, sym_len_Ws, in_W).copy_(out_1) 815 | 816 | sym_patch = out_1[:, :, :sym_len_Ws] 817 | inv_idx = torch.arange(sym_patch.size(2) - 1, -1, -1).long() 818 | sym_patch_inv = sym_patch.index_select(2, inv_idx) 819 | out_1_aug.narrow(2, 0, sym_len_Ws).copy_(sym_patch_inv) 820 | 821 | sym_patch = out_1[:, :, -sym_len_We:] 822 | inv_idx = torch.arange(sym_patch.size(2) - 1, -1, -1).long() 823 | sym_patch_inv = sym_patch.index_select(2, inv_idx) 824 | out_1_aug.narrow(2, sym_len_Ws + in_W, sym_len_We).copy_(sym_patch_inv) 825 | 826 | out_2 = torch.FloatTensor(in_C, out_H, out_W) 827 | kernel_width = weights_W.size(1) 828 | for i in range(out_W): 829 | idx = int(indices_W[i][0]) 830 | for j in range(out_C): 831 | out_2[j, :, i] = out_1_aug[j, :, idx:idx + kernel_width].mv(weights_W[i]) 832 | if need_squeeze: 833 | out_2.squeeze_() 834 | return out_2 835 | 836 | 837 | # -------------------------------------------- 838 | # imresize for numpy image [0, 1] 839 | # -------------------------------------------- 840 | def imresize_np(img, scale, antialiasing=True): 841 | # Now the scale should be the same for H and W 842 | # input: img: Numpy, HWC or HW [0,1] 843 | # output: HWC or HW [0,1] w/o round 844 | img = torch.from_numpy(img) 845 | need_squeeze = True if img.dim() == 2 else False 846 | if need_squeeze: 847 | img.unsqueeze_(2) 848 | 849 | in_H, in_W, in_C = img.size() 850 | out_C, out_H, out_W = in_C, math.ceil(in_H * scale), math.ceil(in_W * scale) 851 | kernel_width = 4 852 | kernel = 'cubic' 853 | 854 | # Return the desired dimension order for performing the resize. The 855 | # strategy is to perform the resize first along the dimension with the 856 | # smallest scale factor. 857 | # Now we do not support this. 858 | 859 | # get weights and indices 860 | weights_H, indices_H, sym_len_Hs, sym_len_He = calculate_weights_indices( 861 | in_H, out_H, scale, kernel, kernel_width, antialiasing) 862 | weights_W, indices_W, sym_len_Ws, sym_len_We = calculate_weights_indices( 863 | in_W, out_W, scale, kernel, kernel_width, antialiasing) 864 | # process H dimension 865 | # symmetric copying 866 | img_aug = torch.FloatTensor(in_H + sym_len_Hs + sym_len_He, in_W, in_C) 867 | img_aug.narrow(0, sym_len_Hs, in_H).copy_(img) 868 | 869 | sym_patch = img[:sym_len_Hs, :, :] 870 | inv_idx = torch.arange(sym_patch.size(0) - 1, -1, -1).long() 871 | sym_patch_inv = sym_patch.index_select(0, inv_idx) 872 | img_aug.narrow(0, 0, sym_len_Hs).copy_(sym_patch_inv) 873 | 874 | sym_patch = img[-sym_len_He:, :, :] 875 | inv_idx = torch.arange(sym_patch.size(0) - 1, -1, -1).long() 876 | sym_patch_inv = sym_patch.index_select(0, inv_idx) 877 | img_aug.narrow(0, sym_len_Hs + in_H, sym_len_He).copy_(sym_patch_inv) 878 | 879 | out_1 = torch.FloatTensor(out_H, in_W, in_C) 880 | kernel_width = weights_H.size(1) 881 | for i in range(out_H): 882 | idx = int(indices_H[i][0]) 883 | for j in range(out_C): 884 | out_1[i, :, j] = img_aug[idx:idx + kernel_width, :, j].transpose(0, 1).mv(weights_H[i]) 885 | 886 | # process W dimension 887 | # symmetric copying 888 | out_1_aug = torch.FloatTensor(out_H, in_W + sym_len_Ws + sym_len_We, in_C) 889 | out_1_aug.narrow(1, sym_len_Ws, in_W).copy_(out_1) 890 | 891 | sym_patch = out_1[:, :sym_len_Ws, :] 892 | inv_idx = torch.arange(sym_patch.size(1) - 1, -1, -1).long() 893 | sym_patch_inv = sym_patch.index_select(1, inv_idx) 894 | out_1_aug.narrow(1, 0, sym_len_Ws).copy_(sym_patch_inv) 895 | 896 | sym_patch = out_1[:, -sym_len_We:, :] 897 | inv_idx = torch.arange(sym_patch.size(1) - 1, -1, -1).long() 898 | sym_patch_inv = sym_patch.index_select(1, inv_idx) 899 | out_1_aug.narrow(1, sym_len_Ws + in_W, sym_len_We).copy_(sym_patch_inv) 900 | 901 | out_2 = torch.FloatTensor(out_H, out_W, in_C) 902 | kernel_width = weights_W.size(1) 903 | for i in range(out_W): 904 | idx = int(indices_W[i][0]) 905 | for j in range(out_C): 906 | out_2[:, i, j] = out_1_aug[:, idx:idx + kernel_width, j].mv(weights_W[i]) 907 | if need_squeeze: 908 | out_2.squeeze_() 909 | 910 | return out_2.numpy() 911 | 912 | 913 | if __name__ == '__main__': 914 | print('---') 915 | # img = imread_uint('test.bmp', 3) 916 | # img = uint2single(img) 917 | # img_bicubic = imresize_np(img, 1/4) 918 | 919 | 920 | 921 | 922 | 923 | 924 | 925 | -------------------------------------------------------------------------------- /utils/utils_logger.py: -------------------------------------------------------------------------------- 1 | import sys 2 | import datetime 3 | import logging 4 | 5 | 6 | ''' 7 | # -------------------------------------------- 8 | # Kai Zhang (github: https://github.com/cszn) 9 | # 03/Mar/2019 10 | # -------------------------------------------- 11 | # https://github.com/xinntao/BasicSR 12 | # -------------------------------------------- 13 | ''' 14 | 15 | 16 | def log(*args, **kwargs): 17 | print(datetime.datetime.now().strftime("%Y-%m-%d %H:%M:%S:"), *args, **kwargs) 18 | 19 | 20 | ''' 21 | # -------------------------------------------- 22 | # logger 23 | # -------------------------------------------- 24 | ''' 25 | 26 | 27 | def logger_info(logger_name, log_path='default_logger.log'): 28 | ''' set up logger 29 | modified by Kai Zhang (github: https://github.com/cszn) 30 | ''' 31 | log = logging.getLogger(logger_name) 32 | if log.hasHandlers(): 33 | print('LogHandlers exist!') 34 | else: 35 | print('LogHandlers setup!') 36 | level = logging.INFO 37 | formatter = logging.Formatter('%(asctime)s.%(msecs)03d : %(message)s', datefmt='%y-%m-%d %H:%M:%S') 38 | fh = logging.FileHandler(log_path, mode='a') 39 | fh.setFormatter(formatter) 40 | log.setLevel(level) 41 | log.addHandler(fh) 42 | # print(len(log.handlers)) 43 | 44 | sh = logging.StreamHandler() 45 | sh.setFormatter(formatter) 46 | log.addHandler(sh) 47 | 48 | 49 | ''' 50 | # -------------------------------------------- 51 | # print to file and std_out simultaneously 52 | # -------------------------------------------- 53 | ''' 54 | 55 | 56 | class logger_print(object): 57 | def __init__(self, log_path="default.log"): 58 | self.terminal = sys.stdout 59 | self.log = open(log_path, 'a') 60 | 61 | def write(self, message): 62 | self.terminal.write(message) 63 | self.log.write(message) # write the message 64 | 65 | def flush(self): 66 | pass 67 | -------------------------------------------------------------------------------- /utils/utils_model.py: -------------------------------------------------------------------------------- 1 | # -*- coding: utf-8 -*- 2 | import numpy as np 3 | import torch 4 | from utils import utils_image as util 5 | import re 6 | import glob 7 | import os 8 | 9 | 10 | ''' 11 | # -------------------------------------------- 12 | # Model 13 | # -------------------------------------------- 14 | # Kai Zhang (github: https://github.com/cszn) 15 | # 03/Mar/2019 16 | # -------------------------------------------- 17 | ''' 18 | 19 | 20 | def find_last_checkpoint(save_dir, net_type='G'): 21 | """ 22 | # --------------------------------------- 23 | # Kai Zhang (github: https://github.com/cszn) 24 | # 03/Mar/2019 25 | # --------------------------------------- 26 | Args: 27 | save_dir: model folder 28 | net_type: 'G' or 'D' 29 | 30 | Return: 31 | init_iter: iteration number 32 | init_path: model path 33 | # --------------------------------------- 34 | """ 35 | file_list = glob.glob(os.path.join(save_dir, '*_{}.pth'.format(net_type))) 36 | if file_list: 37 | iter_exist = [] 38 | for file_ in file_list: 39 | iter_current = re.findall(r"(\d+)_{}.pth".format(net_type), file_) 40 | iter_exist.append(int(iter_current[0])) 41 | init_iter = max(iter_exist) 42 | init_path = os.path.join(save_dir, '{}_{}.pth'.format(init_iter, net_type)) 43 | else: 44 | init_iter = 0 45 | init_path = None 46 | return init_iter, init_path 47 | 48 | 49 | def test_mode(model, L, mode=0, refield=32, min_size=256, sf=1, modulo=1): 50 | ''' 51 | # --------------------------------------- 52 | # Kai Zhang (github: https://github.com/cszn) 53 | # 03/Mar/2019 54 | # --------------------------------------- 55 | Args: 56 | model: trained model 57 | L: input Low-quality image 58 | mode: 59 | (0) normal: test(model, L) 60 | (1) pad: test_pad(model, L, modulo=16) 61 | (2) split: test_split(model, L, refield=32, min_size=256, sf=1, modulo=1) 62 | (3) x8: test_x8(model, L, modulo=1) ^_^ 63 | (4) split and x8: test_split_x8(model, L, refield=32, min_size=256, sf=1, modulo=1) 64 | refield: effective receptive filed of the network, 32 is enough 65 | useful when split, i.e., mode=2, 4 66 | min_size: min_sizeXmin_size image, e.g., 256X256 image 67 | useful when split, i.e., mode=2, 4 68 | sf: scale factor for super-resolution, otherwise 1 69 | modulo: 1 if split 70 | useful when pad, i.e., mode=1 71 | 72 | Returns: 73 | E: estimated image 74 | # --------------------------------------- 75 | ''' 76 | if mode == 0: 77 | E = test(model, L) 78 | elif mode == 1: 79 | E = test_pad(model, L, modulo, sf) 80 | elif mode == 2: 81 | E = test_split(model, L, refield, min_size, sf, modulo) 82 | elif mode == 3: 83 | E = test_x8(model, L, modulo, sf) 84 | elif mode == 4: 85 | E = test_split_x8(model, L, refield, min_size, sf, modulo) 86 | return E 87 | 88 | 89 | ''' 90 | # -------------------------------------------- 91 | # normal (0) 92 | # -------------------------------------------- 93 | ''' 94 | 95 | 96 | def test(model, L): 97 | E = model(L) 98 | return E 99 | 100 | 101 | ''' 102 | # -------------------------------------------- 103 | # pad (1) 104 | # -------------------------------------------- 105 | ''' 106 | 107 | 108 | def test_pad(model, L, modulo=16, sf=1): 109 | h, w = L.size()[-2:] 110 | paddingBottom = int(np.ceil(h/modulo)*modulo-h) 111 | paddingRight = int(np.ceil(w/modulo)*modulo-w) 112 | L = torch.nn.ReplicationPad2d((0, paddingRight, 0, paddingBottom))(L) 113 | E = model(L) 114 | E = E[..., :h*sf, :w*sf] 115 | return E 116 | 117 | 118 | ''' 119 | # -------------------------------------------- 120 | # split (function) 121 | # -------------------------------------------- 122 | ''' 123 | 124 | 125 | def test_split_fn(model, L, refield=32, min_size=256, sf=1, modulo=1): 126 | """ 127 | Args: 128 | model: trained model 129 | L: input Low-quality image 130 | refield: effective receptive filed of the network, 32 is enough 131 | min_size: min_sizeXmin_size image, e.g., 256X256 image 132 | sf: scale factor for super-resolution, otherwise 1 133 | modulo: 1 if split 134 | 135 | Returns: 136 | E: estimated result 137 | """ 138 | h, w = L.size()[-2:] 139 | if h*w <= min_size**2: 140 | L = torch.nn.ReplicationPad2d((0, int(np.ceil(w/modulo)*modulo-w), 0, int(np.ceil(h/modulo)*modulo-h)))(L) 141 | E = model(L) 142 | E = E[..., :h*sf, :w*sf] 143 | else: 144 | top = slice(0, (h//2//refield+1)*refield) 145 | bottom = slice(h - (h//2//refield+1)*refield, h) 146 | left = slice(0, (w//2//refield+1)*refield) 147 | right = slice(w - (w//2//refield+1)*refield, w) 148 | Ls = [L[..., top, left], L[..., top, right], L[..., bottom, left], L[..., bottom, right]] 149 | 150 | if h * w <= 4*(min_size**2): 151 | Es = [model(Ls[i]) for i in range(4)] 152 | else: 153 | Es = [test_split_fn(model, Ls[i], refield=refield, min_size=min_size, sf=sf, modulo=modulo) for i in range(4)] 154 | 155 | b, c = Es[0].size()[:2] 156 | E = torch.zeros(b, c, sf * h, sf * w).type_as(L) 157 | 158 | E[..., :h//2*sf, :w//2*sf] = Es[0][..., :h//2*sf, :w//2*sf] 159 | E[..., :h//2*sf, w//2*sf:w*sf] = Es[1][..., :h//2*sf, (-w + w//2)*sf:] 160 | E[..., h//2*sf:h*sf, :w//2*sf] = Es[2][..., (-h + h//2)*sf:, :w//2*sf] 161 | E[..., h//2*sf:h*sf, w//2*sf:w*sf] = Es[3][..., (-h + h//2)*sf:, (-w + w//2)*sf:] 162 | return E 163 | 164 | 165 | ''' 166 | # -------------------------------------------- 167 | # split (2) 168 | # -------------------------------------------- 169 | ''' 170 | 171 | 172 | def test_split(model, L, refield=32, min_size=256, sf=1, modulo=1): 173 | E = test_split_fn(model, L, refield=refield, min_size=min_size, sf=sf, modulo=modulo) 174 | return E 175 | 176 | 177 | ''' 178 | # -------------------------------------------- 179 | # x8 (3) 180 | # -------------------------------------------- 181 | ''' 182 | 183 | 184 | def test_x8(model, L, modulo=1, sf=1): 185 | E_list = [test_pad(model, util.augment_img_tensor4(L, mode=i), modulo=modulo, sf=sf) for i in range(8)] 186 | for i in range(len(E_list)): 187 | if i == 3 or i == 5: 188 | E_list[i] = util.augment_img_tensor4(E_list[i], mode=8 - i) 189 | else: 190 | E_list[i] = util.augment_img_tensor4(E_list[i], mode=i) 191 | output_cat = torch.stack(E_list, dim=0) 192 | E = output_cat.mean(dim=0, keepdim=False) 193 | return E 194 | 195 | 196 | ''' 197 | # -------------------------------------------- 198 | # split and x8 (4) 199 | # -------------------------------------------- 200 | ''' 201 | 202 | 203 | def test_split_x8(model, L, refield=32, min_size=256, sf=1, modulo=1): 204 | E_list = [test_split_fn(model, util.augment_img_tensor4(L, mode=i), refield=refield, min_size=min_size, sf=sf, modulo=modulo) for i in range(8)] 205 | for k, i in enumerate(range(len(E_list))): 206 | if i==3 or i==5: 207 | E_list[k] = util.augment_img_tensor4(E_list[k], mode=8-i) 208 | else: 209 | E_list[k] = util.augment_img_tensor4(E_list[k], mode=i) 210 | output_cat = torch.stack(E_list, dim=0) 211 | E = output_cat.mean(dim=0, keepdim=False) 212 | return E 213 | 214 | 215 | ''' 216 | # ^_^-^_^-^_^-^_^-^_^-^_^-^_^-^_^-^_^-^_^-^_^- 217 | # _^_^-^_^-^_^-^_^-^_^-^_^-^_^-^_^-^_^-^_^-^_^ 218 | # ^_^-^_^-^_^-^_^-^_^-^_^-^_^-^_^-^_^-^_^-^_^- 219 | ''' 220 | 221 | 222 | ''' 223 | # -------------------------------------------- 224 | # print 225 | # -------------------------------------------- 226 | ''' 227 | 228 | 229 | # -------------------------------------------- 230 | # print model 231 | # -------------------------------------------- 232 | def print_model(model): 233 | msg = describe_model(model) 234 | print(msg) 235 | 236 | 237 | # -------------------------------------------- 238 | # print params 239 | # -------------------------------------------- 240 | def print_params(model): 241 | msg = describe_params(model) 242 | print(msg) 243 | 244 | 245 | ''' 246 | # -------------------------------------------- 247 | # information 248 | # -------------------------------------------- 249 | ''' 250 | 251 | 252 | # -------------------------------------------- 253 | # model inforation 254 | # -------------------------------------------- 255 | def info_model(model): 256 | msg = describe_model(model) 257 | return msg 258 | 259 | 260 | # -------------------------------------------- 261 | # params inforation 262 | # -------------------------------------------- 263 | def info_params(model): 264 | msg = describe_params(model) 265 | return msg 266 | 267 | 268 | ''' 269 | # -------------------------------------------- 270 | # description 271 | # -------------------------------------------- 272 | ''' 273 | 274 | 275 | # -------------------------------------------- 276 | # model name and total number of parameters 277 | # -------------------------------------------- 278 | def describe_model(model): 279 | if isinstance(model, torch.nn.DataParallel): 280 | model = model.module 281 | msg = '\n' 282 | msg += 'models name: {}'.format(model.__class__.__name__) + '\n' 283 | msg += 'Params number: {}'.format(sum(map(lambda x: x.numel(), model.parameters()))) + '\n' 284 | msg += 'Net structure:\n{}'.format(str(model)) + '\n' 285 | return msg 286 | 287 | 288 | # -------------------------------------------- 289 | # parameters description 290 | # -------------------------------------------- 291 | def describe_params(model): 292 | if isinstance(model, torch.nn.DataParallel): 293 | model = model.module 294 | msg = '\n' 295 | msg += ' | {:^6s} | {:^6s} | {:^6s} | {:^6s} || {:<20s}'.format('mean', 'min', 'max', 'std', 'param_name') + '\n' 296 | for name, param in model.state_dict().items(): 297 | if not 'num_batches_tracked' in name: 298 | v = param.data.clone().float() 299 | msg += ' | {:>6.3f} | {:>6.3f} | {:>6.3f} | {:>6.3f} || {:s}'.format(v.mean(), v.min(), v.max(), v.std(), name) + '\n' 300 | return msg 301 | 302 | 303 | if __name__ == '__main__': 304 | 305 | class Net(torch.nn.Module): 306 | def __init__(self, in_channels=3, out_channels=3): 307 | super(Net, self).__init__() 308 | self.conv = torch.nn.Conv2d(in_channels=in_channels, out_channels=out_channels, kernel_size=3, padding=1) 309 | 310 | def forward(self, x): 311 | x = self.conv(x) 312 | return x 313 | 314 | start = torch.cuda.Event(enable_timing=True) 315 | end = torch.cuda.Event(enable_timing=True) 316 | 317 | model = Net() 318 | model = model.eval() 319 | print_model(model) 320 | print_params(model) 321 | x = torch.randn((2,3,401,401)) 322 | torch.cuda.empty_cache() 323 | with torch.no_grad(): 324 | for mode in range(5): 325 | y = test_mode(model, x, mode, refield=32, min_size=256, sf=1, modulo=1) 326 | print(y.shape) 327 | 328 | # run utils/utils_model.py --------------------------------------------------------------------------------