├── LICENSE ├── README.md ├── data_utils.py ├── edsr.py ├── images ├── BicubicOutput.png ├── EDSR.png ├── EdsrOutput.png ├── input.png └── original.png ├── main.py ├── models ├── EDSR_x2.pb ├── EDSR_x3.pb └── EDSR_x4.pb ├── requirements.txt └── run.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 [yyyy] [name of copyright owner] 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 | # EDSR in Tensorflow 2 | 3 | TensorFlow implementation of [Enhanced Deep Residual Networks for Single Image Super-Resolution](https://arxiv.org/pdf/1707.02921.pdf)[1]. 4 | 5 | It was trained on the [Div2K dataset](https://data.vision.ee.ethz.ch/cvl/DIV2K/) - Train Data (HR images). 6 | 7 | ## Google Summer of Code with OpenCV 8 | This repository was made during the 2019 GSoC program for the organization OpenCV. The [trained models (.pb files)](https://github.com/Saafke/EDSR_Tensorflow/tree/master/models/) can easily be used for inference in OpenCV with the ['dnn_superres' module](https://github.com/opencv/opencv_contrib/tree/master/modules/dnn_superres). See the OpenCV documentation for how to do this. 9 | 10 | ## Requirements 11 | - tensorflow 12 | - numpy 13 | - cv2 14 | 15 | ## EDSR 16 | This is the EDSR model, which has a different model for each scale. Architecture shown below. Go to branch 'mdsr' for the MDSR model. 17 | 18 | ![Alt text](images/EDSR.png?raw=true "EDSR architecture") 19 | 20 | # Running 21 | Download [Div2K dataset](https://data.vision.ee.ethz.ch/cvl/DIV2K/). If you want to use another dataset, you will have to calculate the mean of that dataset, and set the new mean in 'main.py'. Code for calculating the mean can be found in data_utils.py. 22 | 23 | Train: 24 | - from scratch 25 | `python main.py --train --fromscratch --scale --traindir /path-to-train-images/` 26 | 27 | - resume/load previous 28 | `python main.py --train --scale --traindir /path-to-train-images/` 29 | 30 | Test (compares edsr with bicubic with PSNR metric): 31 | `python main.py --test --scale --image /path-to-image/` 32 | 33 | Upscale (with edsr): 34 | `python main.py --upscale --scale --image /path-to-image/` 35 | 36 | Export to .pb 37 | `python main.py --export --scale ` 38 | 39 | Extra arguments (Nr of resblocks, filters, batch, lr etc.) 40 | `python main.py --help` 41 | 42 | ## Example 43 | (1) Original picture\ 44 | (2) Input image\ 45 | (3) Bicubic scaled (3x) image\ 46 | (4) EDSR scaled (3x) image\ 47 | ![Alt text](images/original.png?raw=true "Original picture") 48 | ![Alt text](images/input.png?raw=true "Input image picture") 49 | ![Alt text](images/BicubicOutput.png?raw=true "Bicubic picture") 50 | ![Alt text](images/EdsrOutput.png?raw=true "EDSR picture") 51 | 52 | ## Notes 53 | The .pb files in these repository are quantized. This is done purely to shrink the filesizes down from ~150MB to ~40MB, because GitHub does not allow uploads above 100MB. The performance loss due to quantization is minimal. (To quantize during exporting use $ --quant <1,2 or 3> (2 is recommended.)) 54 | 55 | ## References 56 | [1] Bee Lim, Sanghyun Son, Heewon Kim, Seungjun Nah, and Kyoung Mu Lee, **"Enhanced Deep Residual Networks for Single Image Super-Resolution,"** 2nd NTIRE: New Trends in Image Restoration and Enhancement workshop and challenge on image super-resolution in conjunction with **CVPR 2017**. [[PDF](http://openaccess.thecvf.com/content_cvpr_2017_workshops/w12/papers/Lim_Enhanced_Deep_Residual_CVPR_2017_paper.pdf)] [[arXiv](https://arxiv.org/abs/1707.02921)] [[Slide](https://cv.snu.ac.kr/research/EDSR/Presentation_v3(release).pptx)] 57 | -------------------------------------------------------------------------------- /data_utils.py: -------------------------------------------------------------------------------- 1 | import pathlib 2 | import os 3 | from PIL import Image 4 | import numpy as np 5 | import cv2 6 | import tensorflow as tf 7 | import random 8 | 9 | def getpathsx(path): 10 | """ 11 | Get all image paths from folder 'path'. 12 | """ 13 | data = pathlib.Path(path) 14 | all_image_paths = list(data.glob('*')) 15 | all_image_paths = [str(p) for p in all_image_paths] 16 | return all_image_paths 17 | 18 | def getpaths(path): 19 | """ 20 | Get all image paths from folder 'path' while avoiding ._ files. 21 | """ 22 | im_paths = [] 23 | for fil in os.listdir(path): 24 | if '.png' in fil: 25 | if "._" in fil: 26 | #avoid dot underscore 27 | pass 28 | else: 29 | im_paths.append(os.path.join(path, fil)) 30 | return im_paths 31 | 32 | def make_val_dataset(paths, scale, mean): 33 | """ 34 | Python generator-style dataset for the validation set. Creates input and ground truth. 35 | """ 36 | for p in paths: 37 | # normalize 38 | im_norm = cv2.imread(p.decode(), 3).astype(np.float32) - mean 39 | 40 | # divisible by scale - create low-res 41 | hr = im_norm[0:(im_norm.shape[0] - (im_norm.shape[0] % scale)), 42 | 0:(im_norm.shape[1] - (im_norm.shape[1] % scale)), :] 43 | lr = cv2.resize(hr, (int(hr.shape[1] / scale), int(hr.shape[0] / scale)), 44 | interpolation=cv2.INTER_CUBIC) 45 | 46 | yield lr, hr 47 | 48 | def make_dataset(paths, scale, mean): 49 | """ 50 | Python generator-style dataset. Creates 48x48 low-res and corresponding high-res patches. 51 | """ 52 | size_lr = 48 53 | size_hr = size_lr * scale 54 | 55 | for p in paths: 56 | # normalize 57 | im_norm = cv2.imread(p.decode(), 3).astype(np.float32) - mean 58 | 59 | # random flip 60 | r = random.randint(-1, 2) 61 | if not r == 2: 62 | im_norm = cv2.flip(im_norm, r) 63 | 64 | # divisible by scale - create low-res 65 | hr = im_norm[0:(im_norm.shape[0] - (im_norm.shape[0] % scale)), 66 | 0:(im_norm.shape[1] - (im_norm.shape[1] % scale)), :] 67 | lr = cv2.resize(hr, (int(hr.shape[1] / scale), int(hr.shape[0] / scale)), 68 | interpolation=cv2.INTER_CUBIC) 69 | 70 | numx = int(lr.shape[0] / size_lr) 71 | numy = int(lr.shape[1] / size_lr) 72 | 73 | for i in range(0, numx): 74 | startx = i * size_lr 75 | endx = (i * size_lr) + size_lr 76 | 77 | startx_hr = i * size_hr 78 | endx_hr = (i * size_hr) + size_hr 79 | 80 | for j in range(0, numy): 81 | starty = j * size_lr 82 | endy = (j * size_lr) + size_lr 83 | starty_hr = j * size_hr 84 | endy_hr = (j * size_hr) + size_hr 85 | 86 | crop_lr = lr[startx:endx, starty:endy] 87 | crop_hr = hr[startx_hr:endx_hr, starty_hr:endy_hr] 88 | 89 | x = crop_lr.reshape((size_lr, size_lr, 3)) 90 | y = crop_hr.reshape((size_hr, size_hr, 3)) 91 | 92 | yield x, y 93 | 94 | def calcmean(imageFolder, bgr): 95 | """ 96 | Calculates the mean of a dataset. 97 | """ 98 | paths = getpaths(imageFolder) 99 | 100 | total_mean = [0, 0, 0] 101 | im_counter = 0 102 | 103 | for p in paths: 104 | 105 | image = np.asarray(Image.open(p)) 106 | 107 | mean_rgb = np.mean(image, axis=(0, 1), dtype=np.float64) 108 | 109 | if im_counter % 50 == 0: 110 | print("Total mean: {} | current mean: {}".format(total_mean, mean_rgb)) 111 | 112 | total_mean += mean_rgb 113 | im_counter += 1 114 | 115 | total_mean /= im_counter 116 | 117 | # rgb to bgr 118 | if bgr is True: 119 | total_mean = total_mean[...,::-1] 120 | 121 | return total_mean -------------------------------------------------------------------------------- /edsr.py: -------------------------------------------------------------------------------- 1 | from __future__ import print_function 2 | 3 | import cv2 4 | import tensorflow as tf 5 | import numpy as np 6 | import os 7 | 8 | class Edsr: 9 | 10 | def __init__(self, B, F, scale): 11 | self.B = B 12 | self.F = F 13 | self.scale = scale 14 | self.global_step = tf.placeholder(tf.int32, shape=[], name="global_step") 15 | self.scaling_factor = 0.1 16 | self.bias_initializer = tf.constant_initializer(value=0.0) 17 | self.PS = 3 * (scale*scale) #channels x scale^2 18 | self.xavier = tf.contrib.layers.xavier_initializer() 19 | 20 | # -- Filters & Biases -- 21 | self.resFilters = list() 22 | self.resBiases = list() 23 | 24 | for i in range(0, B*2): 25 | self.resFilters.append( tf.get_variable("resFilter%d" % (i), shape=[3,3,F,F], initializer=self.xavier)) 26 | self.resBiases.append(tf.get_variable(name="resBias%d" % (i), shape=[F], initializer=self.bias_initializer)) 27 | 28 | self.filter_one = tf.get_variable("resFilter_one", shape=[3,3,3,F], initializer=self.xavier) 29 | self.filter_two = tf.get_variable("resFilter_two", shape=[3,3,F,F], initializer=self.xavier) 30 | self.filter_three = tf.get_variable("resFilter_three", shape=[3,3,F,self.PS], initializer=self.xavier) 31 | 32 | self.bias_one = tf.get_variable(shape=[F], initializer=self.bias_initializer, name="BiasOne") 33 | self.bias_two = tf.get_variable(shape=[F], initializer=self.bias_initializer, name="BiasTwo") 34 | self.bias_three = tf.get_variable(shape=[self.PS], initializer=self.bias_initializer, name="BiasThree") 35 | 36 | 37 | def model(self, x, y, lr): 38 | """ 39 | Implementation of EDSR: https://arxiv.org/abs/1707.02921. 40 | """ 41 | 42 | # -- Model architecture -- 43 | 44 | # first conv 45 | x = tf.nn.conv2d(x, filter=self.filter_one, strides=[1, 1, 1, 1], padding='SAME') 46 | x = x + self.bias_one 47 | out1 = tf.identity(x) 48 | 49 | # all residual blocks 50 | for i in range(self.B): 51 | x = self.resBlock(x, (i*2)) 52 | 53 | # last conv 54 | x = tf.nn.conv2d(x, filter=self.filter_two, strides=[1, 1, 1, 1], padding='SAME') 55 | x = x + self.bias_two 56 | x = x + out1 57 | 58 | # upsample via sub-pixel, equivalent to depth to space 59 | x = tf.nn.conv2d(x, filter=self.filter_three, strides=[1, 1, 1, 1], padding='SAME') 60 | x = x + self.bias_three 61 | out = tf.nn.depth_to_space(x, self.scale, data_format='NHWC', name="NHWC_output") 62 | 63 | # -- -- 64 | 65 | # some outputs 66 | out_nchw = tf.transpose(out, [0, 3, 1, 2], name="NCHW_output") 67 | psnr = tf.image.psnr(out, y, max_val=255.0) 68 | loss = tf.losses.absolute_difference(out, y) #L1 69 | ssim = tf.image.ssim(out, y, max_val=255.0) 70 | 71 | # (decaying) learning rate 72 | lr = tf.train.exponential_decay(lr, 73 | self.global_step, 74 | decay_steps=15000, 75 | decay_rate=0.95, 76 | staircase=True) 77 | # gradient clipping 78 | optimizer = tf.train.AdamOptimizer(lr) 79 | gradients, variables = zip(*optimizer.compute_gradients(loss)) 80 | gradients, _ = tf.clip_by_global_norm(gradients, 5.0) 81 | train_op = optimizer.apply_gradients(zip(gradients, variables)) 82 | 83 | return out, loss, train_op, psnr, ssim, lr 84 | 85 | def resBlock(self, inpt, f_nr): 86 | x = tf.nn.conv2d(inpt, filter=self.resFilters[f_nr], strides=[1, 1, 1, 1], padding='SAME') 87 | x = x + self.resBiases[f_nr] 88 | x = tf.nn.relu(x) 89 | 90 | x = tf.nn.conv2d(x, filter=self.resFilters[f_nr+1], strides=[1, 1, 1, 1], padding='SAME') 91 | x = x + self.resBiases[f_nr+1] 92 | x = x * self.scaling_factor 93 | 94 | return inpt + x -------------------------------------------------------------------------------- /images/BicubicOutput.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/Saafke/EDSR_Tensorflow/06c7bd65b0305c2955328f8f2721ea86c341f660/images/BicubicOutput.png -------------------------------------------------------------------------------- /images/EDSR.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/Saafke/EDSR_Tensorflow/06c7bd65b0305c2955328f8f2721ea86c341f660/images/EDSR.png -------------------------------------------------------------------------------- /images/EdsrOutput.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/Saafke/EDSR_Tensorflow/06c7bd65b0305c2955328f8f2721ea86c341f660/images/EdsrOutput.png -------------------------------------------------------------------------------- /images/input.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/Saafke/EDSR_Tensorflow/06c7bd65b0305c2955328f8f2721ea86c341f660/images/input.png -------------------------------------------------------------------------------- /images/original.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/Saafke/EDSR_Tensorflow/06c7bd65b0305c2955328f8f2721ea86c341f660/images/original.png -------------------------------------------------------------------------------- /main.py: -------------------------------------------------------------------------------- 1 | import tensorflow as tf 2 | import data_utils 3 | import run 4 | import os 5 | import cv2 6 | import numpy as np 7 | import pathlib 8 | import argparse 9 | from PIL import Image 10 | import numpy 11 | from tensorflow.python.client import device_lib 12 | 13 | os.environ['TF_CPP_MIN_LOG_LEVEL'] = '2' #gets rid of avx/fma warning 14 | 15 | # TODO: 16 | # When starting training for x3 and x4, start from pre-trained x2 model. 17 | 18 | if __name__ == "__main__": 19 | parser = argparse.ArgumentParser() 20 | # bools 21 | parser.add_argument('--train', help='Train the model', action="store_true") 22 | parser.add_argument('--test', help='Run PSNR test on an image', action="store_true") 23 | parser.add_argument('--upscale', help='Upscale an image with desired scale', action="store_true") 24 | parser.add_argument('--export', help='Export the model as .pb', action="store_true") 25 | parser.add_argument('--fromscratch', help='Load previous model for training',action="store_false") 26 | 27 | # numbers 28 | parser.add_argument('--quant', type=int, help='Quantize to shrink .pb file size. 1=round_weights. 2=quantize_weights. 3=round_weights&quantize.', default=0) 29 | parser.add_argument('--B', type=int, help='Number of resBlocks', default=32) 30 | parser.add_argument('--F', type=int, help='Number of filters', default=256) 31 | parser.add_argument('--scale', type=int, help='Scaling factor of the model', default=2) 32 | parser.add_argument('--batch', type=int, help='Batch size of the training', default=16) 33 | parser.add_argument('--epochs', type=int, help='Number of epochs during training', default=20) 34 | parser.add_argument('--lr', type=float, help='Learning_rate', default=0.0001) 35 | 36 | # paths 37 | parser.add_argument('--image', help='Specify test image', default="./images/original.png") 38 | parser.add_argument('--traindir', help='Path to train images') 39 | parser.add_argument('--validdir', help='Path to train images') 40 | args = parser.parse_args() 41 | 42 | # INIT 43 | scale = args.scale 44 | meanbgr = [103.1545782, 111.561547, 114.35629928] 45 | 46 | # Set checkpoint paths for different scales and models 47 | ckpt_path = "" 48 | if scale == 2: 49 | ckpt_path = "./CKPT_dir/x2/" 50 | elif scale == 3: 51 | ckpt_path = "./CKPT_dir/x3/" 52 | elif scale == 4: 53 | ckpt_path = "./CKPT_dir/x4/" 54 | else: 55 | print("No checkpoint directory. Choose scale 2, 3 or 4. Or add checkpoint directory for this scale.") 56 | exit() 57 | 58 | # Set gpu 59 | config = tf.ConfigProto() 60 | config.gpu_options.allow_growth = True 61 | 62 | # Create run instance 63 | run = run.run(config, ckpt_path, scale, args.batch, args.epochs, args.B, args.F, args.lr, args.fromscratch, meanbgr) 64 | 65 | if args.train: 66 | run.train(args.traindir, args.validdir) 67 | 68 | if args.test: 69 | run.testFromPb(args.image) 70 | #run.test(args.image) 71 | 72 | if args.upscale: 73 | run.upscaleFromPb(args.image) 74 | #run.upscale(args.image) 75 | 76 | if args.export: 77 | run.export(args.quant) 78 | 79 | print("I ran successfully.") -------------------------------------------------------------------------------- /models/EDSR_x2.pb: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/Saafke/EDSR_Tensorflow/06c7bd65b0305c2955328f8f2721ea86c341f660/models/EDSR_x2.pb -------------------------------------------------------------------------------- /models/EDSR_x3.pb: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/Saafke/EDSR_Tensorflow/06c7bd65b0305c2955328f8f2721ea86c341f660/models/EDSR_x3.pb -------------------------------------------------------------------------------- /models/EDSR_x4.pb: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/Saafke/EDSR_Tensorflow/06c7bd65b0305c2955328f8f2721ea86c341f660/models/EDSR_x4.pb -------------------------------------------------------------------------------- /requirements.txt: -------------------------------------------------------------------------------- 1 | numpy 2 | opencv-python 3 | tensorflow==1.14.0 4 | Pillow 5 | scikit-image 6 | -------------------------------------------------------------------------------- /run.py: -------------------------------------------------------------------------------- 1 | import tensorflow as tf 2 | import os 3 | import cv2 4 | import numpy as np 5 | import math 6 | import data_utils 7 | from skimage import io 8 | import edsr 9 | from PIL import Image 10 | 11 | from tensorflow.python.tools import freeze_graph 12 | from tensorflow.python.tools import optimize_for_inference_lib 13 | from tensorflow.tools.graph_transforms import TransformGraph 14 | 15 | class run: 16 | def __init__(self, config, ckpt_path, scale, batch, epochs, B, F, lr, load_flag, meanBGR): 17 | self.config = config 18 | self.ckpt_path = ckpt_path 19 | self.scale = scale 20 | self.batch = batch 21 | self.epochs = epochs 22 | self.B = B 23 | self.F = F 24 | self.lr = lr 25 | self.load_flag = load_flag 26 | self.mean = meanBGR 27 | 28 | def train(self, imagefolder, validfolder): 29 | 30 | # Create training dataset 31 | train_image_paths = data_utils.getpaths(imagefolder) 32 | train_dataset = tf.data.Dataset.from_generator(generator=data_utils.make_dataset, 33 | output_types=(tf.float32, tf.float32), 34 | output_shapes=(tf.TensorShape([None, None, 3]), tf.TensorShape([None, None, 3])), 35 | args=[train_image_paths, self.scale, self.mean]) 36 | train_dataset = train_dataset.padded_batch(self.batch, padded_shapes=([None, None, 3],[None, None, 3])) 37 | 38 | # Create validation dataset 39 | val_image_paths = data_utils.getpaths(validfolder) 40 | val_dataset = tf.data.Dataset.from_generator(generator=data_utils.make_val_dataset, 41 | output_types=(tf.float32, tf.float32), 42 | output_shapes=(tf.TensorShape([None, None, 3]), tf.TensorShape([None, None, 3])), 43 | args=[val_image_paths, self.scale, self.mean]) 44 | val_dataset = val_dataset.padded_batch(1, padded_shapes=([None, None, 3],[None, None, 3])) 45 | 46 | # Make the iterator and its initializers 47 | train_val_iterator = tf.data.Iterator.from_structure(train_dataset.output_types, train_dataset.output_shapes) 48 | train_initializer = train_val_iterator.make_initializer(train_dataset) 49 | val_initializer = train_val_iterator.make_initializer(val_dataset) 50 | 51 | handle = tf.placeholder(tf.string, shape=[]) 52 | iterator = tf.data.Iterator.from_string_handle(handle, train_dataset.output_types, train_dataset.output_shapes) 53 | LR, HR = iterator.get_next() 54 | 55 | # Edsr model 56 | print("\nRunning EDSR.") 57 | edsrObj = edsr.Edsr(self.B, self.F, self.scale) 58 | out, loss, train_op, psnr, ssim, lr = edsrObj.model(x=LR, y=HR, lr=self.lr) 59 | 60 | # -- Training session 61 | with tf.Session(config=self.config) as sess: 62 | 63 | train_writer = tf.summary.FileWriter('./logs/train', sess.graph) 64 | sess.run(tf.global_variables_initializer()) 65 | 66 | saver = tf.train.Saver() 67 | 68 | # Create check points directory if not existed, and load previous model if specified. 69 | if not os.path.exists(self.ckpt_path): 70 | os.makedirs(self.ckpt_path) 71 | else: 72 | if os.path.isfile(self.ckpt_path + "edsr_ckpt" + ".meta"): 73 | if self.load_flag: 74 | saver.restore(sess, tf.train.latest_checkpoint(self.ckpt_path)) 75 | print("\nLoaded checkpoint.") 76 | if not self.load_flag: 77 | print("No checkpoint loaded. Training from scratch.") 78 | # else: 79 | # if os.path.isfile("./CKPT_dir/x2/" + "edsr_ckpt" + ".meta"): 80 | # saver.restore(sess, tf.train.latest_checkpoint("./CKPT_dir/x2/")) 81 | # print("Previous checkpoint does not exists. Will load model from x2") 82 | # else: 83 | # print("No checkpoint loaded. Training from scratch.") 84 | 85 | global_step = 0 86 | tf.convert_to_tensor(global_step) 87 | 88 | train_val_handle = sess.run(train_val_iterator.string_handle()) 89 | 90 | print("Training...") 91 | for e in range(1, self.epochs+1): 92 | 93 | sess.run(train_initializer) 94 | step, train_loss = 0, 0 95 | 96 | try: 97 | while True: 98 | o, l, t, l_rate = sess.run([out, loss, train_op, lr], feed_dict={handle:train_val_handle, 99 | edsrObj.global_step: global_step}) 100 | train_loss += l 101 | step += 1 102 | global_step += 1 103 | 104 | if step % 1000 == 0: 105 | save_path = saver.save(sess, self.ckpt_path + "edsr_ckpt") 106 | print("Step nr: [{}/{}] - Loss: {:.5f} - Lr: {:.7f}".format(step, "?", float(train_loss/step), l_rate)) 107 | 108 | except tf.errors.OutOfRangeError: 109 | pass 110 | 111 | # Perform end-of-epoch calculations here. 112 | sess.run(val_initializer) 113 | tot_val_psnr, tot_val_ssim, val_im_cntr = 0, 0, 0 114 | try: 115 | while True: 116 | val_psnr, val_ssim = sess.run([psnr, ssim], feed_dict={handle:train_val_handle}) 117 | 118 | tot_val_psnr += val_psnr[0] 119 | tot_val_ssim += val_ssim[0] 120 | val_im_cntr += 1 121 | 122 | except tf.errors.OutOfRangeError: 123 | pass 124 | 125 | print("Epoch nr: [{}/{}] - Loss: {:.5f} - val PSNR: {:.3f} - val SSIM: {:.3f}\n".format(e, 126 | self.epochs, 127 | float(train_loss/step), 128 | (tot_val_psnr / val_im_cntr), 129 | (tot_val_ssim / val_im_cntr))) 130 | save_path = saver.save(sess, self.ckpt_path + "edsr_ckpt") 131 | 132 | print("Training finished.") 133 | train_writer.close() 134 | 135 | def upscale(self, path): 136 | """ 137 | Upscales an image via model. This loads a checkpoint, not a .pb file. 138 | """ 139 | fullimg = cv2.imread(path, 3) 140 | 141 | floatimg = fullimg.astype(np.float32) - self.mean 142 | 143 | LR_input_ = floatimg.reshape(1, floatimg.shape[0], floatimg.shape[1], 3) 144 | 145 | with tf.Session(config=self.config) as sess: 146 | print("\nUpscale image by a factor of {}:\n".format(self.scale)) 147 | # load the model 148 | ckpt_name = self.ckpt_path + "edsr_ckpt" + ".meta" 149 | saver = tf.train.import_meta_graph(ckpt_name) 150 | saver.restore(sess, tf.train.latest_checkpoint(self.ckpt_path)) 151 | graph_def = sess.graph 152 | LR_tensor = graph_def.get_tensor_by_name("IteratorGetNext:0") 153 | HR_tensor = graph_def.get_tensor_by_name("NHWC_output:0") 154 | 155 | output = sess.run(HR_tensor, feed_dict={LR_tensor: LR_input_}) 156 | 157 | Y = output[0] 158 | HR_image = (Y + self.mean).clip(min=0, max=255) 159 | HR_image = (HR_image).astype(np.uint8) 160 | 161 | bicubic_image = cv2.resize(fullimg, None, fx=self.scale, fy=self.scale, interpolation=cv2.INTER_CUBIC) 162 | 163 | cv2.imshow('Original image', fullimg) 164 | cv2.imshow('EDSR upscaled image', HR_image) 165 | cv2.imshow('Bicubic upscaled image', bicubic_image) 166 | cv2.waitKey(0) 167 | 168 | sess.close() 169 | 170 | def test(self, path): 171 | """ 172 | Test single image and calculate psnr. This loads a checkpoint, not a .pb file. 173 | """ 174 | fullimg = cv2.imread(path, 3) 175 | width = fullimg.shape[0] 176 | height = fullimg.shape[1] 177 | 178 | cropped = fullimg[0:(width - (width % self.scale)), 0:(height - (height % self.scale)), :] 179 | img = cv2.resize(cropped, None, fx=1. / self.scale, fy=1. / self.scale, interpolation=cv2.INTER_CUBIC) 180 | floatimg = img.astype(np.float32) - self.mean 181 | 182 | LR_input_ = floatimg.reshape(1, floatimg.shape[0], floatimg.shape[1], 3) 183 | 184 | with tf.Session(config=self.config) as sess: 185 | print("\nTest model with psnr:\n") 186 | # load the model 187 | ckpt_name = self.ckpt_path + "edsr_ckpt" + ".meta" 188 | saver = tf.train.import_meta_graph(ckpt_name) 189 | saver.restore(sess, tf.train.latest_checkpoint(self.ckpt_path)) 190 | graph_def = sess.graph 191 | LR_tensor = graph_def.get_tensor_by_name("IteratorGetNext:0") 192 | HR_tensor = graph_def.get_tensor_by_name("NHWC_output:0") 193 | 194 | output = sess.run(HR_tensor, feed_dict={LR_tensor: LR_input_}) 195 | 196 | Y = output[0] 197 | HR_image = (Y + self.mean).clip(min=0, max=255) 198 | HR_image = (HR_image).astype(np.uint8) 199 | 200 | bicubic_image = cv2.resize(img, None, fx=self.scale, fy=self.scale, interpolation=cv2.INTER_CUBIC) 201 | 202 | print(np.amax(Y), np.amax(LR_input_)) 203 | print("PSNR of EDSR upscaled image: {}".format(self.psnr(cropped, HR_image))) 204 | print("PSNR of bicubic upscaled image: {}".format(self.psnr(cropped, bicubic_image))) 205 | 206 | cv2.imshow('Original image', fullimg) 207 | cv2.imshow('EDSR upscaled image', HR_image) 208 | cv2.imshow('Bicubic upscaled image', bicubic_image) 209 | 210 | cv2.imwrite("./images/EdsrOutput.png", HR_image) 211 | cv2.imwrite("./images/BicubicOutput.png", bicubic_image) 212 | cv2.imwrite("./images/original.png", fullimg) 213 | cv2.imwrite("./images/input.png", img) 214 | 215 | cv2.waitKey(0) 216 | cv2.destroyAllWindows() 217 | 218 | sess.close() 219 | 220 | def load_pb(self, path_to_pb): 221 | with tf.gfile.GFile(path_to_pb, "rb") as f: 222 | graph_def = tf.GraphDef() 223 | graph_def.ParseFromString(f.read()) 224 | with tf.Graph().as_default() as graph: 225 | tf.import_graph_def(graph_def, name='') 226 | return graph 227 | 228 | def testFromPb(self, path): 229 | """ 230 | Test single image and calculate psnr. This loads a .pb file. 231 | """ 232 | # Read model 233 | pbPath = "./models/EDSR_x{}.pb".format(self.scale) 234 | 235 | # Get graph 236 | graph = self.load_pb(pbPath) 237 | 238 | fullimg = cv2.imread(path, 3) 239 | width = fullimg.shape[0] 240 | height = fullimg.shape[1] 241 | 242 | cropped = fullimg[0:(width - (width % self.scale)), 0:(height - (height % self.scale)), :] 243 | img = cv2.resize(cropped, None, fx=1. / self.scale, fy=1. / self.scale, interpolation=cv2.INTER_CUBIC) 244 | floatimg = img.astype(np.float32) - self.mean 245 | 246 | LR_input_ = floatimg.reshape(1, floatimg.shape[0], floatimg.shape[1], 3) 247 | 248 | LR_tensor = graph.get_tensor_by_name("IteratorGetNext:0") 249 | HR_tensor = graph.get_tensor_by_name("NHWC_output:0") 250 | 251 | with tf.Session(graph=graph) as sess: 252 | print("Loading pb...") 253 | output = sess.run(HR_tensor, feed_dict={LR_tensor: LR_input_}) 254 | Y = output[0] 255 | HR_image = (Y + self.mean).clip(min=0, max=255) 256 | HR_image = (HR_image).astype(np.uint8) 257 | 258 | bicubic_image = cv2.resize(img, None, fx=self.scale, fy=self.scale, interpolation=cv2.INTER_CUBIC) 259 | 260 | print(np.amax(Y), np.amax(LR_input_)) 261 | print("PSNR of EDSR upscaled image: {}".format(self.psnr(cropped, HR_image))) 262 | print("PSNR of bicubic upscaled image: {}".format(self.psnr(cropped, bicubic_image))) 263 | 264 | cv2.imshow('Original image', fullimg) 265 | cv2.imshow('EDSR upscaled image', HR_image) 266 | cv2.imshow('Bicubic upscaled image', bicubic_image) 267 | 268 | cv2.imwrite("./images/EdsrOutput.png", HR_image) 269 | cv2.imwrite("./images/BicubicOutput.png", bicubic_image) 270 | cv2.imwrite("./images/original.png", fullimg) 271 | cv2.imwrite("./images/input.png", img) 272 | 273 | cv2.waitKey(0) 274 | cv2.destroyAllWindows() 275 | print("Done.") 276 | 277 | sess.close() 278 | 279 | def upscaleFromPb(self, path): 280 | """ 281 | Upscale single image by desired model. This loads a .pb file. 282 | """ 283 | # Read model 284 | pbPath = "./models/EDSR_x{}.pb".format(self.scale) 285 | 286 | # Get graph 287 | graph = self.load_pb(pbPath) 288 | 289 | fullimg = cv2.imread(path, 3) 290 | floatimg = fullimg.astype(np.float32) - self.mean 291 | LR_input_ = floatimg.reshape(1, floatimg.shape[0], floatimg.shape[1], 3) 292 | 293 | LR_tensor = graph.get_tensor_by_name("IteratorGetNext:0") 294 | HR_tensor = graph.get_tensor_by_name("NHWC_output:0") 295 | 296 | with tf.Session(graph=graph) as sess: 297 | print("Loading pb...") 298 | output = sess.run(HR_tensor, feed_dict={LR_tensor: LR_input_}) 299 | Y = output[0] 300 | HR_image = (Y + self.mean).clip(min=0, max=255) 301 | HR_image = (HR_image).astype(np.uint8) 302 | 303 | bicubic_image = cv2.resize(fullimg, None, fx=self.scale, fy=self.scale, interpolation=cv2.INTER_CUBIC) 304 | 305 | cv2.imshow('Original image', fullimg) 306 | cv2.imshow('EDSR upscaled image', HR_image) 307 | cv2.imshow('Bicubic upscaled image', bicubic_image) 308 | 309 | cv2.waitKey(0) 310 | cv2.destroyAllWindows() 311 | 312 | sess.close() 313 | 314 | def export(self, quant): 315 | print("Exporting model...") 316 | 317 | export_dir = "./models/" 318 | if not os.path.exists(export_dir): 319 | os.makedirs(export_dir) 320 | 321 | export_file = "EDSRorig_x{}.pb".format(self.scale) 322 | 323 | graph = tf.get_default_graph() 324 | with graph.as_default(): 325 | with tf.Session(config=self.config) as sess: 326 | 327 | ### Restore checkpoint 328 | ckpt_name = self.ckpt_path + "edsr_ckpt" + ".meta" 329 | saver = tf.train.import_meta_graph(ckpt_name) 330 | saver.restore(sess, tf.train.latest_checkpoint(self.ckpt_path)) 331 | 332 | # Return a serialized GraphDef representation of this graph 333 | graph_def = sess.graph.as_graph_def() 334 | 335 | # All variables to constants 336 | graph_def = tf.graph_util.convert_variables_to_constants(sess, graph_def, ['NCHW_output']) 337 | 338 | # Optimize for inference 339 | graph_def = optimize_for_inference_lib.optimize_for_inference(graph_def, ["IteratorGetNext"], 340 | ["NCHW_output"], # ["NHWC_output"], 341 | tf.float32.as_datatype_enum) 342 | 343 | # Implement certain file shrinking transforms. 2 is recommended. 344 | transforms = ["sort_by_execution_order"] 345 | if quant == 1: 346 | print("Rounding weights for export.") 347 | transforms = ["sort_by_execution_order", "round_weights"] 348 | export_file = "EDSR_x{}_q1.pb".format(self.scale) 349 | if quant == 2: 350 | print("Quantizing for export.") 351 | transforms = ["sort_by_execution_order", "quantize_weights"] 352 | export_file = "EDSR_x{}.pb".format(self.scale) 353 | if quant == 3: 354 | print("Round weights and quantizing for export.") 355 | transforms = ["sort_by_execution_order", "round_weights", "quantize_weights"] 356 | export_file = "EDSR_x{}_q3.pb".format(self.scale) 357 | 358 | graph_def = TransformGraph(graph_def, ["IteratorGetNext"], 359 | ["NCHW_output"], 360 | transforms) 361 | 362 | print("Exported file = {}".format(export_dir+export_file)) 363 | with tf.gfile.GFile(export_dir + export_file, 'wb') as f: 364 | f.write(graph_def.SerializeToString()) 365 | 366 | tf.train.write_graph(graph_def, ".", 'train.pbtxt') 367 | 368 | sess.close() 369 | 370 | def psnr(self, img1, img2): 371 | mse = np.mean( (img1 - img2) ** 2 ) 372 | if mse == 0: 373 | return 100 374 | PIXEL_MAX = 255.0 375 | return (20 * math.log10(PIXEL_MAX / math.sqrt(mse))) --------------------------------------------------------------------------------