[
  {
    "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": "# BokehMe: When Neural Rendering Meets Classical Rendering (CVPR 2022 Oral)\n\n[Juewen Peng](https://scholar.google.com/citations?hl=en&user=fYC6lCUAAAAJ)<sup>1</sup>,\n[Zhiguo Cao](http://english.aia.hust.edu.cn/info/1085/1528.htm)<sup>1</sup>,\n[Xianrui Luo](https://scholar.google.com/citations?hl=en&user=tUeWQ5AAAAAJ)<sup>1</sup>,\n[Hao Lu](http://faculty.hust.edu.cn/LUHAO/en/index.htm)<sup>1</sup>,\n[Ke Xian](https://sites.google.com/site/kexian1991/)<sup>1*</sup>,\n[Jianming Zhang](https://jimmie33.github.io/)<sup>2</sup>\n\n<sup>1</sup>Huazhong University of Science and Technology, <sup>2</sup>Adobe Research\n\n<p align=\"center\">\n<img src=https://user-images.githubusercontent.com/38718148/171405815-b3cc8799-27cd-457e-89df-686695187554.jpg />\n</p>\n\n### [Project](https://juewenpeng.github.io/BokehMe/) | [Paper](https://github.com/JuewenPeng/BokehMe/blob/main/pdf/BokehMe.pdf) | [Supp](https://github.com/JuewenPeng/BokehMe/blob/main/pdf/BokehMe-supp.pdf) | [Poster](https://github.com/JuewenPeng/BokehMe/blob/main/pdf/BokehMe-poster.pdf) | [Video](https://www.youtube.com/watch?v=e-zr_wCxNc8) | [Data](#blb-dataset)\n\nThis repository is the official PyTorch implementation of the CVPR 2022 paper \"BokehMe: When Neural Rendering Meets Classical Rendering\".\n\n\n**NOTE**: There is a citation mistake in the paper of the conference version. In section 4.1, the disparity maps of the EBB400 dataset are predicted by MiDaS [1] instead of DPT [2]. <!-- We have corrected it in the arXiv version. We apologize for this oversight and for any confusion that it may have caused.  --><br/>\n> [1] Towards Robust Monocular Depth Estimation: Mixing Datasets for Zero-shot Cross-dataset Transfer <br/>\n> [2] Vision Transformers for Dense Prediction\n\n\n\n## Installation\n```\ngit clone https://github.com/JuewenPeng/BokehMe.git\ncd BokehMe\npip install -r requirements.txt\n```\n\n\n## Usage\n```\npython demo.py --image_path 'inputs/21.jpg' --disp_path 'inputs/21.png' --save_dir 'outputs' --K 60 --disp_focus 90/255 --gamma 4 --highlight\n```\n- `image_path`:  path of the input all-in-focus image\n- `disp_path`: path of the input disparity map (predicted by [DPT](https://github.com/isl-org/DPT) in this example)\n- `save_dir`: directory to save the results\n- `K`: blur parameter\n- `disp_focus`: refocused disparity (range from 0 to 1)\n- `gamma`: gamma value (range from 1 to 5)\n- `highlight`: enhance RGB values of highlights before rendering for stunning bokeh balls\n\nSee `demo.py` for more details.\n\n\n\n\n## BLB Dataset\nThe BLB dataset is synthesized by Blender 2.93. It contains 10 scenes, each consisting of an all-in-focus image, a disparity map, a stack of bokeh images with 5 blur amounts and 10 refocused disparities, and a parameter file. We additionally provide 15 corrupted disparity maps (through gaussian blur, dilation, erosion) for each scene. Our BLB dataset can be downloaded from [Google Drive](https://drive.google.com/drive/folders/1URpab6AXQsNTqcBcighF73w5pFlvM0Ej?usp=sharing) or [Baidu Netdisk](https://pan.baidu.com/s/1U0XlFM_84-vVgnXGYz0ncQ?pwd=re8q).\n\n**Instructions**: \n- EXR images can be loaded by `image = cv2.imread(IMAGE_PATH, -1)[..., :3].astype(np.float32) ** (1/2.2)` . The loaded images are in BGR, so you can convert them to RGB by `image = cv2.cvtColor(image, cv2.COLOR_BGR2RGB)` if necessary.\n- EXR depth maps can be loaded by `depth = cv2.imread(DEPTH_PATH, -1)[..., 0].astype(np.float32)`. You can convert them to disparity maps by `disp = 1 / depth`. Note that it is **unnecesary** to normalize the disparity maps since we have pre-processed them to ensure that the signed defocus maps calculated by `K * (disp - disp_focus)` are in line with the experimental settings of the paper.\n- NOTE: Some pixel values of images may be larger than 1 for highlights (but mostly smaller than 1). Considering the fact that some rendering methods can only output values between 0 and 1, we clip the numerical ranges of the predicted bokeh images and the real ones to [0, 1] before evaluation. The main reason for this phenomenon (image values exceeding 1) is that the EXR images exported from Blender are in linear space, and we only process them with gamma 2.2 correction without tone mapping. We will improve it in the future.\n\n## Citation\nIf you find our work useful in your research, please cite our paper.\n\n```\n@inproceedings{Peng2022BokehMe,\n  title = {BokehMe: When Neural Rendering Meets Classical Rendering},\n  author = {Peng, Juewen and Cao, Zhiguo and Luo, Xianrui and Lu, Hao and Xian, Ke and Zhang, Jianming},\n  booktitle = {Proceedings of the IEEE/CVF International Conference on Computer Vision and Pattern Recognition (CVPR)},\n  year = {2022}\n}\n```\n"
  },
  {
    "path": "classical_renderer/scatter.py",
    "content": "#!/user/bin/env python3\n# -*- coding: utf-8 -*-\n\nimport torch\nimport torch.nn as nn\nimport torch.nn.functional as F\nimport cupy\nimport re\n\nkernel_Render_updateOutput = '''\n\n    extern \"C\" __global__ void kernel_Render_updateOutput(\n        const int n,\n        const float* image,          // original image\n        const float* defocus,        // signed defocus map\n        int* defocusDilate,          // signed defocus map after dilating\n        float* bokehCum,             // cumulative bokeh image\n        float* weightCum             // cumulative weight map\n    )\n    {\n        for (int intIndex = (blockIdx.x * blockDim.x) + threadIdx.x; intIndex < n; intIndex += blockDim.x * gridDim.x) {\n            const int intN = ( intIndex / SIZE_3(weightCum) / SIZE_2(weightCum) / SIZE_1(weightCum) ) % SIZE_0(weightCum);\n            // const int intC = ( intIndex / SIZE_3(weightCum) / SIZE_2(weightCum)                     ) % SIZE_1(weightCum);\n            const int intY = ( intIndex / SIZE_3(weightCum)                                         ) % SIZE_2(weightCum);\n            const int intX = ( intIndex                                                             ) % SIZE_3(weightCum);\n\n            float fltDefocus = VALUE_4(defocus, intN, 0, intY, intX);\n            float fltRadius = fabsf(fltDefocus);\n\n            for (int intDeltaY = -(int)(fltRadius)-1; intDeltaY <= (int)(fltRadius)+1; ++intDeltaY) {\n                for (int intDeltaX = -(int)(fltRadius)-1; intDeltaX <= (int)(fltRadius)+1; ++intDeltaX) {\n\n                    int intNeighborY = intY + intDeltaY;\n                    int intNeighborX = intX + intDeltaX;\n\n                    if ((intNeighborY >= 0) && (intNeighborY < SIZE_2(bokehCum)) && (intNeighborX >= 0) && (intNeighborX < SIZE_3(bokehCum))) {\n                        float fltDist = sqrtf((float)(intDeltaY)*(float)(intDeltaY) + (float)(intDeltaX)*(float)(intDeltaX));\n                        float fltWeight = (0.5 + 0.5 * tanhf(4 * (fltRadius - fltDist))) / (fltRadius * fltRadius + 0.2);\n                        if (fltRadius >= fltDist) {\n                            atomicMax(&defocusDilate[OFFSET_4(defocusDilate, intN, 0, intNeighborY, intNeighborX)], int(fltDefocus));\n                        }\n                        atomicAdd(&weightCum[OFFSET_4(weightCum, intN, 0, intNeighborY, intNeighborX)], fltWeight);\n                        atomicAdd(&bokehCum[OFFSET_4(bokehCum, intN, 0, intNeighborY, intNeighborX)], fltWeight * VALUE_4(image, intN, 0, intY, intX));\n                        atomicAdd(&bokehCum[OFFSET_4(bokehCum, intN, 1, intNeighborY, intNeighborX)], fltWeight * VALUE_4(image, intN, 1, intY, intX));\n                        atomicAdd(&bokehCum[OFFSET_4(bokehCum, intN, 2, intNeighborY, intNeighborX)], fltWeight * VALUE_4(image, intN, 2, intY, intX));\n                    }\n                }\n            }\n        }\n    }\n\n'''\n\n\ndef cupy_kernel(strFunction, objVariables):\n    strKernel = globals()[strFunction]\n\n    while True:\n        objMatch = re.search('(SIZE_)([0-4])(\\()([^\\)]*)(\\))', strKernel)\n\n        if objMatch is None:\n            break\n        # end\n\n        intArg = int(objMatch.group(2))\n\n        strTensor = objMatch.group(4)\n        intSizes = objVariables[strTensor].size()\n\n        strKernel = strKernel.replace(objMatch.group(), str(intSizes[intArg]))\n    # end\n\n    while True:\n        objMatch = re.search('(OFFSET_)([0-4])(\\()([^\\)]+)(\\))', strKernel)\n\n        if objMatch is None:\n            break\n        # end\n\n        intArgs = int(objMatch.group(2))\n        strArgs = objMatch.group(4).split(',')\n\n        strTensor = strArgs[0]\n        intStrides = objVariables[strTensor].stride()\n        strIndex = ['((' + strArgs[intArg + 1].replace('{', '(').replace('}', ')').strip() + ')*' + str(\n            intStrides[intArg]) + ')' for intArg in range(intArgs)]\n\n        strKernel = strKernel.replace(objMatch.group(0), '(' + str.join('+', strIndex) + ')')\n    # end\n\n    while True:\n        objMatch = re.search('(VALUE_)([0-4])(\\()([^\\)]+)(\\))', strKernel)\n\n        if objMatch is None:\n            break\n        # end\n\n        intArgs = int(objMatch.group(2))\n        strArgs = objMatch.group(4).split(',')\n\n        strTensor = strArgs[0]\n        intStrides = objVariables[strTensor].stride()\n        strIndex = ['((' + strArgs[intArg + 1].replace('{', '(').replace('}', ')').strip() + ')*' + str(\n            intStrides[intArg]) + ')' for intArg in range(intArgs)]\n\n        strKernel = strKernel.replace(objMatch.group(0), strTensor + '[' + str.join('+', strIndex) + ']')\n    # end\n\n    return strKernel\n# end\n\n\n# @cupy.util.memoize(for_each_device=True)\n@cupy.memoize(for_each_device=True)\ndef cupy_launch(strFunction, strKernel):\n    return cupy.cuda.compile_with_cache(strKernel).get_function(strFunction)\n# end\n\n\nclass _FunctionRender(torch.autograd.Function):\n    @staticmethod\n    def forward(self, image, defocus):\n        # self.save_for_backward(image, defocus)\n\n        defocus_dilate = defocus.int()\n        bokeh_cum = torch.zeros_like(image)\n        weight_cum = torch.zeros_like(defocus)\n\n        if defocus.is_cuda == True:\n            n = weight_cum.nelement()\n            cupy_launch('kernel_Render_updateOutput', cupy_kernel('kernel_Render_updateOutput', {\n                'image': image,\n                'defocus': defocus,\n                'defocusDilate': defocus_dilate,\n                'bokehCum': bokeh_cum,\n                'weightCum': weight_cum\n            }))(\n                grid=tuple([int((n + 512 - 1) / 512), 1, 1]),\n                block=tuple([512, 1, 1]),\n                args=[\n                    cupy.int(n),\n                    image.data_ptr(),\n                    defocus.data_ptr(),\n                    defocus_dilate.data_ptr(),\n                    bokeh_cum.data_ptr(),\n                    weight_cum.data_ptr()\n                ]\n            )\n\n        elif defocus.is_cuda == False:\n            raise NotImplementedError()\n\n        # end\n\n        return defocus_dilate.float(), bokeh_cum, weight_cum\n    # end\n\n    # @staticmethod\n    # def backward(self, gradBokehCum, gradWeightCum):\n    # end\n\n# end\n\n\ndef FunctionRender(image, defocus):\n    defocus_dilate, bokeh_cum, weight_cum = _FunctionRender.apply(image, defocus)\n\n    return defocus_dilate, bokeh_cum, weight_cum\n# end\n\n\nclass ModuleRenderScatter(torch.nn.Module):\n    def __init__(self):\n        super(ModuleRenderScatter, self).__init__()\n    # end\n\n    def forward(self, image, defocus):\n        defocus_dilate, bokeh_cum, weight_cum = FunctionRender(image, defocus)\n        bokeh = bokeh_cum / weight_cum\n        return bokeh, defocus_dilate\n    # end\n# end\n"
  },
  {
    "path": "classical_renderer/scatter_ex.py",
    "content": "#!/user/bin/env python3\n# -*- coding: utf-8 -*-\n\nimport torch\nimport cupy\nimport re\n\nkernel_Render_updateOutput = '''\n\n    extern \"C\" __global__ void kernel_Render_updateOutput(\n        const int n,\n        const int polySides,\n        const float initAngle,\n        const float* image,          // original image\n        const float* defocus,        // signed defocus map\n        int* defocusDilate,          // signed defocus map after dilating\n        float* bokehCum,             // cumulative bokeh image\n        float* weightCum             // cumulative weight map\n    )\n    {\n        // int polySides = 6;\n        float PI = 3.1415926536;\n        float fltAngle1 = 2 * PI / (float)(polySides);\n        float fltAngle2 = PI / 2 - PI / (float)(polySides);\n        // float initAngle = PI / 2;\n        float donutRatio = 0;  // (0 -> 0.5 : circle -> donut)\n\n        for (int intIndex = (blockIdx.x * blockDim.x) + threadIdx.x; intIndex < n; intIndex += blockDim.x * gridDim.x) {\n            const int intN = ( intIndex / SIZE_3(weightCum) / SIZE_2(weightCum) / SIZE_1(weightCum) ) % SIZE_0(weightCum);\n            // const int intC = ( intIndex / SIZE_3(weightCum) / SIZE_2(weightCum)                     ) % SIZE_1(weightCum);\n            const int intY = ( intIndex / SIZE_3(weightCum)                                         ) % SIZE_2(weightCum);\n            const int intX = ( intIndex                                                             ) % SIZE_3(weightCum);\n\n            float fltDefocus = VALUE_4(defocus, intN, 0, intY, intX);\n            float fltRadius = fabsf(fltDefocus);\n            float fltRadiusSquare = fltRadius * fltRadius;\n            // float fltWeight = 1.0 / (fltRadiusSquare + 0.4);\n\n            for (int intDeltaY = -(int)(fltRadius)-1; intDeltaY <= (int)(fltRadius)+1; intDeltaY++) {\n                for (int intDeltaX = -(int)(fltRadius)-1; intDeltaX <= (int)(fltRadius)+1; intDeltaX++) {\n\n                    int intNeighborY = intY + intDeltaY;\n                    int intNeighborX = intX + intDeltaX;\n\n                    float fltAngle = atan2f((float)(intDeltaY), (float)(intDeltaX));\n                    fltAngle = fmodf(fabsf(fltAngle + initAngle), fltAngle1);\n\n                    if ((intNeighborY >= 0) & (intNeighborY < SIZE_2(bokehCum)) & (intNeighborX >= 0) & (intNeighborX < SIZE_3(bokehCum))) {\n                        float fltDist = sqrtf((float)(intDeltaY)*(float)(intDeltaY) + (float)(intDeltaX)*(float)(intDeltaX));\n                        float fltWeight = (0.5 + 0.5 * tanhf(4 * (fltRadius * sinf(fltAngle2)/sinf(fltAngle+fltAngle2) - fltDist))) * (1 - donutRatio + donutRatio * tanhf(0.2 * (1 + fltDist - fltRadius * sinf(fltAngle2)/sinf(fltAngle+fltAngle2)))) / (fltRadius * fltRadius + 0.2);\n                        if (fltRadius >= fltDist) {\n                            atomicMax(&defocusDilate[OFFSET_4(defocusDilate, intN, 0, intNeighborY, intNeighborX)], int(fltDefocus));\n                        }\n                        atomicAdd(&weightCum[OFFSET_4(weightCum, intN, 0, intNeighborY, intNeighborX)], fltWeight);\n                        atomicAdd(&bokehCum[OFFSET_4(bokehCum, intN, 0, intNeighborY, intNeighborX)], fltWeight * VALUE_4(image, intN, 0, intY, intX));\n                        atomicAdd(&bokehCum[OFFSET_4(bokehCum, intN, 1, intNeighborY, intNeighborX)], fltWeight * VALUE_4(image, intN, 1, intY, intX));\n                        atomicAdd(&bokehCum[OFFSET_4(bokehCum, intN, 2, intNeighborY, intNeighborX)], fltWeight * VALUE_4(image, intN, 2, intY, intX));\n                    }\n                }\n            }\n        }\n    }\n\n'''\n\n\ndef cupy_kernel(strFunction, objVariables):\n    strKernel = globals()[strFunction]\n\n    while True:\n        objMatch = re.search('(SIZE_)([0-4])(\\()([^\\)]*)(\\))', strKernel)\n\n        if objMatch is None:\n            break\n        # end\n\n        intArg = int(objMatch.group(2))\n\n        strTensor = objMatch.group(4)\n        intSizes = objVariables[strTensor].size()\n\n        strKernel = strKernel.replace(objMatch.group(), str(intSizes[intArg]))\n    # end\n\n    while True:\n        objMatch = re.search('(OFFSET_)([0-4])(\\()([^\\)]+)(\\))', strKernel)\n\n        if objMatch is None:\n            break\n        # end\n\n        intArgs = int(objMatch.group(2))\n        strArgs = objMatch.group(4).split(',')\n\n        strTensor = strArgs[0]\n        intStrides = objVariables[strTensor].stride()\n        strIndex = ['((' + strArgs[intArg + 1].replace('{', '(').replace('}', ')').strip() + ')*' + str(\n            intStrides[intArg]) + ')' for intArg in range(intArgs)]\n\n        strKernel = strKernel.replace(objMatch.group(0), '(' + str.join('+', strIndex) + ')')\n    # end\n\n    while True:\n        objMatch = re.search('(VALUE_)([0-4])(\\()([^\\)]+)(\\))', strKernel)\n\n        if objMatch is None:\n            break\n        # end\n\n        intArgs = int(objMatch.group(2))\n        strArgs = objMatch.group(4).split(',')\n\n        strTensor = strArgs[0]\n        intStrides = objVariables[strTensor].stride()\n        strIndex = ['((' + strArgs[intArg + 1].replace('{', '(').replace('}', ')').strip() + ')*' + str(\n            intStrides[intArg]) + ')' for intArg in range(intArgs)]\n\n        strKernel = strKernel.replace(objMatch.group(0), strTensor + '[' + str.join('+', strIndex) + ']')\n    # end\n\n    return strKernel\n\n\n# end\n\n# @cupy.util.memoize(for_each_device=True)\n@cupy.memoize(for_each_device=True)\ndef cupy_launch(strFunction, strKernel):\n    return cupy.cuda.compile_with_cache(strKernel).get_function(strFunction)\n\n\n# end\n\nclass _FunctionRender(torch.autograd.Function):\n    @staticmethod\n    def forward(self, image, defocus, poly_sides, init_angle):\n        # self.save_for_backward(image, signedDisp)\n\n        defocus_dilate = defocus.int()\n        bokeh_cum = torch.zeros_like(image)\n        weight_cum = torch.zeros_like(defocus)\n\n        if defocus.is_cuda == True:\n            n = weight_cum.nelement()\n            cupy_launch('kernel_Render_updateOutput', cupy_kernel('kernel_Render_updateOutput', {\n                'poly_sides': poly_sides,\n                'init_angle': init_angle,\n                'image': image,\n                'defocus': defocus,\n                'defocusDilate': defocus_dilate,\n                'bokehCum': bokeh_cum,\n                'weightCum': weight_cum,\n            }))(\n                grid=tuple([int((n + 512 - 1) / 512), 1, 1]),\n                block=tuple([512, 1, 1]),\n                args=[\n                    cupy.int(n),\n                    cupy.int(poly_sides),\n                    cupy.float32(init_angle),\n                    image.data_ptr(),\n                    defocus.data_ptr(),\n                    defocus_dilate.data_ptr(),\n                    bokeh_cum.data_ptr(),\n                    weight_cum.data_ptr()\n                ]\n            )\n\n        elif defocus.is_cuda == False:\n            raise NotImplementedError()\n\n        # end\n\n        return defocus_dilate.float(), bokeh_cum, weight_cum\n    # end\n\n    # @staticmethod\n    # def backward(self, gradBokehCum, gradWeightCum):\n    # end\n\n# end\n\ndef FunctionRender(image, defocus, poly_sides, init_angle):\n    defocus_dilate, bokeh_cum, weight_cum = _FunctionRender.apply(image, defocus, poly_sides, init_angle)\n\n    return defocus_dilate, bokeh_cum, weight_cum\n# end\n\nclass ModuleRenderScatterEX(torch.nn.Module):\n    def __init__(self):\n        super(ModuleRenderScatterEX, self).__init__()\n    # end\n\n    def forward(self, image, defocus, poly_sides=10000, init_angle=3.1415926536/2):\n        defocus_dilate, bokeh_cum, weight_cum = FunctionRender(image, defocus, poly_sides, init_angle)\n        bokeh = bokeh_cum / weight_cum\n        return bokeh, defocus_dilate\n    # end\n# end\n"
  },
  {
    "path": "demo.py",
    "content": "#!/usr/bin/env python\n# encoding: utf-8\n\nimport os\n\n# os.environ['CUDA_VISIBLE_DEVICES'] = '7'\n\nimport matplotlib.pyplot as plt\nimport numpy as np\nimport cv2\nimport argparse\n\nimport torch\nimport torch.nn.functional as F\n\nfrom neural_renderer import ARNet, IUNet\n\nfrom classical_renderer.scatter import ModuleRenderScatter  # circular aperture\nfrom classical_renderer.scatter_ex import ModuleRenderScatterEX  # adjustable aperture shape\n\n\ndef gaussian_blur(x, r, sigma=None):\n    r = int(round(r))\n    if sigma is None:\n        sigma = 0.3 * (r - 1) + 0.8\n    x_grid, y_grid = torch.meshgrid(torch.arange(-int(r), int(r) + 1), torch.arange(-int(r), int(r) + 1))\n    kernel = torch.exp(-(x_grid ** 2 + y_grid ** 2) / 2 / sigma ** 2)\n    kernel = kernel.float() / kernel.sum()\n    kernel = kernel.expand(1, 1, 2*r+1, 2*r+1).to(x.device)\n    x = F.pad(x, pad=(r, r, r, r), mode='replicate')\n    x = F.conv2d(x, weight=kernel, padding=0)\n    return x\n\n\ndef pipeline(classical_renderer, arnet, iunet, image, defocus, gamma, args):\n    bokeh_classical, defocus_dilate = classical_renderer(image**gamma, defocus*args.defocus_scale)\n    # bokeh_classical, defocus_dilate = classical_renderer_ex(image**gamma, defocus*args.defocus_scale, poly_sides=6)\n\n    bokeh_classical = bokeh_classical ** (1/gamma)\n    defocus_dilate = defocus_dilate / args.defocus_scale\n    gamma = (gamma - args.gamma_min) / (args.gamma_max - args.gamma_min)\n    adapt_scale = max(defocus.abs().max().item(), 1)\n\n    image_re = F.interpolate(image, scale_factor=1/adapt_scale, mode='bilinear', align_corners=True)\n    defocus_re = 1 / adapt_scale * F.interpolate(defocus, scale_factor=1/adapt_scale, mode='bilinear', align_corners=True)\n    bokeh_neural, error_map = arnet(image_re, defocus_re, gamma)\n    error_map = F.interpolate(error_map, size=(image.shape[2], image.shape[3]), mode='bilinear', align_corners=True)\n    bokeh_neural.clamp_(0, 1e5)\n\n    if args.save_intermediate:\n        cv2.imwrite(os.path.join(save_root, 'bokeh_neural_s0.jpg'), bokeh_neural[0].cpu().permute(1, 2, 0).numpy()[..., ::-1] * 255)\n\n    scale = -1\n    for scale in range(int(np.log2(adapt_scale))):\n        ratio = 2**(scale+1) / adapt_scale\n        h_re, w_re = int(ratio * image.shape[2]), int(ratio * image.shape[3])\n        image_re = F.interpolate(image, size=(h_re, w_re), mode='bilinear', align_corners=True)\n        defocus_re = ratio * F.interpolate(defocus, size=(h_re, w_re), mode='bilinear', align_corners=True)\n        defocus_dilate_re = ratio * F.interpolate(defocus_dilate, size=(h_re, w_re), mode='bilinear', align_corners=True)\n        bokeh_neural_refine = iunet(image_re, defocus_re.clamp(-1, 1), bokeh_neural, gamma).clamp(0, 1e5)\n        mask = gaussian_blur(((defocus_dilate_re < 1) * (defocus_dilate_re > -1)).float(), 0.005 * (defocus_dilate_re.shape[2] + defocus_dilate_re.shape[3]))\n        bokeh_neural = mask * bokeh_neural_refine + (1 - mask) * F.interpolate(bokeh_neural, size=(h_re, w_re), mode='bilinear', align_corners=True)\n        if args.save_intermediate:\n            cv2.imwrite(os.path.join(save_root, f'bokeh_neural_s{scale+1}.jpg'), bokeh_neural[0].cpu().permute(1, 2, 0).numpy()[..., ::-1] * 255)\n            cv2.imwrite(os.path.join(save_root, f'fmask_neural_s{scale+1}.jpg'), mask[0][0].cpu().numpy() * 255)\n\n    bokeh_neural_refine = iunet(image, defocus.clamp(-1, 1), bokeh_neural, gamma).clamp(0, 1e5)\n    mask = gaussian_blur(((defocus_dilate < 1) * (defocus_dilate > -1)).float(), 0.005 * (defocus_dilate.shape[2] + defocus_dilate.shape[3]))\n    bokeh_neural = mask * bokeh_neural_refine + (1 - mask) * F.interpolate(bokeh_neural, size=(image.shape[2], image.shape[3]), mode='bilinear', align_corners=True)\n    if args.save_intermediate:\n        cv2.imwrite(os.path.join(save_root, f'bokeh_neural_s{scale+2}.jpg'), bokeh_neural[0].cpu().permute(1, 2, 0).numpy()[..., ::-1] * 255)\n        cv2.imwrite(os.path.join(save_root, f'fmask_neural_s{scale+2}.jpg'), mask[0][0].cpu().numpy() * 255)\n\n    bokeh_pred = bokeh_classical * (1 - error_map) + bokeh_neural * error_map\n\n    return bokeh_pred.clamp(0, 1), bokeh_classical.clamp(0, 1), bokeh_neural.clamp(0, 1), error_map\n\n\n\n\ndevice = torch.device('cuda' if torch.cuda.is_available() else 'cpu')\n\nparser = argparse.ArgumentParser(description='Bokeh Rendering', fromfile_prefix_chars='@')\n\n\nparser.add_argument('--defocus_scale',               type=float, default=10.)\nparser.add_argument('--gamma_min',                   type=float, default=1.)\nparser.add_argument('--gamma_max',                   type=float, default=5.)\n\n# Model 1\nparser.add_argument('--arnet_shuffle_rate',          type=int,   default=2)\nparser.add_argument('--arnet_in_channels',           type=int,   default=5)\nparser.add_argument('--arnet_out_channels',          type=int,   default=4)\nparser.add_argument('--arnet_middle_channels',       type=int,   default=128)\nparser.add_argument('--arnet_num_block',             type=int,   default=3)\nparser.add_argument('--arnet_share_weight',                      action='store_true')\nparser.add_argument('--arnet_connect_mode',          type=str,   default='distinct_source')\nparser.add_argument('--arnet_use_bn',                            action='store_true')\nparser.add_argument('--arnet_activation',            type=str,   default='elu')\n\n# Model 2\nparser.add_argument('--iunet_shuffle_rate',          type=int,   default=2)\nparser.add_argument('--iunet_in_channels',           type=int,   default=8)\nparser.add_argument('--iunet_out_channels',          type=int,   default=3)\nparser.add_argument('--iunet_middle_channels',       type=int,   default=64)\nparser.add_argument('--iunet_num_block',             type=int,   default=3)\nparser.add_argument('--iunet_share_weight',                      action='store_true')\nparser.add_argument('--iunet_connect_mode',          type=str,   default='distinct_source')\nparser.add_argument('--iunet_use_bn',                            action='store_true')\nparser.add_argument('--iunet_activation',            type=str,   default='elu')\n\n# Checkpoint\nparser.add_argument('--arnet_checkpoint_path',       type=str,   default='./checkpoints/arnet.pth')\nparser.add_argument('--iunet_checkpoint_path',       type=str,   default='./checkpoints/iunet.pth')\n\n# Input\nparser.add_argument('--image_path',                  type=str,   default='./inputs/21.jpg')\nparser.add_argument('--disp_path',                   type=str,   default='./inputs/21.png')\nparser.add_argument('--save_dir',                    type=str,   default='./outputs')\nparser.add_argument('--K',                           type=float, default=60,          help='blur parameter')\nparser.add_argument('--disp_focus',                  type=float, default=90/255,      help='refocused disparity (0~1)')\nparser.add_argument('--gamma',                       type=float, default=4,           help='gamma value (1~5)')\n\nparser.add_argument('--highlight',                               action='store_true', help='forcibly enchance RGB values of highlights')\nparser.add_argument('--highlight_RGB_threshold',     type=float, default=220/255)\nparser.add_argument('--highlight_enhance_ratio',     type=float, default=0.4)\n\nparser.add_argument('--save_intermediate',                       action='store_true', help='save intermediate results')\n\nargs = parser.parse_args()\n\narnet_checkpoint_path = args.arnet_checkpoint_path\niunet_checkpoint_path = args.iunet_checkpoint_path\n\nclassical_renderer = ModuleRenderScatter().to(device)\n# classical_renderer_ex = ModuleRenderScatterEX().to(device)\n\narnet = ARNet(args.arnet_shuffle_rate, args.arnet_in_channels, args.arnet_out_channels, args.arnet_middle_channels,\n              args.arnet_num_block, args.arnet_share_weight, args.arnet_connect_mode, args.arnet_use_bn, args.arnet_activation)\niunet = IUNet(args.iunet_shuffle_rate, args.iunet_in_channels, args.iunet_out_channels, args.iunet_middle_channels,\n              args.iunet_num_block, args.iunet_share_weight, args.iunet_connect_mode, args.iunet_use_bn, args.iunet_activation)\n\narnet.cuda()\niunet.cuda()\n\ncheckpoint = torch.load(arnet_checkpoint_path)\narnet.load_state_dict(checkpoint['model'])\ncheckpoint = torch.load(iunet_checkpoint_path)\niunet.load_state_dict(checkpoint['model'])\n\narnet.eval()\niunet.eval()\n\nsave_root = os.path.join(args.save_dir, os.path.splitext(os.path.basename(args.image_path))[0])\nos.makedirs(save_root, exist_ok=True)\n\nK = args.K                     # blur parameter\ndisp_focus = args.disp_focus   # 0~1\ngamma = args.gamma             # 1~5\n\nimage = cv2.imread(args.image_path).astype(np.float32) / 255.0\nimage = cv2.cvtColor(image, cv2.COLOR_BGR2RGB)\nimage_ori = image.copy()\n\ndisp = np.float32(cv2.imread(args.disp_path, cv2.IMREAD_GRAYSCALE))\ndisp = (disp - disp.min()) / (disp.max() - disp.min())\n\n########## Highlights ##########\nif args.highlight:\n    mask1 = np.clip(np.tanh(200 * (np.abs(disp - disp_focus)**2 - 0.01)), 0, 1)[..., np.newaxis]  # out-of-focus areas\n    # mask2 = (np.max(image, axis=2, keepdims=True) > args.highlight_RGB_threshold)  # highlight areas\n    mask2 = np.clip(np.tanh(10*(image - args.highlight_RGB_threshold)), 0, 1)    # highlight areas\n    mask = mask1 * mask2\n    image = image * (1 + mask * args.highlight_enhance_ratio)\n################################\n\n\ndefocus = K * (disp - disp_focus) / args.defocus_scale\n\nwith torch.no_grad():\n    image = torch.from_numpy(image).permute(2, 0, 1).unsqueeze(0)\n    defocus = torch.from_numpy(defocus).unsqueeze(0).unsqueeze(0)\n    image = image.cuda()\n    defocus = defocus.cuda()\n\n    bokeh_pred, bokeh_classical, bokeh_neural, error_map = pipeline(\n        classical_renderer, arnet, iunet, image, defocus, gamma, args\n    )\n\n\ndefocus = defocus[0][0].cpu().numpy()\nerror_map = error_map[0][0].cpu().numpy()\nbokeh_classical = bokeh_classical[0].cpu().permute(1, 2, 0).numpy()\nbokeh_neural = bokeh_neural[0].cpu().permute(1, 2, 0).detach().numpy()\nbokeh_pred = bokeh_pred[0].cpu().permute(1, 2, 0).detach().numpy()\n\ncv2.imwrite(os.path.join(save_root, 'image.jpg'), image_ori[..., ::-1] * 255)\nplt.imsave(os.path.join(save_root, 'defocus.jpg'), defocus, cmap='coolwarm', vmin=-max(defocus.max(), -defocus.min()), vmax=max(defocus.max(), -defocus.min()))\ncv2.imwrite(os.path.join(save_root, 'disparity.jpg'), disp * 255)\ncv2.imwrite(os.path.join(save_root, 'error_map.jpg'), error_map * 255)\ncv2.imwrite(os.path.join(save_root, 'bokeh_classical.jpg'), bokeh_classical[..., ::-1] * 255)\ncv2.imwrite(os.path.join(save_root, 'bokeh_neural.jpg'), bokeh_neural[..., ::-1] * 255)\ncv2.imwrite(os.path.join(save_root, 'bokeh_pred.jpg'), bokeh_pred[..., ::-1] * 255)\n"
  },
  {
    "path": "neural_renderer.py",
    "content": "#!/usr/bin/env python\n# encoding: utf-8\nimport os\n\n# os.environ['CUDA_VISIBLE_DEVICES'] = '5'\n\nimport torch\nimport torch.nn as nn\nimport torch.nn.functional as F\n\n\nclass Space2Depth(nn.Module):\n    def __init__(self, down_factor):\n        super(Space2Depth, self).__init__()\n        self.down_factor = down_factor\n\n    def forward(self, x):\n        n, c, h, w = x.size()\n        unfolded_x = torch.nn.functional.unfold(x, self.down_factor, stride=self.down_factor)\n        return unfolded_x.view(n, c * self.down_factor ** 2, h // self.down_factor, w // self.down_factor)\n\n\ndef conv_bn_activation(in_channels, out_channels, kernel_size, stride, padding, use_bn, activation):\n    module = nn.Sequential()\n    # module.add_module('pad', nn.ReflectionPad2d(padding))\n    module.add_module('conv', nn.Conv2d(in_channels, out_channels, kernel_size, stride, padding))\n    module.add_module('bn', nn.BatchNorm2d(out_channels)) if use_bn else None\n    module.add_module('activation', activation) if activation else None\n\n    return module\n\n\nclass BlockStack(nn.Module):\n    def __init__(self, channels, num_block, share_weight, connect_mode, use_bn, activation):\n        # connect_mode: refer to \"Fast and Accurate Image Super-Resolution with Deep Laplacian Pyramid Networks\"\n        super(BlockStack, self).__init__()\n\n        self.num_block = num_block\n        self.connect_mode = connect_mode\n\n        self.blocks = nn.ModuleList()\n\n        if share_weight is True:\n            block = nn.Sequential(\n                conv_bn_activation(\n                    in_channels=channels,\n                    out_channels=channels,\n                    kernel_size=3, stride=1, padding=1,\n                    use_bn=use_bn, activation=activation\n                ),\n                conv_bn_activation(\n                    in_channels=channels,\n                    out_channels=channels,\n                    kernel_size=3, stride=1, padding=1,\n                    use_bn=use_bn, activation=activation\n                )\n            )\n            for i in range(num_block):\n                self.blocks.append(block)\n\n        else:\n            for i in range(num_block):\n                block = nn.Sequential(\n                    conv_bn_activation(\n                        in_channels=channels,\n                        out_channels=channels,\n                        kernel_size=3, stride=1, padding=1,\n                        use_bn=use_bn, activation=activation\n                    ),\n                    conv_bn_activation(\n                        in_channels=channels,\n                        out_channels=channels,\n                        kernel_size=3, stride=1, padding=1,\n                        use_bn=use_bn, activation=activation\n                    )\n                )\n                self.blocks.append(block)\n\n    def forward(self, x):\n        if self.connect_mode == 'no':\n            for i in range(self.num_block):\n                x = self.blocks[i](x)\n        elif self.connect_mode == 'distinct_source':\n            for i in range(self.num_block):\n                x = self.blocks[i](x) + x\n        elif self.connect_mode == 'shared_source':\n            x0 = x\n            for i in range(self.num_block):\n                x = self.blocks[i](x) + x0\n        else:\n            print('\"connect_mode\" error!')\n            exit(0)\n        return x\n\n\nclass ARNet(nn.Module):  # Adaptive Rendering Network\n    def __init__(self, shuffle_rate=2, in_channels=5, out_channels=4, middle_channels=128, num_block=3, share_weight=False, connect_mode='distinct_source', use_bn=False, activation='elu'):\n        super(ARNet, self).__init__()\n\n        self.shuffle_rate = shuffle_rate\n        self.connect_mode = connect_mode\n\n        if activation == 'relu':\n            activation = nn.ReLU(inplace=True)\n        elif activation == 'leaky_relu':\n            activation = nn.LeakyReLU(inplace=True)\n        elif activation == 'elu':\n            activation = nn.ELU(inplace=True)\n        else:\n            print('\"activation\" error!')\n            exit(0)\n\n        self.downsample = Space2Depth(shuffle_rate)\n        self.conv0 = conv_bn_activation(\n            in_channels=(in_channels - 1) * shuffle_rate ** 2 + 1,\n            out_channels=middle_channels,\n            kernel_size=3, stride=1, padding=1,\n            use_bn=use_bn, activation=activation\n        )\n        self.block_stack = BlockStack(\n            channels=middle_channels,\n            num_block=num_block, share_weight=share_weight, connect_mode=connect_mode,\n            use_bn=use_bn, activation=activation\n        )\n        self.conv1 = conv_bn_activation(\n            in_channels=middle_channels,\n            out_channels=out_channels * shuffle_rate ** 2,\n            kernel_size=3, stride=1, padding=1,\n            use_bn=False, activation=None\n        )\n        self.upsample = nn.PixelShuffle(shuffle_rate)\n\n    def forward(self, image, defocus, gamma):\n        _, _, h, w = image.shape\n        h_re = int(h // self.shuffle_rate * self.shuffle_rate)\n        w_re = int(w // self.shuffle_rate * self.shuffle_rate)\n        x = torch.cat((image, defocus), dim=1)\n        x = F.interpolate(x, size=(h_re, w_re), mode='bilinear', align_corners=True)\n        x = self.downsample(x)\n        gamma = torch.ones_like(x[:, :1]) * gamma\n        x = torch.cat((x, gamma), dim=1)\n        x = self.conv0(x)\n        x = self.block_stack(x)\n        x = self.conv1(x)\n        x = self.upsample(x)\n        x = F.interpolate(x, size=(h, w), mode='bilinear', align_corners=True)\n\n        bokeh = x[:, :-1]\n        mask = torch.sigmoid(x[:, -1:])\n\n        return bokeh, mask\n\n\nclass IUNet(nn.Module):  # Iterative Upsampling Network\n    def __init__(self, shuffle_rate=2, in_channels=8, out_channels=3, middle_channels=64, num_block=3, share_weight=False, connect_mode='distinct_source', use_bn=False, activation='elu'):\n        super(IUNet, self).__init__()\n\n        self.shuffle_rate = shuffle_rate\n        self.connect_mode = connect_mode\n\n        if activation == 'relu':\n            activation = nn.ReLU(inplace=True)\n        elif activation == 'leaky_relu':\n            activation = nn.LeakyReLU(inplace=True)\n        elif activation == 'elu':\n            activation = nn.ELU(inplace=True)\n        else:\n            print('\"activation\" error!')\n            exit(0)\n\n        self.downsample = Space2Depth(shuffle_rate)\n        self.conv0 = conv_bn_activation(\n            in_channels=(in_channels - 4) * shuffle_rate ** 2 + 4,\n            out_channels=middle_channels,\n            kernel_size=3, stride=1, padding=1,\n            use_bn=use_bn, activation=activation\n        )\n        self.block_stack = BlockStack(\n            channels=middle_channels,\n            num_block=num_block, share_weight=share_weight, connect_mode=connect_mode,\n            use_bn=use_bn, activation=activation\n        )\n        self.conv1 = conv_bn_activation(\n            in_channels=middle_channels,\n            out_channels=out_channels * shuffle_rate ** 2,\n            kernel_size=3, stride=1, padding=1,\n            use_bn=False, activation=None\n        )\n        self.upsample = nn.PixelShuffle(shuffle_rate)\n\n    def forward(self, image, defocus, bokeh_coarse, gamma):\n        _, _, h, w = image.shape\n        h_re = int(h // self.shuffle_rate * self.shuffle_rate)\n        w_re = int(w // self.shuffle_rate * self.shuffle_rate)\n        x = torch.cat((image, defocus), dim=1)\n        x = F.interpolate(x, size=(h_re, w_re), mode='bilinear', align_corners=True)\n        x = self.downsample(x)\n        if bokeh_coarse.shape[2] != x.shape[2] or bokeh_coarse.shape[3] != x.shape[3]:\n            bokeh_coarse = F.interpolate(bokeh_coarse, size=(x.shape[2], x.shape[3]), mode='bilinear', align_corners=False)\n        gamma = torch.ones_like(x[:, :1]) * gamma\n        x = torch.cat((x, bokeh_coarse, gamma), dim=1)\n        x = self.conv0(x)\n        x = self.block_stack(x)\n        x = self.conv1(x)\n        x = self.upsample(x)\n        bokeh_refine = F.interpolate(x, size=(h, w), mode='bilinear', align_corners=True)\n\n        return bokeh_refine\n"
  },
  {
    "path": "requirements.txt",
    "content": "cupy==10.5.0\ncupy_cuda90==7.7.0\nmatplotlib==3.5.1\nnumpy==1.18.5\nopencv_python==4.2.0.34\nPillow==9.1.1\ntorch==1.8.1\ntorchvision==0.9.1\n"
  }
]