[
  {
    "path": "LICENSE",
    "content": "                                 Apache License\n                           Version 2.0, January 2004\n                        http://www.apache.org/licenses/\n\n   TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION\n\n   1. Definitions.\n\n      \"License\" shall mean the terms and conditions for use, reproduction,\n      and distribution as defined by Sections 1 through 9 of this document.\n\n      \"Licensor\" shall mean the copyright owner or entity authorized by\n      the copyright owner that is granting the License.\n\n      \"Legal Entity\" shall mean the union of the acting entity and all\n      other entities that control, are controlled by, or are under common\n      control with that entity. For the purposes of this definition,\n      \"control\" means (i) the power, direct or indirect, to cause the\n      direction or management of such entity, whether by contract or\n      otherwise, or (ii) ownership of fifty percent (50%) or more of the\n      outstanding shares, or (iii) beneficial ownership of such entity.\n\n      \"You\" (or \"Your\") shall mean an individual or Legal Entity\n      exercising permissions granted by this License.\n\n      \"Source\" form shall mean the preferred form for making modifications,\n      including but not limited to software source code, documentation\n      source, and configuration files.\n\n      \"Object\" form shall mean any form resulting from mechanical\n      transformation or translation of a Source form, including but\n      not limited to compiled object code, generated documentation,\n      and conversions to other media types.\n\n      \"Work\" shall mean the work of authorship, whether in Source or\n      Object form, made available under the License, as indicated by a\n      copyright notice that is included in or attached to the work\n      (an example is provided in the Appendix below).\n\n      \"Derivative Works\" shall mean any work, whether in Source or Object\n      form, that is based on (or derived from) the Work and for which the\n      editorial revisions, annotations, elaborations, or other modifications\n      represent, as a whole, an original work of authorship. For the purposes\n      of this License, Derivative Works shall not include works that remain\n      separable from, or merely link (or bind by name) to the interfaces of,\n      the Work and Derivative Works thereof.\n\n      \"Contribution\" shall mean any work of authorship, including\n      the original version of the Work and any modifications or additions\n      to that Work or Derivative Works thereof, that is intentionally\n      submitted to Licensor for inclusion in the Work by the copyright owner\n      or by an individual or Legal Entity authorized to submit on behalf of\n      the copyright owner. For the purposes of this definition, \"submitted\"\n      means any form of electronic, verbal, or written communication sent\n      to the Licensor or its representatives, including but not limited to\n      communication on electronic mailing lists, source code control systems,\n      and issue tracking systems that are managed by, or on behalf of, the\n      Licensor for the purpose of discussing and improving the Work, but\n      excluding communication that is conspicuously marked or otherwise\n      designated in writing by the copyright owner as \"Not a Contribution.\"\n\n      \"Contributor\" shall mean Licensor and any individual or Legal Entity\n      on behalf of whom a Contribution has been received by Licensor and\n      subsequently incorporated within the Work.\n\n   2. Grant of Copyright License. Subject to the terms and conditions of\n      this License, each Contributor hereby grants to You a perpetual,\n      worldwide, non-exclusive, no-charge, royalty-free, irrevocable\n      copyright license to reproduce, prepare Derivative Works of,\n      publicly display, publicly perform, sublicense, and distribute the\n      Work and such Derivative Works in Source or Object form.\n\n   3. Grant of Patent License. Subject to the terms and conditions of\n      this License, each Contributor hereby grants to You a perpetual,\n      worldwide, non-exclusive, no-charge, royalty-free, irrevocable\n      (except as stated in this section) patent license to make, have made,\n      use, offer to sell, sell, import, and otherwise transfer the Work,\n      where such license applies only to those patent claims licensable\n      by such Contributor that are necessarily infringed by their\n      Contribution(s) alone or by combination of their Contribution(s)\n      with the Work to which such Contribution(s) was submitted. If You\n      institute patent litigation against any entity (including a\n      cross-claim or counterclaim in a lawsuit) alleging that the Work\n      or a Contribution incorporated within the Work constitutes direct\n      or contributory patent infringement, then any patent licenses\n      granted to You under this License for that Work shall terminate\n      as of the date such litigation is filed.\n\n   4. Redistribution. You may reproduce and distribute copies of the\n      Work or Derivative Works thereof in any medium, with or without\n      modifications, and in Source or Object form, provided that You\n      meet the following conditions:\n\n      (a) You must give any other recipients of the Work or\n          Derivative Works a copy of this License; and\n\n      (b) You must cause any modified files to carry prominent notices\n          stating that You changed the files; and\n\n      (c) You must retain, in the Source form of any Derivative Works\n          that You distribute, all copyright, patent, trademark, and\n          attribution notices from the Source form of the Work,\n          excluding those notices that do not pertain to any part of\n          the Derivative Works; and\n\n      (d) If the Work includes a \"NOTICE\" text file as part of its\n          distribution, then any Derivative Works that You distribute must\n          include a readable copy of the attribution notices contained\n          within such NOTICE file, excluding those notices that do not\n          pertain to any part of the Derivative Works, in at least one\n          of the following places: within a NOTICE text file distributed\n          as part of the Derivative Works; within the Source form or\n          documentation, if provided along with the Derivative Works; or,\n          within a display generated by the Derivative Works, if and\n          wherever such third-party notices normally appear. The contents\n          of the NOTICE file are for informational purposes only and\n          do not modify the License. You may add Your own attribution\n          notices within Derivative Works that You distribute, alongside\n          or as an addendum to the NOTICE text from the Work, provided\n          that such additional attribution notices cannot be construed\n          as modifying the License.\n\n      You may add Your own copyright statement to Your modifications and\n      may provide additional or different license terms and conditions\n      for use, reproduction, or distribution of Your modifications, or\n      for any such Derivative Works as a whole, provided Your use,\n      reproduction, and distribution of the Work otherwise complies with\n      the conditions stated in this License.\n\n   5. Submission of Contributions. Unless You explicitly state otherwise,\n      any Contribution intentionally submitted for inclusion in the Work\n      by You to the Licensor shall be under the terms and conditions of\n      this License, without any additional terms or conditions.\n      Notwithstanding the above, nothing herein shall supersede or modify\n      the terms of any separate license agreement you may have executed\n      with Licensor regarding such Contributions.\n\n   6. Trademarks. This License does not grant permission to use the trade\n      names, trademarks, service marks, or product names of the Licensor,\n      except as required for reasonable and customary use in describing the\n      origin of the Work and reproducing the content of the NOTICE file.\n\n   7. Disclaimer of Warranty. Unless required by applicable law or\n      agreed to in writing, Licensor provides the Work (and each\n      Contributor provides its Contributions) on an \"AS IS\" BASIS,\n      WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or\n      implied, including, without limitation, any warranties or conditions\n      of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A\n      PARTICULAR PURPOSE. You are solely responsible for determining the\n      appropriateness of using or redistributing the Work and assume any\n      risks associated with Your exercise of permissions under this License.\n\n   8. Limitation of Liability. In no event and under no legal theory,\n      whether in tort (including negligence), contract, or otherwise,\n      unless required by applicable law (such as deliberate and grossly\n      negligent acts) or agreed to in writing, shall any Contributor be\n      liable to You for damages, including any direct, indirect, special,\n      incidental, or consequential damages of any character arising as a\n      result of this License or out of the use or inability to use the\n      Work (including but not limited to damages for loss of goodwill,\n      work stoppage, computer failure or malfunction, or any and all\n      other commercial damages or losses), even if such Contributor\n      has been advised of the possibility of such damages.\n\n   9. Accepting Warranty or Additional Liability. While redistributing\n      the Work or Derivative Works thereof, You may choose to offer,\n      and charge a fee for, acceptance of support, warranty, indemnity,\n      or other liability obligations and/or rights consistent with this\n      License. However, in accepting such obligations, You may act only\n      on Your own behalf and on Your sole responsibility, not on behalf\n      of any other Contributor, and only if You agree to indemnify,\n      defend, and hold each Contributor harmless for any liability\n      incurred by, or claims asserted against, such Contributor by reason\n      of your accepting any such warranty or additional liability.\n\n   END OF TERMS AND CONDITIONS\n\n   APPENDIX: How to apply the Apache License to your work.\n\n      To apply the Apache License to your work, attach the following\n      boilerplate notice, with the fields enclosed by brackets \"[]\"\n      replaced with your own identifying information. (Don't include\n      the brackets!)  The text should be enclosed in the appropriate\n      comment syntax for the file format. We also recommend that a\n      file or class name and description of purpose be included on the\n      same \"printed page\" as the copyright notice for easier\n      identification within third-party archives.\n\n   Copyright [yyyy] [name of copyright owner]\n\n   Licensed under the Apache License, Version 2.0 (the \"License\");\n   you may not use this file except in compliance with the License.\n   You may obtain a copy of the License at\n\n       http://www.apache.org/licenses/LICENSE-2.0\n\n   Unless required by applicable law or agreed to in writing, software\n   distributed under the License is distributed on an \"AS IS\" BASIS,\n   WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n   See the License for the specific language governing permissions and\n   limitations under the License.\n"
  },
  {
    "path": "README.md",
    "content": "# EDSR in Tensorflow\n\nTensorFlow implementation of [Enhanced Deep Residual Networks for Single Image Super-Resolution](https://arxiv.org/pdf/1707.02921.pdf)[1].\n\nIt was trained on the [Div2K dataset](https://data.vision.ee.ethz.ch/cvl/DIV2K/) - Train Data (HR images).\n\n## Google Summer of Code with OpenCV\nThis 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.\n\n## Requirements\n- tensorflow\n- numpy\n- cv2\n\n## EDSR\nThis is the EDSR model, which has a different model for each scale. Architecture shown below. Go to branch 'mdsr' for the MDSR model.\n\n![Alt text](images/EDSR.png?raw=true \"EDSR architecture\")\n\n# Running\nDownload [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.\n\nTrain:\n- from scratch\n`python main.py --train --fromscratch --scale <scale> --traindir /path-to-train-images/`\n\n- resume/load previous\n`python main.py --train --scale <scale> --traindir /path-to-train-images/`\n\nTest (compares edsr with bicubic with PSNR metric):\n`python main.py --test --scale <scale> --image /path-to-image/`\n\nUpscale (with edsr):\n`python main.py --upscale --scale <scale> --image /path-to-image/`\n\nExport to .pb\n`python main.py --export --scale <scale>`\n\nExtra arguments (Nr of resblocks, filters, batch, lr etc.)\n`python main.py --help`\n\n## Example\n(1) Original picture\\\n(2) Input image\\\n(3) Bicubic scaled (3x) image\\\n(4) EDSR scaled (3x) image\\\n![Alt text](images/original.png?raw=true \"Original picture\")\n![Alt text](images/input.png?raw=true \"Input image picture\")\n![Alt text](images/BicubicOutput.png?raw=true \"Bicubic picture\")\n![Alt text](images/EdsrOutput.png?raw=true \"EDSR picture\")\n\n## Notes\nThe .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.))\n\n## References\n[1] Bee Lim, Sanghyun Son, Heewon Kim, Seungjun Nah, and Kyoung Mu Lee, **\"Enhanced Deep Residual Networks for Single Image Super-Resolution,\"** <i>2nd NTIRE: New Trends in Image Restoration and Enhancement workshop and challenge on image super-resolution in conjunction with **CVPR 2017**. </i> [[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)]\n"
  },
  {
    "path": "data_utils.py",
    "content": "import pathlib\nimport os\nfrom PIL import Image\nimport numpy as np\nimport cv2\nimport tensorflow as tf\nimport random\n\ndef getpathsx(path):\n    \"\"\"\n    Get all image paths from folder 'path'.\n    \"\"\"\n    data = pathlib.Path(path)\n    all_image_paths = list(data.glob('*'))\n    all_image_paths = [str(p) for p in all_image_paths]\n    return all_image_paths\n\ndef getpaths(path):\n    \"\"\"\n    Get all image paths from folder 'path' while avoiding ._ files.\n    \"\"\"\n    im_paths = []\n    for fil in os.listdir(path):\n            if '.png' in fil:\n                if \"._\" in fil:\n                    #avoid dot underscore\n                    pass\n                else:\n                    im_paths.append(os.path.join(path, fil))\n    return im_paths\n\ndef make_val_dataset(paths, scale, mean):\n    \"\"\"\n    Python generator-style dataset for the validation set. Creates input and ground truth.\n    \"\"\"\n    for p in paths:\n        # normalize\n        im_norm = cv2.imread(p.decode(), 3).astype(np.float32) - mean\n\n        # divisible by scale - create low-res\n        hr = im_norm[0:(im_norm.shape[0] - (im_norm.shape[0] % scale)),\n                  0:(im_norm.shape[1] - (im_norm.shape[1] % scale)), :]\n        lr = cv2.resize(hr, (int(hr.shape[1] / scale), int(hr.shape[0] / scale)),\n                        interpolation=cv2.INTER_CUBIC)\n\n        yield lr, hr\n\ndef make_dataset(paths, scale, mean):\n    \"\"\"\n    Python generator-style dataset. Creates 48x48 low-res and corresponding high-res patches.\n    \"\"\"\n    size_lr = 48\n    size_hr = size_lr * scale\n\n    for p in paths:\n        # normalize\n        im_norm = cv2.imread(p.decode(), 3).astype(np.float32) - mean\n\n        # random flip\n        r = random.randint(-1, 2)\n        if not r == 2:\n            im_norm = cv2.flip(im_norm, r)\n\n        # divisible by scale - create low-res\n        hr = im_norm[0:(im_norm.shape[0] - (im_norm.shape[0] % scale)),\n                  0:(im_norm.shape[1] - (im_norm.shape[1] % scale)), :]\n        lr = cv2.resize(hr, (int(hr.shape[1] / scale), int(hr.shape[0] / scale)),\n                        interpolation=cv2.INTER_CUBIC)\n\n        numx = int(lr.shape[0] / size_lr)\n        numy = int(lr.shape[1] / size_lr)\n\n        for i in range(0, numx):\n            startx = i * size_lr\n            endx = (i * size_lr) + size_lr\n\n            startx_hr = i * size_hr\n            endx_hr = (i * size_hr) + size_hr\n\n            for j in range(0, numy):\n                starty = j * size_lr\n                endy = (j * size_lr) + size_lr\n                starty_hr = j * size_hr\n                endy_hr = (j * size_hr) + size_hr\n\n                crop_lr = lr[startx:endx, starty:endy]\n                crop_hr = hr[startx_hr:endx_hr, starty_hr:endy_hr]\n\n                x = crop_lr.reshape((size_lr, size_lr, 3))\n                y = crop_hr.reshape((size_hr, size_hr, 3))\n\n                yield x, y\n\ndef calcmean(imageFolder, bgr):\n    \"\"\"\n    Calculates the mean of a dataset.\n    \"\"\"\n    paths = getpaths(imageFolder)\n\n    total_mean = [0, 0, 0]\n    im_counter = 0\n\n    for p in paths:\n\n        image = np.asarray(Image.open(p))\n\n        mean_rgb = np.mean(image, axis=(0, 1), dtype=np.float64)\n\n        if im_counter % 50 == 0:\n            print(\"Total mean: {} | current mean: {}\".format(total_mean, mean_rgb))\n\n        total_mean += mean_rgb\n        im_counter += 1\n\n    total_mean /= im_counter\n\n    # rgb to bgr\n    if bgr is True:\n        total_mean = total_mean[...,::-1]\n\n    return total_mean"
  },
  {
    "path": "edsr.py",
    "content": "from __future__ import print_function\n\nimport cv2\nimport tensorflow as tf\nimport numpy as np\nimport os\n\nclass Edsr:\n\n    def __init__(self, B, F, scale):\n        self.B = B\n        self.F = F\n        self.scale = scale\n        self.global_step = tf.placeholder(tf.int32, shape=[], name=\"global_step\")\n        self.scaling_factor = 0.1\n        self.bias_initializer = tf.constant_initializer(value=0.0)\n        self.PS = 3 * (scale*scale) #channels x scale^2\n        self.xavier = tf.contrib.layers.xavier_initializer()\n\n        # -- Filters & Biases --\n        self.resFilters = list()\n        self.resBiases = list()\n\n        for i in range(0, B*2):\n            self.resFilters.append( tf.get_variable(\"resFilter%d\" % (i), shape=[3,3,F,F], initializer=self.xavier))\n            self.resBiases.append(tf.get_variable(name=\"resBias%d\" % (i), shape=[F], initializer=self.bias_initializer))\n\n        self.filter_one = tf.get_variable(\"resFilter_one\", shape=[3,3,3,F], initializer=self.xavier)\n        self.filter_two = tf.get_variable(\"resFilter_two\", shape=[3,3,F,F], initializer=self.xavier)\n        self.filter_three = tf.get_variable(\"resFilter_three\", shape=[3,3,F,self.PS], initializer=self.xavier)\n\n        self.bias_one = tf.get_variable(shape=[F], initializer=self.bias_initializer, name=\"BiasOne\")\n        self.bias_two = tf.get_variable(shape=[F], initializer=self.bias_initializer, name=\"BiasTwo\")\n        self.bias_three = tf.get_variable(shape=[self.PS], initializer=self.bias_initializer, name=\"BiasThree\")\n\n\n    def model(self, x, y, lr):\n        \"\"\"\n        Implementation of EDSR: https://arxiv.org/abs/1707.02921.\n        \"\"\"\n\n        # -- Model architecture --\n\n        # first conv\n        x = tf.nn.conv2d(x, filter=self.filter_one, strides=[1, 1, 1, 1], padding='SAME')\n        x = x + self.bias_one\n        out1 = tf.identity(x)\n\n        # all residual blocks\n        for i in range(self.B):\n            x = self.resBlock(x, (i*2))\n\n        # last conv\n        x = tf.nn.conv2d(x, filter=self.filter_two, strides=[1, 1, 1, 1], padding='SAME')\n        x = x + self.bias_two\n        x = x + out1\n\n        # upsample via sub-pixel, equivalent to depth to space\n        x = tf.nn.conv2d(x, filter=self.filter_three, strides=[1, 1, 1, 1], padding='SAME')\n        x = x + self.bias_three\n        out = tf.nn.depth_to_space(x, self.scale, data_format='NHWC', name=\"NHWC_output\")\n        \n        # -- --\n\n        # some outputs\n        out_nchw = tf.transpose(out, [0, 3, 1, 2], name=\"NCHW_output\")\n        psnr = tf.image.psnr(out, y, max_val=255.0)\n        loss = tf.losses.absolute_difference(out, y) #L1\n        ssim = tf.image.ssim(out, y, max_val=255.0)\n        \n        # (decaying) learning rate\n        lr = tf.train.exponential_decay(lr,\n                                        self.global_step,\n                                        decay_steps=15000,\n                                        decay_rate=0.95,\n                                        staircase=True)\n        # gradient clipping\n        optimizer = tf.train.AdamOptimizer(lr)\n        gradients, variables = zip(*optimizer.compute_gradients(loss))\n        gradients, _ = tf.clip_by_global_norm(gradients, 5.0)\n        train_op = optimizer.apply_gradients(zip(gradients, variables))\n\n        return out, loss, train_op, psnr, ssim, lr\n\n    def resBlock(self, inpt, f_nr):\n        x = tf.nn.conv2d(inpt, filter=self.resFilters[f_nr], strides=[1, 1, 1, 1], padding='SAME')\n        x = x + self.resBiases[f_nr]\n        x = tf.nn.relu(x)\n\n        x = tf.nn.conv2d(x, filter=self.resFilters[f_nr+1], strides=[1, 1, 1, 1], padding='SAME')\n        x = x + self.resBiases[f_nr+1]\n        x = x * self.scaling_factor\n\n        return inpt + x"
  },
  {
    "path": "main.py",
    "content": "import tensorflow as tf\nimport data_utils\nimport run\nimport os\nimport cv2\nimport numpy as np\nimport pathlib\nimport argparse\nfrom PIL import Image\nimport numpy\nfrom tensorflow.python.client import device_lib\n\nos.environ['TF_CPP_MIN_LOG_LEVEL'] = '2' #gets rid of avx/fma warning\n\n# TODO:\n# When starting training for x3 and x4, start from pre-trained x2 model.\n\nif __name__ == \"__main__\":\n    parser = argparse.ArgumentParser()\n    # bools\n    parser.add_argument('--train', help='Train the model', action=\"store_true\")\n    parser.add_argument('--test', help='Run PSNR test on an image', action=\"store_true\")\n    parser.add_argument('--upscale', help='Upscale an image with desired scale', action=\"store_true\")\n    parser.add_argument('--export', help='Export the model as .pb', action=\"store_true\")\n    parser.add_argument('--fromscratch', help='Load previous model for training',action=\"store_false\")\n\n    # numbers\n    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)\n    parser.add_argument('--B', type=int, help='Number of resBlocks', default=32)\n    parser.add_argument('--F', type=int, help='Number of filters', default=256)\n    parser.add_argument('--scale', type=int, help='Scaling factor of the model', default=2)\n    parser.add_argument('--batch', type=int, help='Batch size of the training', default=16)\n    parser.add_argument('--epochs', type=int, help='Number of epochs during training', default=20)\n    parser.add_argument('--lr', type=float, help='Learning_rate', default=0.0001)\n\n    # paths\n    parser.add_argument('--image', help='Specify test image', default=\"./images/original.png\")\n    parser.add_argument('--traindir', help='Path to train images')\n    parser.add_argument('--validdir', help='Path to train images')\n    args = parser.parse_args()\n\n    # INIT\n    scale = args.scale\n    meanbgr = [103.1545782, 111.561547, 114.35629928]\n\n    # Set checkpoint paths for different scales and models\n    ckpt_path = \"\"\n    if scale == 2:\n        ckpt_path = \"./CKPT_dir/x2/\"\n    elif scale == 3:\n        ckpt_path = \"./CKPT_dir/x3/\"\n    elif scale == 4:\n        ckpt_path = \"./CKPT_dir/x4/\"\n    else:\n        print(\"No checkpoint directory. Choose scale 2, 3 or 4. Or add checkpoint directory for this scale.\")\n        exit()\n\n    # Set gpu\n    config = tf.ConfigProto()\n    config.gpu_options.allow_growth = True\n\n    # Create run instance\n    run = run.run(config, ckpt_path, scale, args.batch, args.epochs, args.B, args.F, args.lr, args.fromscratch, meanbgr)\n\n    if args.train:\n        run.train(args.traindir, args.validdir)\n\n    if args.test:\n        run.testFromPb(args.image)\n        #run.test(args.image)\n    \n    if args.upscale:\n        run.upscaleFromPb(args.image)\n        #run.upscale(args.image)\n\n    if args.export:\n        run.export(args.quant)\n\n    print(\"I ran successfully.\")"
  },
  {
    "path": "requirements.txt",
    "content": "numpy\nopencv-python\ntensorflow==1.14.0\nPillow\nscikit-image\n"
  },
  {
    "path": "run.py",
    "content": "import tensorflow as tf\nimport os\nimport cv2\nimport numpy as np\nimport math\nimport data_utils\nfrom skimage import io\nimport edsr\nfrom PIL import Image\n\nfrom tensorflow.python.tools import freeze_graph\nfrom tensorflow.python.tools import optimize_for_inference_lib\nfrom tensorflow.tools.graph_transforms import TransformGraph\n\nclass run:\n    def __init__(self, config, ckpt_path, scale, batch, epochs, B, F, lr, load_flag, meanBGR):\n        self.config = config\n        self.ckpt_path = ckpt_path\n        self.scale = scale\n        self.batch = batch\n        self.epochs = epochs\n        self.B = B\n        self.F = F\n        self.lr = lr\n        self.load_flag = load_flag\n        self.mean = meanBGR\n\n    def train(self, imagefolder, validfolder):\n\n        # Create training dataset\n        train_image_paths = data_utils.getpaths(imagefolder)\n        train_dataset = tf.data.Dataset.from_generator(generator=data_utils.make_dataset,\n                                                 output_types=(tf.float32, tf.float32),\n                                                 output_shapes=(tf.TensorShape([None, None, 3]), tf.TensorShape([None, None, 3])),\n                                                 args=[train_image_paths, self.scale, self.mean])\n        train_dataset = train_dataset.padded_batch(self.batch, padded_shapes=([None, None, 3],[None, None, 3]))\n\n        # Create validation dataset\n        val_image_paths = data_utils.getpaths(validfolder)\n        val_dataset = tf.data.Dataset.from_generator(generator=data_utils.make_val_dataset,\n                                                 output_types=(tf.float32, tf.float32),\n                                                 output_shapes=(tf.TensorShape([None, None, 3]), tf.TensorShape([None, None, 3])),\n                                                 args=[val_image_paths, self.scale, self.mean])\n        val_dataset = val_dataset.padded_batch(1, padded_shapes=([None, None, 3],[None, None, 3]))\n\n        # Make the iterator and its initializers\n        train_val_iterator = tf.data.Iterator.from_structure(train_dataset.output_types, train_dataset.output_shapes)\n        train_initializer = train_val_iterator.make_initializer(train_dataset)\n        val_initializer = train_val_iterator.make_initializer(val_dataset)\n\n        handle = tf.placeholder(tf.string, shape=[])\n        iterator = tf.data.Iterator.from_string_handle(handle, train_dataset.output_types, train_dataset.output_shapes)\n        LR, HR = iterator.get_next()\n\n        # Edsr model\n        print(\"\\nRunning EDSR.\")\n        edsrObj = edsr.Edsr(self.B, self.F, self.scale)\n        out, loss, train_op, psnr, ssim, lr = edsrObj.model(x=LR, y=HR, lr=self.lr)\n\n        # -- Training session\n        with tf.Session(config=self.config) as sess:\n\n            train_writer = tf.summary.FileWriter('./logs/train', sess.graph)\n            sess.run(tf.global_variables_initializer())\n\n            saver = tf.train.Saver()\n\n            # Create check points directory if not existed, and load previous model if specified.\n            if not os.path.exists(self.ckpt_path):\n                os.makedirs(self.ckpt_path)\n            else:\n                if os.path.isfile(self.ckpt_path + \"edsr_ckpt\" + \".meta\"):\n                    if self.load_flag:\n                        saver.restore(sess, tf.train.latest_checkpoint(self.ckpt_path))\n                        print(\"\\nLoaded checkpoint.\")\n                    if not self.load_flag:\n                        print(\"No checkpoint loaded. Training from scratch.\")\n                # else:\n                #     if os.path.isfile(\"./CKPT_dir/x2/\" + \"edsr_ckpt\" + \".meta\"):\n                #         saver.restore(sess, tf.train.latest_checkpoint(\"./CKPT_dir/x2/\"))\n                #         print(\"Previous checkpoint does not exists. Will load model from x2\")\n                #     else:\n                #         print(\"No checkpoint loaded. Training from scratch.\")\n\n            global_step = 0\n            tf.convert_to_tensor(global_step)\n\n            train_val_handle = sess.run(train_val_iterator.string_handle())\n\n            print(\"Training...\")\n            for e in range(1, self.epochs+1):\n\n                sess.run(train_initializer)\n                step, train_loss = 0, 0\n\n                try:\n                    while True:\n                        o, l, t, l_rate = sess.run([out, loss, train_op, lr], feed_dict={handle:train_val_handle,\n                                                                                         edsrObj.global_step: global_step})\n                        train_loss += l\n                        step += 1\n                        global_step += 1\n\n                        if step % 1000 == 0:\n                            save_path = saver.save(sess, self.ckpt_path + \"edsr_ckpt\")\n                            print(\"Step nr: [{}/{}] - Loss: {:.5f} - Lr: {:.7f}\".format(step, \"?\", float(train_loss/step), l_rate))\n\n                except tf.errors.OutOfRangeError:\n                    pass\n\n                # Perform end-of-epoch calculations here.\n                sess.run(val_initializer)\n                tot_val_psnr, tot_val_ssim, val_im_cntr = 0, 0, 0\n                try:\n                    while True:\n                        val_psnr, val_ssim = sess.run([psnr, ssim], feed_dict={handle:train_val_handle})\n\n                        tot_val_psnr += val_psnr[0]\n                        tot_val_ssim += val_ssim[0]\n                        val_im_cntr += 1\n\n                except tf.errors.OutOfRangeError:\n                    pass\n\n                print(\"Epoch nr: [{}/{}]  - Loss: {:.5f} - val PSNR: {:.3f} - val SSIM: {:.3f}\\n\".format(e,\n                                                                                                         self.epochs,\n                                                                                                         float(train_loss/step),\n                                                                                                         (tot_val_psnr / val_im_cntr),\n                                                                                                         (tot_val_ssim / val_im_cntr)))\n                save_path = saver.save(sess, self.ckpt_path + \"edsr_ckpt\")\n\n            print(\"Training finished.\")\n            train_writer.close()\n\n    def upscale(self, path):\n        \"\"\"\n        Upscales an image via model. This loads a checkpoint, not a .pb file.\n        \"\"\"\n        fullimg = cv2.imread(path, 3)\n\n        floatimg = fullimg.astype(np.float32) - self.mean\n\n        LR_input_ = floatimg.reshape(1, floatimg.shape[0], floatimg.shape[1], 3)\n\n        with tf.Session(config=self.config) as sess:\n            print(\"\\nUpscale image by a factor of {}:\\n\".format(self.scale))\n            # load the model\n            ckpt_name = self.ckpt_path + \"edsr_ckpt\" + \".meta\"\n            saver = tf.train.import_meta_graph(ckpt_name)\n            saver.restore(sess, tf.train.latest_checkpoint(self.ckpt_path))\n            graph_def = sess.graph\n            LR_tensor = graph_def.get_tensor_by_name(\"IteratorGetNext:0\")\n            HR_tensor = graph_def.get_tensor_by_name(\"NHWC_output:0\")\n\n            output = sess.run(HR_tensor, feed_dict={LR_tensor: LR_input_})\n\n            Y = output[0]\n            HR_image = (Y + self.mean).clip(min=0, max=255)\n            HR_image = (HR_image).astype(np.uint8)\n\n            bicubic_image = cv2.resize(fullimg, None, fx=self.scale, fy=self.scale, interpolation=cv2.INTER_CUBIC)\n\n            cv2.imshow('Original image', fullimg)\n            cv2.imshow('EDSR upscaled image', HR_image)\n            cv2.imshow('Bicubic upscaled image', bicubic_image)\n            cv2.waitKey(0)\n\n        sess.close()\n\n    def test(self, path):\n        \"\"\"\n        Test single image and calculate psnr. This loads a checkpoint, not a .pb file.\n        \"\"\"\n        fullimg = cv2.imread(path, 3)\n        width = fullimg.shape[0]\n        height = fullimg.shape[1]\n\n        cropped = fullimg[0:(width - (width % self.scale)), 0:(height - (height % self.scale)), :]\n        img = cv2.resize(cropped, None, fx=1. / self.scale, fy=1. / self.scale, interpolation=cv2.INTER_CUBIC)\n        floatimg = img.astype(np.float32) - self.mean\n\n        LR_input_ = floatimg.reshape(1, floatimg.shape[0], floatimg.shape[1], 3)\n\n        with tf.Session(config=self.config) as sess:\n            print(\"\\nTest model with psnr:\\n\")\n            # load the model\n            ckpt_name = self.ckpt_path + \"edsr_ckpt\" + \".meta\"\n            saver = tf.train.import_meta_graph(ckpt_name)\n            saver.restore(sess, tf.train.latest_checkpoint(self.ckpt_path))\n            graph_def = sess.graph\n            LR_tensor = graph_def.get_tensor_by_name(\"IteratorGetNext:0\")\n            HR_tensor = graph_def.get_tensor_by_name(\"NHWC_output:0\")\n\n            output = sess.run(HR_tensor, feed_dict={LR_tensor: LR_input_})\n\n            Y = output[0]\n            HR_image = (Y + self.mean).clip(min=0, max=255)\n            HR_image = (HR_image).astype(np.uint8)\n\n            bicubic_image = cv2.resize(img, None, fx=self.scale, fy=self.scale, interpolation=cv2.INTER_CUBIC)\n\n            print(np.amax(Y), np.amax(LR_input_))\n            print(\"PSNR of  EDSR   upscaled image: {}\".format(self.psnr(cropped, HR_image)))\n            print(\"PSNR of bicubic upscaled image: {}\".format(self.psnr(cropped, bicubic_image)))\n\n            cv2.imshow('Original image', fullimg)\n            cv2.imshow('EDSR upscaled image', HR_image)\n            cv2.imshow('Bicubic upscaled image', bicubic_image)\n\n            cv2.imwrite(\"./images/EdsrOutput.png\", HR_image)\n            cv2.imwrite(\"./images/BicubicOutput.png\", bicubic_image)\n            cv2.imwrite(\"./images/original.png\", fullimg)\n            cv2.imwrite(\"./images/input.png\", img)\n\n            cv2.waitKey(0)\n            cv2.destroyAllWindows()\n\n        sess.close()\n\n    def load_pb(self, path_to_pb):\n        with tf.gfile.GFile(path_to_pb, \"rb\") as f:\n            graph_def = tf.GraphDef()\n            graph_def.ParseFromString(f.read())\n        with tf.Graph().as_default() as graph:\n            tf.import_graph_def(graph_def, name='')\n            return graph\n\n    def testFromPb(self, path):\n        \"\"\"\n        Test single image and calculate psnr. This loads a .pb file.\n        \"\"\"\n        # Read model\n        pbPath = \"./models/EDSR_x{}.pb\".format(self.scale)\n\n        # Get graph\n        graph = self.load_pb(pbPath)\n\n        fullimg = cv2.imread(path, 3)\n        width = fullimg.shape[0]\n        height = fullimg.shape[1]\n\n        cropped = fullimg[0:(width - (width % self.scale)), 0:(height - (height % self.scale)), :]\n        img = cv2.resize(cropped, None, fx=1. / self.scale, fy=1. / self.scale, interpolation=cv2.INTER_CUBIC)\n        floatimg = img.astype(np.float32) - self.mean\n\n        LR_input_ = floatimg.reshape(1, floatimg.shape[0], floatimg.shape[1], 3)\n\n        LR_tensor = graph.get_tensor_by_name(\"IteratorGetNext:0\")\n        HR_tensor = graph.get_tensor_by_name(\"NHWC_output:0\")\n\n        with tf.Session(graph=graph) as sess:\n            print(\"Loading pb...\")\n            output = sess.run(HR_tensor, feed_dict={LR_tensor: LR_input_})\n            Y = output[0]\n            HR_image = (Y + self.mean).clip(min=0, max=255)\n            HR_image = (HR_image).astype(np.uint8)\n\n            bicubic_image = cv2.resize(img, None, fx=self.scale, fy=self.scale, interpolation=cv2.INTER_CUBIC)\n\n            print(np.amax(Y), np.amax(LR_input_))\n            print(\"PSNR of  EDSR   upscaled image: {}\".format(self.psnr(cropped, HR_image)))\n            print(\"PSNR of bicubic upscaled image: {}\".format(self.psnr(cropped, bicubic_image)))\n\n            cv2.imshow('Original image', fullimg)\n            cv2.imshow('EDSR upscaled image', HR_image)\n            cv2.imshow('Bicubic upscaled image', bicubic_image)\n\n            cv2.imwrite(\"./images/EdsrOutput.png\", HR_image)\n            cv2.imwrite(\"./images/BicubicOutput.png\", bicubic_image)\n            cv2.imwrite(\"./images/original.png\", fullimg)\n            cv2.imwrite(\"./images/input.png\", img)\n\n            cv2.waitKey(0)\n            cv2.destroyAllWindows()\n            print(\"Done.\")\n\n        sess.close()\n\n    def upscaleFromPb(self, path):\n        \"\"\"\n        Upscale single image by desired model. This loads a .pb file.\n        \"\"\"\n        # Read model\n        pbPath = \"./models/EDSR_x{}.pb\".format(self.scale)\n\n        # Get graph\n        graph = self.load_pb(pbPath)\n\n        fullimg = cv2.imread(path, 3)\n        floatimg = fullimg.astype(np.float32) - self.mean\n        LR_input_ = floatimg.reshape(1, floatimg.shape[0], floatimg.shape[1], 3)\n\n        LR_tensor = graph.get_tensor_by_name(\"IteratorGetNext:0\")\n        HR_tensor = graph.get_tensor_by_name(\"NHWC_output:0\")\n\n        with tf.Session(graph=graph) as sess:\n            print(\"Loading pb...\")\n            output = sess.run(HR_tensor, feed_dict={LR_tensor: LR_input_})\n            Y = output[0]\n            HR_image = (Y + self.mean).clip(min=0, max=255)\n            HR_image = (HR_image).astype(np.uint8)\n\n            bicubic_image = cv2.resize(fullimg, None, fx=self.scale, fy=self.scale, interpolation=cv2.INTER_CUBIC)\n\n            cv2.imshow('Original image', fullimg)\n            cv2.imshow('EDSR upscaled image', HR_image)\n            cv2.imshow('Bicubic upscaled image', bicubic_image)\n\n            cv2.waitKey(0)\n            cv2.destroyAllWindows()\n\n        sess.close()\n\n    def export(self, quant):\n        print(\"Exporting model...\")\n\n        export_dir = \"./models/\"\n        if not os.path.exists(export_dir):\n                os.makedirs(export_dir)\n\n        export_file = \"EDSRorig_x{}.pb\".format(self.scale)\n\n        graph = tf.get_default_graph()\n        with graph.as_default():\n            with tf.Session(config=self.config) as sess:\n\n                ### Restore checkpoint\n                ckpt_name = self.ckpt_path + \"edsr_ckpt\" + \".meta\"\n                saver = tf.train.import_meta_graph(ckpt_name)\n                saver.restore(sess, tf.train.latest_checkpoint(self.ckpt_path))\n\n                # Return a serialized GraphDef representation of this graph\n                graph_def = sess.graph.as_graph_def()\n\n                # All variables to constants\n                graph_def = tf.graph_util.convert_variables_to_constants(sess, graph_def, ['NCHW_output'])\n\n                # Optimize for inference\n                graph_def = optimize_for_inference_lib.optimize_for_inference(graph_def, [\"IteratorGetNext\"],\n                                                                            [\"NCHW_output\"],  # [\"NHWC_output\"],\n                                                                            tf.float32.as_datatype_enum)\n                \n                # Implement certain file shrinking transforms. 2 is recommended.\n                transforms = [\"sort_by_execution_order\"]\n                if quant == 1:\n                    print(\"Rounding weights for export.\")\n                    transforms = [\"sort_by_execution_order\", \"round_weights\"]\n                    export_file = \"EDSR_x{}_q1.pb\".format(self.scale)\n                if quant == 2:\n                    print(\"Quantizing for export.\")\n                    transforms = [\"sort_by_execution_order\", \"quantize_weights\"]\n                    export_file = \"EDSR_x{}.pb\".format(self.scale)\n                if quant == 3:\n                    print(\"Round weights and quantizing for export.\")\n                    transforms = [\"sort_by_execution_order\", \"round_weights\", \"quantize_weights\"]\n                    export_file = \"EDSR_x{}_q3.pb\".format(self.scale)\n\n                graph_def = TransformGraph(graph_def, [\"IteratorGetNext\"],\n                                                      [\"NCHW_output\"],\n                                                      transforms)\n                \n                print(\"Exported file = {}\".format(export_dir+export_file))\n                with tf.gfile.GFile(export_dir + export_file, 'wb') as f:\n                    f.write(graph_def.SerializeToString())\n\n                tf.train.write_graph(graph_def, \".\", 'train.pbtxt')\n\n        sess.close()\n\n    def psnr(self, img1, img2):\n        mse = np.mean( (img1 - img2) ** 2 )\n        if mse == 0:\n            return 100\n        PIXEL_MAX = 255.0\n        return (20 * math.log10(PIXEL_MAX / math.sqrt(mse)))"
  }
]