[
  {
    "path": ".gitignore",
    "content": "# Byte-compiled / optimized / DLL files\n__pycache__/\n*.py[cod]\n*$py.class\n\n# C extensions\n*.so\n\n# Distribution / packaging\n.Python\nbuild/\ndevelop-eggs/\ndist/\ndownloads/\neggs/\n.eggs/\nlib/\nlib64/\nparts/\nsdist/\nvar/\nwheels/\npip-wheel-metadata/\nshare/python-wheels/\n*.egg-info/\n.installed.cfg\n*.egg\nMANIFEST\n\n# PyInstaller\n#  Usually these files are written by a python script from a template\n#  before PyInstaller builds the exe, so as to inject date/other infos into it.\n*.manifest\n*.spec\n\n# Installer logs\npip-log.txt\npip-delete-this-directory.txt\n\n# Unit test / coverage reports\nhtmlcov/\n.tox/\n.nox/\n.coverage\n.coverage.*\n.cache\nnosetests.xml\ncoverage.xml\n*.cover\n*.py,cover\n.hypothesis/\n.pytest_cache/\n\n# Translations\n*.mo\n*.pot\n\n# Django stuff:\n*.log\nlocal_settings.py\ndb.sqlite3\ndb.sqlite3-journal\n\n# Flask stuff:\ninstance/\n.webassets-cache\n\n# Scrapy stuff:\n.scrapy\n\n# Sphinx documentation\ndocs/_build/\n\n# PyBuilder\ntarget/\n\n# Jupyter Notebook\n.ipynb_checkpoints\n\n# IPython\nprofile_default/\nipython_config.py\n\n# pyenv\n.python-version\n\n# pipenv\n#   According to pypa/pipenv#598, it is recommended to include Pipfile.lock in version control.\n#   However, in case of collaboration, if having platform-specific dependencies or dependencies\n#   having no cross-platform support, pipenv may install dependencies that don't work, or not\n#   install all needed dependencies.\n#Pipfile.lock\n\n# PEP 582; used by e.g. github.com/David-OConnor/pyflow\n__pypackages__/\n\n# Celery stuff\ncelerybeat-schedule\ncelerybeat.pid\n\n# SageMath parsed files\n*.sage.py\n\n# Environments\n.env\n.venv\nenv/\nvenv/\nENV/\nenv.bak/\nvenv.bak/\n\n# Spyder project settings\n.spyderproject\n.spyproject\n\n# Rope project settings\n.ropeproject\n\n# mkdocs documentation\n/site\n\n# mypy\n.mypy_cache/\n.dmypy.json\ndmypy.json\n\n# Pyre type checker\n.pyre/\n"
  },
  {
    "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": "# TiNeuVox: Time-Aware Neural Voxels\n## ACM SIGGRAPH Asia 2022\n\n### [Project Page](https://jaminfong.cn/tineuvox) | [ACM Paper](https://dl.acm.org/doi/10.1145/3550469.3555383) | [Arxiv Paper](https://arxiv.org/abs/2205.15285) | [Video](https://youtu.be/sROLfK_VkCk)\n\n[Fast Dynamic Radiance Fields with Time-Aware Neural Voxels](https://jaminfong.cn/tineuvox)   \n[Jiemin Fang](https://jaminfong.cn/)<sup>1,2*</sup>, [Taoran Yi](https://github.com/taoranyi)<sup>2*</sup>, [Xinggang Wang](https://xinggangw.info/)<sup>✉2</sup>, [Lingxi Xie](http://lingxixie.com/)<sup>3</sup>, </br>[Xiaopeng Zhang](https://sites.google.com/site/zxphistory/)<sup>3</sup>, [Wenyu Liu](http://eic.hust.edu.cn/professor/liuwenyu/)<sup>2</sup>, [Matthias Nießner](https://niessnerlab.org/members/matthias_niessner/profile.html)<sup>4</sup>, [Qi Tian](https://scholar.google.com/citations?hl=en&user=61b6eYkAAAAJ)<sup>3</sup>  \n<sup>1</sup>Institute of AI, HUST &emsp; <sup>2</sup>School of EIC, HUST &emsp; <sup>3</sup>Huawei Cloud &emsp; <sup>4</sup>TUM\n\n---------------------------------------------------\n![block](./imgs/render_demo.gif)   \nOur method converges very quickly. This is a comparison between D-NeRF (left) and our method (right). \n\n![block](./imgs/rep_img.jpg)\nWe propose a radiance field framework by representing scenes with time-aware voxel features, named as TiNeuVox. A tiny coordinate deformation network is introduced to model coarse motion trajectories and temporal information is further enhanced in the radiance network. A multi-distance interpolation method is proposed and applied on voxel features to model both small and large motions. Our framework significantly accelerates the optimization of dynamic radiance fields while maintaining high rendering quality. Empirical evaluation is performed on both syntheticand real scenes. Our TiNeuVox completes training with only **8 minutes** and **8-MB** storage cost while showing similar or even better rendering performance than previous dynamic NeRF methods.\n\n## Notes\n* *May. 31, 2022* The first and preliminary version is realeased. Code may not be cleaned thoroughly, so feel free to open an issue if any question.\n\n\n## Requirements\n* lpips\n* mmcv\n* imageio\n* imageio-ffmpeg\n* opencv-python\n* pytorch_msssim\n* torch\n* torch_scatter\n\n## Data Preparation\n**For synthetic scenes:**  \nThe dataset provided in [D-NeRF](https://github.com/albertpumarola/D-NeRF) is used. You can download the dataset from [dropbox](https://www.dropbox.com/s/0bf6fl0ye2vz3vr/data.zip?dl=0). Then organize your dataset as follows.\n```\n├── data_dnerf \n│   ├── mutant\n│   ├── standup \n│   ├── ...\n```\n\n**For real dynamic scenes:**  \nThe dataset provided in [HyperNeRF](https://github.com/google/hypernerf) is used. You can download scenes from [Hypernerf Dataset](https://github.com/google/hypernerf/releases/tag/v0.1) and organize them as [Nerfies](https://github.com/google/nerfies#datasets).\n\n\n\n## Training\nFor training synthetic scenes such as `standup`, run \n``` \npython run.py --config configs/nerf-*/standup.py \n``` \nUse `small` for TiNeuVox-S and `base` for TiNeuVox-B.\nUse `--render_video` to render a video.\n\nFor training real scenes such as `vrig_chicken`, run \n``` \npython run.py --config configs/vrig_dataset/chicken.py  \n``` \n\n## Evaluation\nRun the following script to evaluate the model.  \n\n**For synthetic ones:**  \n```\npython run.py --config configs/nerf-small/standup.py --render_test --render_only --eval_psnr --eval_lpips_vgg --eval_ssim \n```\n\n**For real ones:**  \n```\npython run.py --config configs/vrig_dataset/chicken.py --render_test --render_only --eval_psnr\n```\n\nTo fairly compare with values reported in D-NeRF, `metric.py` is provided to directly evaluate the rendered images with `uint8` values.\n\n## Main Results   \nPlease visit our [video](https://youtu.be/sROLfK_VkCk) for more rendered videos.\n\n### Synthetic Scenes\n\n| **Method** | **w/Time Enc.**  | **w/Explicit Rep.** |**Time** | **Storage** | **PSNR** | **SSIM** | **LPIPS** |\n|:-:|:-:|:-:|:-:|:-:|:-:|:-:|:-:|\n| NeRF | ✗ |✗ |∼ hours |5 MB |19.00 |0.87 |0.18\nDirectVoxGO | ✗ |✓ |5 mins |205 MB |18.61| 0.85| 0.17\nPlenoxels |✗ |✓ |6 mins| 717 MB |20.24 |0.87 |0.16\nT-NeRF  |✓ |✗ |∼ hours |– |29.51 |0.95 |0.08\nD-NeRF | ✓ |✗ |20 hours |4 MB |30.50 |0.95 |0.07\nTiNeuVox-S (ours)| ✓ |✓ |8 mins |8 MB |30.75 |0.96 |0.07\nTiNeuVox-B (ours)| ✓ |✓ |28 mins |48 MB |32.67 |0.97 |0.04\n\n### Real Dynamic Scenes\n| **Method** | **Time** | **PSNR** | **MS-SSIM** |\n|:-:|:-:|:-:|:-:|\nNeRF |∼ hours |20.1 |0.745\nNV | ∼ hours |16.9 |0.571\nNSFF | ∼ hours |26.3 |0.916\nNerfies | ∼ hours |22.2 |0.803\nHyperNeRF | 32 hours |22.4 |0.814\nTiNeuVox-S (ours) |10 mins |23.4 |0.813\nTiNeuVox-B (ours) |30 mins |24.3 |0.837\n\n## Acknowledgements\nThis repository is partially based on [DirectVoxGO](https://github.com/sunset1995/directvoxgo) and [D-NeRF](https://github.com/albertpumarola/D-NeRF). Thanks for their awesome works.\n\n\n## Citation\nIf you find this repository/work helpful in your research, welcome to cite the paper and give a ⭐.\n```\n@inproceedings{TiNeuVox,\n  author = {Fang, Jiemin and Yi, Taoran and Wang, Xinggang and Xie, Lingxi and Zhang, Xiaopeng and Liu, Wenyu and Nie\\ss{}ner, Matthias and Tian, Qi},\n  title = {Fast Dynamic Radiance Fields with Time-Aware Neural Voxels},\n  year = {2022},\n  booktitle = {SIGGRAPH Asia 2022 Conference Papers}\n}\n```\n"
  },
  {
    "path": "configs/misc/espresso.py",
    "content": "_base_ = './hyper_default.py'\n\nexpname = 'misc/espresso'\nbasedir = './logs/vrig_data'\n\ndata = dict(\n    datadir='./espresso',\n    dataset_type='hyper_dataset',\n    white_bkgd=False,\n)"
  },
  {
    "path": "configs/misc/hyper_default.py",
    "content": "from copy import deepcopy\n\nexpname = None                    # experiment name\nbasedir = './logs/'               # where to store ckpts and logs\n\n''' Template of data options\n'''\ndata = dict(\n    datadir=None,                 # path to dataset root folder\n    dataset_type=None,            \n    load2gpu_on_the_fly=True,    # do not load all images into gpu (to save gpu memory)\n    testskip=1,                   # subsample testset to preview results\n    white_bkgd=False,             # use white background (note that some dataset don't provide alpha and with blended bg color)\n    half_res=True,              \n    factor=4,                     \n    ndc=False,                    # use ndc coordinate (only for forward-facing; not support yet)\n    spherify=False,               # inward-facing\n    llffhold=8,                   # testsplit\n    load_depths=False,            # load depth\n    use_bg_points=True,\n    add_cam=True,\n\n)\n\n''' Template of training options\n'''\ntrain_config = dict(\n    N_iters=20000,                # number of optimization steps\n    N_rand=4096,                  # batch size (number of random rays per optimization step)\n    lrate_feature=1e-1,           # lr of voxel grid\n    lrate_featurenet=1e-3,\n    lrate_deformation_net=7e-4,\n    lrate_densitynet=1e-3,\n    lrate_timenet=1e-3,\n    lrate_camnet=1e-3,\n    lrate_rgbnet=1e-3,           # lr of the mlp \n    lrate_decay=20,               # lr decay by 0.1 after every lrate_decay*1000 steps\n    ray_sampler='in_maskcache',        # ray sampling strategies\n    weight_main=1.0,              # weight of photometric loss\n    weight_entropy_last=0.001,\n    weight_rgbper=0.01,            # weight of per-point rgb loss\n    tv_every=1,                   # count total variation loss every tv_every step\n    tv_after=0,                   # count total variation loss from tv_from step\n    tv_before=1e9,                   # count total variation before the given number of iterations\n    tv_feature_before=10000,            # count total variation densely before the given number of iterations\n    weight_tv_feature=1e-5,\n    pg_scale=[2000, 4000, 6000, 8000],\n    skip_zero_grad_fields=['feature'],\n)\n\n''' Template of model and rendering options\n'''\n\nmodel_and_render = dict(\n    num_voxels=160**3,          # expected number of voxel\n    num_voxels_base=160**3,      # to rescale delta distance\n    voxel_dim=6,                 # feature voxel grid dim\n    defor_depth=3,               # depth of the deformation MLP \n    net_width=256,             # width of the  MLP\n    alpha_init=1e-3,              # set the alpha values everywhere at the begin of training\n    fast_color_thres=1e-4,           # threshold of alpha value to skip the fine stage sampled point\n    stepsize=0.5,                 # sampling stepsize in volume rendering\n    world_bound_scale=1.05,\n)\n\n\n\ndel deepcopy\n"
  },
  {
    "path": "configs/nerf-base/bouncingballs.py",
    "content": "_base_ = './default.py'\n\nexpname = 'base/dnerf_bouncingballs-400'\nbasedir = './logs/nerf_synthetic'\n\ndata = dict(\n    datadir='/data_dnerf/bouncingballs',\n    dataset_type='dnerf',\n    white_bkgd=True,\n)\n\n"
  },
  {
    "path": "configs/nerf-base/default.py",
    "content": "from copy import deepcopy\n\nexpname = None                    # experiment name\nbasedir = './logs/'               # where to store ckpts and logs\n\n''' Template of data options\n'''\ndata = dict(\n    datadir=None,                 # path to dataset root folder\n    dataset_type=None,            \n    load2gpu_on_the_fly=False,    # do not load all images into gpu (to save gpu memory)\n    testskip=1,                   # subsample testset to preview results\n    white_bkgd=False,             # use white background (note that some dataset don't provide alpha and with blended bg color)\n    half_res=True,              \n    factor=4,                     \n    ndc=False,                    # use ndc coordinate (only for forward-facing; not support yet)\n    spherify=False,               # inward-facing\n    llffhold=8,                   # testsplit\n    load_depths=False,            # load depth\n    use_bg_points=False,\n    add_cam=False,\n)\n\n''' Template of training options\n'''\ntrain_config = dict(\n    N_iters=20000,                # number of optimization steps\n    N_rand=4096,                  # batch size (number of random rays per optimization step)\n    lrate_feature=8e-2,           # lr of  voxel grid\n    lrate_featurenet=8e-4,\n    lrate_deformation_net=6e-4,\n    lrate_densitynet=8e-4,\n    lrate_timenet=8e-4,\n    lrate_rgbnet=8e-4,           # lr of the mlp  \n    lrate_decay=20,               # lr decay by 0.1 after every lrate_decay*1000 steps\n    ray_sampler='in_maskcache',        # ray sampling strategies\n    weight_main=1.0,              # weight of photometric loss\n    weight_entropy_last=0.001,\n    weight_rgbper=0.01,            # weight of per-point rgb loss\n    tv_every=1,                   # count total variation loss every tv_every step\n    tv_after=0,                   # count total variation loss from tv_from step\n    tv_before=1e9,                   # count total variation before the given number of iterations\n    tv_feature_before=10000,            # count total variation densely before the given number of iterations\n    weight_tv_feature=0,\n    pg_scale=[2000, 4000, 6000],\n    skip_zero_grad_fields=['feature'],\n)\n\n''' Template of model and rendering options\n'''\n\nmodel_and_render = dict(\n    num_voxels=160**3,          # expected number of voxel\n    num_voxels_base=160**3,      # to rescale delta distance\n    voxel_dim=6,                 # feature voxel grid dim\n    defor_depth=3,               # depth of the deformation MLP \n    net_width=256,             # width of the  MLP\n    alpha_init=1e-3,              # set the alpha values everywhere at the begin of training\n    fast_color_thres=1e-4,           # threshold of alpha value to skip the fine stage sampled point\n    stepsize=0.5,                 # sampling stepsize in volume rendering\n    world_bound_scale=1.05,\n)\n\n\n\ndel deepcopy\n"
  },
  {
    "path": "configs/nerf-base/hellwarrior.py",
    "content": "_base_ = './default.py'\n\nexpname = 'base/dnerf_hellwarrior-400'\nbasedir = './logs/nerf_synthetic'\n\ndata = dict(\n    datadir='/data_dnerf/hellwarrior',\n    dataset_type='dnerf',\n    white_bkgd=True,\n)\n\n"
  },
  {
    "path": "configs/nerf-base/hook.py",
    "content": "_base_ = './default.py'\n\nexpname = 'base/dnerf_hook-400'\nbasedir = './logs/nerf_synthetic'\n\ndata = dict(\n    datadir='/data_dnerf/hook',\n    dataset_type='dnerf',\n    white_bkgd=True,\n)\n\n"
  },
  {
    "path": "configs/nerf-base/jumpingjacks.py",
    "content": "_base_ = './default.py'\n\nexpname = 'base/dnerf_jumpingjacks-400'\nbasedir = './logs/nerf_synthetic'\n\ndata = dict(\n    datadir='/data_dnerf/jumpingjacks',\n    dataset_type='dnerf',\n    white_bkgd=True,\n)\n\n"
  },
  {
    "path": "configs/nerf-base/lego.py",
    "content": "_base_ = './default.py'\n\nexpname = 'base/dnerf_lego-400'\nbasedir = './logs/nerf_synthetic'\n\ndata = dict(\n    datadir='/data_dnerf/lego',\n    dataset_type='dnerf',\n    white_bkgd=True,\n)\n\n"
  },
  {
    "path": "configs/nerf-base/mutant.py",
    "content": "_base_ = './default.py'\n\nexpname = 'base/dnerf_mutant-400'\nbasedir = './logs/nerf_synthetic'\n\ndata = dict(\n    datadir='/data_dnerf/mutant',\n    dataset_type='dnerf',\n    white_bkgd=True,\n)\n\n"
  },
  {
    "path": "configs/nerf-base/standup.py",
    "content": "_base_ = './default.py'\n\nexpname = 'base/dnerf_standup-400'\nbasedir = './logs/nerf_synthetic'\n\ndata = dict(\n    datadir='/data_dnerf/standup',\n    dataset_type='dnerf',\n    white_bkgd=True,\n)"
  },
  {
    "path": "configs/nerf-base/trex.py",
    "content": "_base_ = './default.py'\n\nexpname = 'base/dnerf_trex-400'\nbasedir = './logs/nerf_synthetic'\n\ndata = dict(\n    datadir='/data_dnerf/trex',\n    dataset_type='dnerf',\n    white_bkgd=True,\n)\n\n"
  },
  {
    "path": "configs/nerf-small/bouncingballs.py",
    "content": "_base_ = './default.py'\n\nexpname = 'small/dnerf_bouncingballs-400'\nbasedir = './logs/nerf_synthetic'\n\ndata = dict(\n    datadir='/data_dnerf/bouncingballs',\n    dataset_type='dnerf',\n    white_bkgd=True,\n)\n\n"
  },
  {
    "path": "configs/nerf-small/default.py",
    "content": "from copy import deepcopy\n\nexpname = None                    # experiment name\nbasedir = './logs/'               # where to store ckpts and logs\n\n''' Template of data options\n'''\ndata = dict(\n    datadir=None,                 # path to dataset root folder\n    dataset_type=None,            \n    load2gpu_on_the_fly=False,    # do not load all images into gpu (to save gpu memory)\n    testskip=1,                   # subsample testset to preview results\n    white_bkgd=False,             # use white background (note that some dataset don't provide alpha and with blended bg color)\n    half_res=True,              \n    factor=4,                     \n    ndc=False,                    # use ndc coordinate (only for forward-facing; not support yet)\n    spherify=False,               # inward-facing\n    llffhold=8,                   # testsplit\n    load_depths=False,            # load depth\n    use_bg_points=False,\n    add_cam=False,\n)\n\n''' Template of training options\n'''\ntrain_config = dict(\n    N_iters=20000,                # number of optimization steps\n    N_rand=4096,                  # batch size (number of random rays per optimization step)\n    lrate_feature=8e-2,           # lr of density voxel grid\n    lrate_featurenet=8e-4,\n    lrate_deformation_net=6e-4,\n    lrate_densitynet=8e-4,\n    lrate_timenet=8e-4,\n    lrate_rgbnet=8e-4,           # lr of the mlp to preduct view-dependent color\n    lrate_decay=20,               # lr decay by 0.1 after every lrate_decay*1000 steps\n    ray_sampler='in_maskcache',        # ray sampling strategies\n    weight_main=1.0,              # weight of photometric loss\n    weight_entropy_last=0.001,\n    weight_rgbper=0.01,            # weight of per-point rgb loss\n    tv_every=1,                   # count total variation loss every tv_every step\n    tv_after=0,                   # count total variation loss from tv_from step\n    tv_before=1e9,                   # count total variation before the given number of iterations\n    tv_feature_before=10000,            # count total variation densely before the given number of iterations\n    weight_tv_feature=0,\n    pg_scale=[2000, 4000, 6000],\n    skip_zero_grad_fields=['feature'],\n)\n\n''' Template of model and rendering options\n'''\n\nmodel_and_render = dict(\n    num_voxels=100**3,          # expected number of voxel\n    num_voxels_base=100**3,      # to rescale delta distance\n    voxel_dim=4,                 # feature voxel grid dim\n    defor_depth=3,               # depth of the colors MLP (there are rgbnet_depth-1 intermediate features)\n    net_width=64,             # width of the colors MLP\n    alpha_init=1e-2,              # set the alpha values everywhere at the begin of training\n    fast_color_thres=1e-4,           # threshold of alpha value to skip the fine stage sampled point\n    stepsize=0.5,                 # sampling stepsize in volume rendering\n    world_bound_scale=1.05,\n)\n\n\n\ndel deepcopy\n"
  },
  {
    "path": "configs/nerf-small/hellwarrior.py",
    "content": "_base_ = './default.py'\n\nexpname = 'small/dnerf_hellwarrior-400'\nbasedir = './logs/nerf_synthetic'\n\ndata = dict(\n    datadir='/data_dnerf/hellwarrior',\n    dataset_type='dnerf',\n    white_bkgd=True,\n)\n\n"
  },
  {
    "path": "configs/nerf-small/hook.py",
    "content": "_base_ = './default.py'\n\nexpname = 'small/dnerf_hook-400'\nbasedir = './logs/nerf_synthetic'\n\ndata = dict(\n    datadir='/data_dnerf/hook',\n    dataset_type='dnerf',\n    white_bkgd=True,\n)\n\n"
  },
  {
    "path": "configs/nerf-small/jumpingjacks.py",
    "content": "_base_ = './default.py'\n\nexpname = 'small/dnerf_jumpingjacks-400'\nbasedir = './logs/nerf_synthetic'\n\ndata = dict(\n    datadir='/data_dnerf/jumpingjacks',\n    dataset_type='dnerf',\n    white_bkgd=True,\n)\n\n"
  },
  {
    "path": "configs/nerf-small/lego.py",
    "content": "_base_ = './default.py'\n\nexpname = 'small/dnerf_lego-400'\nbasedir = './logs/nerf_synthetic'\n\ndata = dict(\n    datadir='/data_dnerf/lego',\n    dataset_type='dnerf',\n    white_bkgd=True,\n)\n\n"
  },
  {
    "path": "configs/nerf-small/mutant.py",
    "content": "_base_ = './default.py'\n\nexpname = 'small/dnerf_mutant-400'\nbasedir = './logs/nerf_synthetic'\n\ndata = dict(\n    datadir='/data_dnerf/mutant',\n    dataset_type='dnerf',\n    white_bkgd=True,\n)\n\n"
  },
  {
    "path": "configs/nerf-small/standup.py",
    "content": "_base_ = './default.py'\n\nexpname = 'small/dnerf_standup-400'\nbasedir = './logs/nerf_synthetic'\n\ndata = dict(\n    datadir='/data_dnerf/standup',\n    dataset_type='dnerf',\n    white_bkgd=True,\n)"
  },
  {
    "path": "configs/nerf-small/trex.py",
    "content": "_base_ = './default.py'\n\nexpname = 'small/dnerf_trex-400'\nbasedir = './logs/nerf_synthetic'\n\ndata = dict(\n    datadir='/data_dnerf/trex',\n    dataset_type='dnerf',\n    white_bkgd=True,\n)\n\n"
  },
  {
    "path": "configs/vrig_dataset/3dprinter.py",
    "content": "_base_ = './hyper_default.py'\n\nexpname = 'vrig/base-3dprinter'\nbasedir = './logs/vrig_data'\n\ndata = dict(\n    datadir='./vrig-3dprinter',\n    dataset_type='hyper_dataset',\n    white_bkgd=False,\n)"
  },
  {
    "path": "configs/vrig_dataset/broom.py",
    "content": "_base_ = './hyper_default.py'\n\nexpname = 'vrig/base-broom'\nbasedir = './logs/vrig_data'\n\ndata = dict(\n    datadir='./vrig_dataset/broom2',\n    dataset_type='hyper_dataset',\n    white_bkgd=False,\n)"
  },
  {
    "path": "configs/vrig_dataset/chicken.py",
    "content": "_base_ = './hyper_default.py'\n\nexpname = 'vrig/base-chicken'\nbasedir = './logs/vrig_data'\n\ndata = dict(\n    datadir='./vrig-chicken',\n    dataset_type='hyper_dataset',\n    white_bkgd=False,\n)"
  },
  {
    "path": "configs/vrig_dataset/hyper_default.py",
    "content": "from copy import deepcopy\n\nexpname = None                    # experiment name\nbasedir = './logs/'               # where to store ckpts and logs\n\n''' Template of data options\n'''\ndata = dict(\n    datadir=None,                 # path to dataset root folder\n    dataset_type=None,            \n    load2gpu_on_the_fly=True,    # do not load all images into gpu (to save gpu memory)\n    testskip=1,                   # subsample testset to preview results\n    white_bkgd=False,             # use white background (note that some dataset don't provide alpha and with blended bg color)\n    half_res=True,              \n    factor=4,                     \n    ndc=False,                    # use ndc coordinate (only for forward-facing; not support yet)\n    spherify=False,               # inward-facing\n    llffhold=8,                   # testsplit\n    load_depths=False,            # load depth\n    use_bg_points=True,\n    add_cam=True,\n\n)\n\n''' Template of training options\n'''\ntrain_config = dict(\n    N_iters=20000,                # number of optimization steps\n    N_rand=4096,                  # batch size (number of random rays per optimization step)\n    lrate_feature=1e-1,           # lr of voxel grid\n    lrate_featurenet=1e-3,\n    lrate_deformation_net=7e-4,\n    lrate_densitynet=1e-3,\n    lrate_timenet=1e-3,\n    lrate_camnet=1e-3,\n    lrate_rgbnet=1e-3,           # lr of the mlp \n    lrate_decay=20,               # lr decay by 0.1 after every lrate_decay*1000 steps\n    ray_sampler='in_maskcache',        # ray sampling strategies\n    weight_main=1.0,              # weight of photometric loss\n    weight_entropy_last=0.001,\n    weight_rgbper=0.01,            # weight of per-point rgb loss\n    tv_every=1,                   # count total variation loss every tv_every step\n    tv_after=0,                   # count total variation loss from tv_from step\n    tv_before=1e9,                   # count total variation before the given number of iterations\n    tv_feature_before=10000,            # count total variation densely before the given number of iterations\n    weight_tv_feature=1e-5,\n    pg_scale=[2000, 4000, 6000, 8000],\n    skip_zero_grad_fields=['feature'],\n)\n\n''' Template of model and rendering options\n'''\n\nmodel_and_render = dict(\n    num_voxels=160**3,          # expected number of voxel\n    num_voxels_base=160**3,      # to rescale delta distance\n    voxel_dim=6,                 # feature voxel grid dim\n    defor_depth=3,               # depth of the deformation MLP \n    net_width=256,             # width of the  MLP\n    alpha_init=1e-3,              # set the alpha values everywhere at the begin of training\n    fast_color_thres=1e-4,           # threshold of alpha value to skip the fine stage sampled point\n    stepsize=0.5,                 # sampling stepsize in volume rendering\n    world_bound_scale=1.05,\n)\n\n\n\ndel deepcopy\n"
  },
  {
    "path": "configs/vrig_dataset/peel-banana.py",
    "content": "_base_ = './hyper_default.py'\n\nexpname = 'vrig/base-peel-banana'\nbasedir = './logs/vrig_data'\n\ndata = dict(\n    datadir='./vrig-peel-banana',\n    dataset_type='hyper_dataset',\n    white_bkgd=False,\n)"
  },
  {
    "path": "metric.py",
    "content": "\nimport argparse\nimport math\nimport os\n\nimport imageio\nimport lpips\nimport numpy as np\nimport torch\nimport torch.nn as nn\nimport torch.nn.functional as F\n\n\n# Mean Square Error\nclass MSE(object):\n    def __call__(self, pred, gt):\n        return torch.mean((pred - gt) ** 2)\n\n# Peak Signal to Noise Ratio\nclass PSNR(object):\n    def __call__(self, pred, gt):\n        mse = torch.mean((pred - gt) ** 2)\n        return 10 * torch.log10(1 / mse)\n\n\n# structural similarity index\nclass SSIM(object):\n    '''\n    borrowed from https://github.com/huster-wgm/Pytorch-metrics/blob/master/metrics.py\n    '''\n    def gaussian(self, w_size, sigma):\n        gauss = torch.Tensor([math.exp(-(x - w_size//2)**2/float(2*sigma**2)) for x in range(w_size)])\n        return gauss/gauss.sum()\n\n    def create_window(self, w_size, channel=1):\n        _1D_window = self.gaussian(w_size, 1.5).unsqueeze(1)\n        _2D_window = _1D_window.mm(_1D_window.t()).float().unsqueeze(0).unsqueeze(0)\n        window = _2D_window.expand(channel, 1, w_size, w_size).contiguous()\n        return window\n\n    def __call__(self, y_pred, y_true, w_size=11, size_average=True, full=False):\n        \"\"\"\n        args:\n            y_true : 4-d ndarray in [batch_size, channels, img_rows, img_cols]\n            y_pred : 4-d ndarray in [batch_size, channels, img_rows, img_cols]\n            w_size : int, default 11\n            size_average : boolean, default True\n            full : boolean, default False\n        return ssim, larger the better\n        \"\"\"\n        # Value range can be different from 255. Other common ranges are 1 (sigmoid) and 2 (tanh).\n        if torch.max(y_pred) > 128:\n            max_val = 255\n        else:\n            max_val = 1\n\n        if torch.min(y_pred) < -0.5:\n            min_val = -1\n        else:\n            min_val = 0\n        L = max_val - min_val\n\n        padd = 0\n        (_, channel, height, width) = y_pred.size()\n        window = self.create_window(w_size, channel=channel).to(y_pred.device)\n\n        mu1 = F.conv2d(y_pred, window, padding=padd, groups=channel)\n        mu2 = F.conv2d(y_true, window, padding=padd, groups=channel)\n\n        mu1_sq = mu1.pow(2)\n        mu2_sq = mu2.pow(2)\n        mu1_mu2 = mu1 * mu2\n\n        sigma1_sq = F.conv2d(y_pred * y_pred, window, padding=padd, groups=channel) - mu1_sq\n        sigma2_sq = F.conv2d(y_true * y_true, window, padding=padd, groups=channel) - mu2_sq\n        sigma12 = F.conv2d(y_pred * y_true, window, padding=padd, groups=channel) - mu1_mu2\n\n        C1 = (0.01 * L) ** 2\n        C2 = (0.03 * L) ** 2\n\n        v1 = 2.0 * sigma12 + C2\n        v2 = sigma1_sq + sigma2_sq + C2\n        cs = torch.mean(v1 / v2)  # contrast sensitivity\n\n        ssim_map = ((2 * mu1_mu2 + C1) * v1) / ((mu1_sq + mu2_sq + C1) * v2)\n\n        if size_average:\n            ret = ssim_map.mean()\n        else:\n            ret = ssim_map.mean(1).mean(1).mean(1)\n\n        if full:\n            return ret, cs\n        return ret\n\n\n\n# Learned Perceptual Image Patch Similarity\nclass LPIPS(object):\n    '''\n    borrowed from https://github.com/huster-wgm/Pytorch-metrics/blob/master/metrics.py\n    '''\n    def __init__(self):\n        self.model = lpips.LPIPS(net='vgg').cuda()\n\n    def __call__(self, y_pred, y_true, normalized=True):\n        \"\"\"\n        args:\n            y_true : 4-d ndarray in [batch_size, channels, img_rows, img_cols]\n            y_pred : 4-d ndarray in [batch_size, channels, img_rows, img_cols]\n            normalized : change [0,1] => [-1,1] (default by LPIPS)\n        return LPIPS, smaller the better\n        \"\"\"\n        if normalized:\n            y_pred = y_pred * 2.0 - 1.0\n            y_true = y_true * 2.0 - 1.0\n        error =  self.model.forward(y_pred, y_true)\n        return torch.mean(error)\n\n\ndef read_images_in_dir(imgs_dir):\n    imgs = []\n    fnames = os.listdir(imgs_dir)\n    fnames.sort()\n    for fname in fnames:\n        if fname.endswith(\".mp4\") == True:  # ignore canonical space, only evalute real scene\n            continue\n        if fname.endswith(\".txt\") == True:  # ignore canonical space, only evalute real scene\n            continue\n\n        img_path = os.path.join(imgs_dir, fname)\n        # print(img_path)\n        img = imageio.imread(img_path)\n        img = (np.array(img) / 255.).astype(np.float32)\n        img = np.transpose(img, (2, 0, 1))\n        imgs.append(img)\n    \n    imgs = np.stack(imgs)       \n    return imgs\n\ndef estim_error(estim, gt):\n    errors = dict()\n    metric = PSNR()\n    errors[\"psnr\"] = metric(estim, gt).item()\n    metric = SSIM()\n    errors[\"ssim\"] = metric(estim, gt).item()\n    metric = LPIPS()\n    errors[\"lpips\"] = metric(estim, gt).item()\n    return errors\n\n\nparser = argparse.ArgumentParser()\nparser.add_argument('--estim_dir', type = str, default = None , help ='images path')\nparser.add_argument('--gt_dir', type = str, default = None ,help ='GT path')\nargs = parser.parse_args()\n\npsnr_cal = 0\nssim_cal = 0\nlpips_cal = 0\nscens = ['hellwarrior','mutant','hook','bouncingballs','lego','trex','standup','jumpingjacks']\nfor str in scens:\n    estim_dir = args.estim_dir + '/dnerf_'+str+'-400/render_test_fine_last'\n    gt_dir = args.gt_dir + '/'+str+'/renderonly_test_799999/gt'\n\n    estim = read_images_in_dir(estim_dir)\n    gt = read_images_in_dir(gt_dir)\n\n    estim = torch.Tensor(estim).cuda()\n    gt = torch.Tensor(gt).cuda()\n\n    errors = estim_error(estim, gt)\n    psnr_cal += errors[\"psnr\"]\n    ssim_cal += errors[\"ssim\"]\n    lpips_cal += errors[\"lpips\"]\n    print(str , errors)\nprint(psnr_cal/8 , ssim_cal/8 , lpips_cal/8)\n"
  },
  {
    "path": "requirements.txt",
    "content": "numpy\nscipy\ntqdm\nlpips\nmmcv\nimageio\nimageio-ffmpeg\nopencv-python\npytorch_msssim\ntorch\ntorch_scatter\nPillow"
  },
  {
    "path": "run.py",
    "content": "import argparse\nimport copy\nimport os\nimport random\nimport time\nfrom builtins import print\n\nimport imageio\nimport mmcv\nimport numpy as np\nimport torch\nimport torch.nn as nn\nimport torch.nn.functional as F\nfrom pytorch_msssim import ms_ssim\nfrom tqdm import tqdm, trange\n\nfrom lib import tineuvox, utils\nfrom lib.load_data import load_data\n\n\ndef config_parser():\n    '''Define command line arguments\n    '''\n    parser = argparse.ArgumentParser(formatter_class=argparse.ArgumentDefaultsHelpFormatter)\n    parser.add_argument('--config', required=True,\n                        help='config file path')\n    parser.add_argument(\"--seed\", type=int, default=0,\n                        help='Random seed')\n    parser.add_argument(\"--ft_path\", type=str, default='',\n                        help='specific weights npy file to reload for coarse network')\n    # testing options\n    parser.add_argument(\"--render_only\", action='store_true',\n                        help='do not optimize, reload weights and render out render_poses path')\n    parser.add_argument(\"--render_test\", action='store_true')\n    parser.add_argument(\"--render_train\", action='store_true')\n    parser.add_argument(\"--render_video\", action='store_true')\n    parser.add_argument(\"--render_video_factor\", type=int, default=0,\n                        help='downsampling factor to speed up rendering, set 4 or 8 for fast preview')\n    parser.add_argument(\"--eval_ssim\", action='store_true')\n    parser.add_argument(\"--eval_lpips_alex\", action='store_true')\n    parser.add_argument(\"--eval_lpips_vgg\", action='store_true')\n    parser.add_argument(\"--eval_psnr\", action='store_true')\n\n    # logging/saving options\n    parser.add_argument(\"--i_print\",   type=int, default=2000,\n                        help='frequency of console printout and metric loggin')\n    parser.add_argument(\"--fre_test\", type=int, default=30000,\n                        help='frequency of test')\n    parser.add_argument(\"--step_to_half\", type=int, default=19000,\n                        help='The iteration when fp32 becomes fp16')\n    return parser\n\n@torch.no_grad()\ndef render_viewpoints_hyper(model, data_class, ndc, render_kwargs, test=True, \n                                all=False, savedir=None, eval_psnr=False):\n    \n    rgbs = []\n    rgbs_gt =[]\n    rgbs_tensor =[]\n    rgbs_gt_tensor =[]\n    depths = []\n    psnrs = []\n    ms_ssims =[]\n\n    if test:\n        if all:\n            idx = data_class.i_test\n        else:\n            idx = data_class.i_test[::16]\n    else:\n        if all:\n            idx = data_class.i_train\n        else:\n            idx = data_class.i_train[::16]\n    for i in tqdm(idx):\n        rays_o, rays_d, viewdirs,rgb_gt = data_class.load_idx(i, not_dic=True)\n        keys = ['rgb_marched', 'depth']\n        time_one = data_class.all_time[i]*torch.ones_like(rays_o[:,0:1])\n        cam_one = data_class.all_cam[i]*torch.ones_like(rays_o[:,0:1])\n        bacth_size = 1000\n        render_result_chunks = [\n            {k: v for k, v in model(ro, rd, vd,ts, cams,**render_kwargs).items() if k in keys}\n            for ro, rd, vd ,ts,cams in zip(rays_o.split(bacth_size, 0), rays_d.split(bacth_size, 0),\n                                             viewdirs.split(bacth_size, 0),time_one.split(bacth_size, 0),cam_one.split(bacth_size, 0))\n        ]\n        render_result = {\n            k: torch.cat([ret[k] for ret in render_result_chunks]).reshape(data_class.h,data_class.w,-1)\n            for k in render_result_chunks[0].keys()\n        }\n        rgb_gt = rgb_gt.reshape(data_class.h,data_class.w,-1).cpu().numpy()\n        rgb = render_result['rgb_marched'].cpu().numpy()\n        depth = render_result['depth'].cpu().numpy()\n        rgbs.append(rgb)\n        depths.append(depth)\n        rgbs_gt.append(rgb_gt)\n        if eval_psnr:\n            p = -10. * np.log10(np.mean(np.square(rgb - rgb_gt)))\n            psnrs.append(p)\n            rgbs_tensor.append(torch.from_numpy(np.clip(rgb,0,1)).reshape(-1,data_class.h,data_class.w))\n            rgbs_gt_tensor.append(torch.from_numpy(np.clip(rgb_gt,0,1)).reshape(-1,data_class.h,data_class.w))\n        if i==0:\n            print('Testing', rgb.shape)\n    if eval_psnr:\n        rgbs_tensor = torch.stack(rgbs_tensor,0)\n        rgbs_gt_tensor = torch.stack(rgbs_gt_tensor,0)\n        ms_ssims = ms_ssim(rgbs_gt_tensor, rgbs_tensor, data_range=1, size_average=True )\n    if len(psnrs):\n        print('Testing psnr', np.mean(psnrs), '(avg)')\n        print('Testing ms_ssims', ms_ssims, '(avg)')\n\n    if savedir is not None:\n        print(f'Writing images to {savedir}')\n        for i in trange(len(rgbs)):\n            rgb8 = utils.to8b(rgbs[i])\n            filename = os.path.join(savedir, '{:03d}.png'.format(i))\n            imageio.imwrite(filename, rgb8)\n    rgbs = np.array(rgbs)\n    depths = np.array(depths)\n    return rgbs,depths\n\n\n@torch.no_grad()\ndef render_viewpoints(model, render_poses, HW, Ks, ndc, render_kwargs,\n                      gt_imgs=None, savedir=None, test_times=None, render_factor=0, eval_psnr=False,\n                      eval_ssim=False, eval_lpips_alex=False, eval_lpips_vgg=False,):\n    '''Render images for the given viewpoints; run evaluation if gt given.\n    '''\n    assert len(render_poses) == len(HW) and len(HW) == len(Ks)\n\n    if render_factor!=0:\n        HW = np.copy(HW)\n        Ks = np.copy(Ks)\n        HW //= render_factor\n        Ks[:, :2, :3] //= render_factor\n    rgbs = []\n    depths = []\n    psnrs = []\n    ssims = []\n    lpips_alex = []\n    lpips_vgg = []\n\n    for i, c2w in enumerate(tqdm(render_poses)):\n\n        H, W = HW[i]\n        K = Ks[i]\n        rays_o, rays_d, viewdirs = tineuvox.get_rays_of_a_view(\n                H, W, K, c2w, ndc)\n        keys = ['rgb_marched', 'depth']\n        rays_o = rays_o.flatten(0,-2)\n        rays_d = rays_d.flatten(0,-2)\n        viewdirs = viewdirs.flatten(0,-2)\n        time_one = test_times[i]*torch.ones_like(rays_o[:,0:1])\n        bacth_size=1000\n        render_result_chunks = [\n            {k: v for k, v in model(ro, rd, vd,ts, **render_kwargs).items() if k in keys}\n            for ro, rd, vd ,ts in zip(rays_o.split(bacth_size, 0), rays_d.split(bacth_size, 0), viewdirs.split(bacth_size, 0),time_one.split(bacth_size, 0))\n        ]\n        render_result = {\n            k: torch.cat([ret[k] for ret in render_result_chunks]).reshape(H,W,-1)\n            for k in render_result_chunks[0].keys()\n        }\n        rgb = render_result['rgb_marched'].cpu().numpy()\n        depth = render_result['depth'].cpu().numpy()\n\n        rgbs.append(rgb)\n        depths.append(depth)\n        if i==0:\n            print('Testing', rgb.shape)\n\n        if gt_imgs is not None and render_factor == 0:\n            if eval_psnr:\n                p = -10. * np.log10(np.mean(np.square(rgb - gt_imgs[i])))\n                psnrs.append(p)\n            if eval_ssim:\n                ssims.append(utils.rgb_ssim(rgb, gt_imgs[i], max_val=1))\n            if eval_lpips_alex:\n                lpips_alex.append(utils.rgb_lpips(rgb, gt_imgs[i], net_name = 'alex', device = c2w.device))\n            if eval_lpips_vgg:\n                lpips_vgg.append(utils.rgb_lpips(rgb, gt_imgs[i], net_name = 'vgg', device = c2w.device))\n\n    if len(psnrs):\n        if eval_psnr: print('Testing psnr', np.mean(psnrs), '(avg)')\n        if eval_ssim: print('Testing ssim', np.mean(ssims), '(avg)')\n        if eval_lpips_vgg: print('Testing lpips (vgg)', np.mean(lpips_vgg), '(avg)')\n        if eval_lpips_alex: print('Testing lpips (alex)', np.mean(lpips_alex), '(avg)')\n\n    if savedir is not None:\n        print(f'Writing images to {savedir}')\n        for i in trange(len(rgbs)):\n            rgb8 = utils.to8b(rgbs[i])\n            filename = os.path.join(savedir, '{:03d}.png'.format(i))\n            imageio.imwrite(filename, rgb8)\n\n    rgbs = np.array(rgbs)\n    depths = np.array(depths)\n    return rgbs, depths\n\n\ndef seed_everything():\n    '''Seed everything for better reproducibility.\n    (some pytorch operation is non-deterministic like the backprop of grid_samples)\n    '''\n    torch.manual_seed(args.seed)\n    np.random.seed(args.seed)\n    random.seed(args.seed)\n\n\ndef load_everything(args, cfg):\n    '''Load images / poses / camera settings / data split.\n    '''\n    data_dict = load_data(cfg.data)\n    if cfg.data.dataset_type == 'hyper_dataset':\n        kept_keys = {\n            'data_class',\n            'near', 'far',\n            'i_train', 'i_val', 'i_test',}\n        for k in list(data_dict.keys()):\n            if k not in kept_keys:\n                data_dict.pop(k)\n        return data_dict\n\n    # remove useless field\n    kept_keys = {\n            'hwf', 'HW', 'Ks', 'near', 'far',\n            'i_train', 'i_val', 'i_test', 'irregular_shape',\n            'poses', 'render_poses', 'images','times','render_times'}\n    for k in list(data_dict.keys()):\n        if k not in kept_keys:\n            data_dict.pop(k)\n\n    # construct data tensor\n    if data_dict['irregular_shape']:\n        data_dict['images'] = [torch.FloatTensor(im, device='cpu') for im in data_dict['images']]\n    else:\n        data_dict['images'] = torch.FloatTensor(data_dict['images'], device = 'cpu')\n    data_dict['poses'] = torch.Tensor(data_dict['poses'])\n    return data_dict\n\n\ndef compute_bbox_by_cam_frustrm(args, cfg, HW, Ks, poses, i_train, near, far, **kwargs):\n    print('compute_bbox_by_cam_frustrm: start')\n    xyz_min = torch.Tensor([np.inf, np.inf, np.inf])\n    xyz_max = -xyz_min\n    for (H, W), K, c2w in zip(HW[i_train], Ks[i_train], poses[i_train]):\n        rays_o, rays_d, viewdirs = tineuvox.get_rays_of_a_view(\n                H=H, W=W, K=K, c2w=c2w,ndc=cfg.data.ndc)\n        if cfg.data.ndc:\n            pts_nf = torch.stack([rays_o+rays_d*near, rays_o+rays_d*far])\n        else:\n            pts_nf = torch.stack([rays_o+viewdirs*near, rays_o+viewdirs*far])\n        xyz_min = torch.minimum(xyz_min, pts_nf.amin((0,1,2)))\n        xyz_max = torch.maximum(xyz_max, pts_nf.amax((0,1,2)))\n    print('compute_bbox_by_cam_frustrm: xyz_min', xyz_min)\n    print('compute_bbox_by_cam_frustrm: xyz_max', xyz_max)\n    print('compute_bbox_by_cam_frustrm: finish')\n    return xyz_min, xyz_max\n\n\ndef compute_bbox_by_cam_frustrm_hyper(args, cfg,data_class):\n    print('compute_bbox_by_cam_frustrm: start')\n    xyz_min = torch.Tensor([np.inf, np.inf, np.inf])\n    xyz_max = -xyz_min\n    for i in data_class.i_train:\n        rays_o, _, viewdirs,_ = data_class.load_idx(i,not_dic=True)\n        pts_nf = torch.stack([rays_o+viewdirs*data_class.near, rays_o+viewdirs*data_class.far])\n        xyz_min = torch.minimum(xyz_min, pts_nf.amin((0,1,2)))\n        xyz_max = torch.maximum(xyz_max, pts_nf.amax((0,1,2)))\n    print('compute_bbox_by_cam_frustrm: xyz_min', xyz_min)\n    print('compute_bbox_by_cam_frustrm: xyz_max', xyz_max)\n    print('compute_bbox_by_cam_frustrm: finish')\n    return xyz_min, xyz_max\n\n\ndef scene_rep_reconstruction(args, cfg, cfg_model, cfg_train, xyz_min, xyz_max, data_dict):\n\n    # init\n    device = torch.device('cuda' if torch.cuda.is_available() else 'cpu')\n    if abs(cfg_model.world_bound_scale - 1) > 1e-9:\n        xyz_shift = (xyz_max - xyz_min) * (cfg_model.world_bound_scale - 1) / 2\n        xyz_min -= xyz_shift\n        xyz_max += xyz_shift\n\n    if cfg.data.dataset_type !='hyper_dataset':\n        HW, Ks, near, far, i_train, i_val, i_test, poses, render_poses, images ,times,render_times= [\n            data_dict[k] for k in [\n                'HW', 'Ks', 'near', 'far', 'i_train', 'i_val', 'i_test', 'poses', \n                'render_poses', 'images',\n                'times','render_times'\n            ]\n        ]\n        times = torch.Tensor(times)\n        times_i_train = times[i_train].to('cpu' if cfg.data.load2gpu_on_the_fly else device)\n    else:\n        data_class = data_dict['data_class']\n        near = data_class.near\n        far = data_class.far\n        i_train = data_class.i_train\n        i_test = data_class.i_test\n\n    last_ckpt_path = os.path.join(cfg.basedir, cfg.expname, 'fine_last.tar')\n    # init model and optimizer\n    start = 0\n    # init model\n    model_kwargs = copy.deepcopy(cfg_model)\n\n    num_voxels = model_kwargs.pop('num_voxels')\n    if len(cfg_train.pg_scale) :\n        num_voxels = int(num_voxels / (2**len(cfg_train.pg_scale)))\n    model = tineuvox.TiNeuVox(\n        xyz_min=xyz_min, xyz_max=xyz_max,\n        num_voxels=num_voxels,\n        **model_kwargs)\n    model = model.to(device)\n    optimizer = utils.create_optimizer_or_freeze_model(model, cfg_train, global_step=0)\n\n    # init rendering setup\n    render_kwargs = {\n        'near': near,\n        'far': far,\n        'bg': 1 if cfg.data.white_bkgd else 0,\n        'stepsize': cfg_model.stepsize,\n    }\n    # init batch rays sampler\n    def gather_training_rays_hyper():\n        now_device = 'cpu'  if cfg.data.load2gpu_on_the_fly else device\n        N = len(data_class.i_train)*data_class.h*data_class.w\n        rgb_tr = torch.zeros([N,3], device=now_device)\n        rays_o_tr = torch.zeros_like(rgb_tr)\n        rays_d_tr = torch.zeros_like(rgb_tr)\n        viewdirs_tr = torch.zeros_like(rgb_tr)\n        times_tr = torch.ones([N,1], device=now_device)\n        cam_tr = torch.ones([N,1], device=now_device)\n        imsz = []\n        top = 0\n        for i in data_class.i_train:\n            rays_o, rays_d, viewdirs,rgb = data_class.load_idx(i,not_dic=True)\n            n = rgb.shape[0]\n            if data_class.add_cam:\n                cam_tr[top:top+n] = cam_tr[top:top+n]*data_class.all_cam[i]\n            times_tr[top:top+n] = times_tr[top:top+n]*data_class.all_time[i]\n            rgb_tr[top:top+n].copy_(rgb)\n            rays_o_tr[top:top+n].copy_(rays_o.to(now_device))\n            rays_d_tr[top:top+n].copy_(rays_d.to(now_device))\n            viewdirs_tr[top:top+n].copy_(viewdirs.to(now_device))\n            imsz.append(n)\n            top += n\n        assert top == N\n        index_generator = tineuvox.batch_indices_generator(len(rgb_tr), cfg_train.N_rand)\n        batch_index_sampler = lambda: next(index_generator)\n        return rgb_tr, times_tr,cam_tr,rays_o_tr, rays_d_tr, viewdirs_tr, imsz, batch_index_sampler\n\n\n    def gather_training_rays():\n        if data_dict['irregular_shape']:\n            rgb_tr_ori = [images[i].to('cpu' if cfg.data.load2gpu_on_the_fly else device) for i in i_train]\n        else:\n            rgb_tr_ori = images[i_train].to('cpu' if cfg.data.load2gpu_on_the_fly else device)\n\n        if cfg_train.ray_sampler == 'in_maskcache':\n            print('cfg_train.ray_sampler =in_maskcache')\n            rgb_tr, times_flaten,rays_o_tr, rays_d_tr, viewdirs_tr, imsz = tineuvox.get_training_rays_in_maskcache_sampling(\n                    rgb_tr_ori=rgb_tr_ori,times=times_i_train,\n                    train_poses=poses[i_train],\n                    HW=HW[i_train], Ks=Ks[i_train],\n                    ndc=cfg.data.ndc, \n                    model=model, render_kwargs=render_kwargs)\n        elif cfg_train.ray_sampler == 'flatten':\n            print('cfg_train.ray_sampler =flatten')\n            rgb_tr, times_flaten,rays_o_tr, rays_d_tr, viewdirs_tr, imsz = tineuvox.get_training_rays_flatten(\n                rgb_tr_ori=rgb_tr_ori,times=times_i_train,\n                train_poses=poses[i_train],\n                HW=HW[i_train], Ks=Ks[i_train], ndc=cfg.data.ndc,)\n        else:\n            print('cfg_train.ray_sampler =random')\n            rgb_tr, times_flaten,rays_o_tr, rays_d_tr, viewdirs_tr, imsz = tineuvox.get_training_rays(\n                rgb_tr=rgb_tr_ori,times=times_i_train,\n                train_poses=poses[i_train],\n                HW=HW[i_train], Ks=Ks[i_train], ndc=cfg.data.ndc,)\n        index_generator = tineuvox.batch_indices_generator(len(rgb_tr), cfg_train.N_rand)\n        batch_index_sampler = lambda: next(index_generator)\n        return rgb_tr,times_flaten, rays_o_tr, rays_d_tr, viewdirs_tr, imsz, batch_index_sampler\n    if cfg.data.dataset_type !='hyper_dataset':\n        rgb_tr,times_flaten, rays_o_tr, rays_d_tr, viewdirs_tr, imsz, batch_index_sampler = gather_training_rays()\n    else:\n        rgb_tr,times_flaten,cam_tr, rays_o_tr, rays_d_tr, viewdirs_tr, imsz, batch_index_sampler = gather_training_rays_hyper()\n\n    torch.cuda.empty_cache()\n    psnr_lst = []\n    time0 = time.time()\n    global_step = -1\n\n    for global_step in trange(1+start, 1+cfg_train.N_iters):\n\n        if global_step == args.step_to_half:\n                model.feature.data=model.feature.data.half()\n        # progress scaling checkpoint\n        if global_step in cfg_train.pg_scale:\n            n_rest_scales = len(cfg_train.pg_scale)-cfg_train.pg_scale.index(global_step)-1\n            cur_voxels = int(cfg_model.num_voxels / (2**n_rest_scales))\n            if isinstance(model, tineuvox.TiNeuVox):\n                model.scale_volume_grid(cur_voxels)\n            else:\n                raise NotImplementedError\n            optimizer = utils.create_optimizer_or_freeze_model(model, cfg_train, global_step=0)\n\n        # random sample rays\n        if cfg_train.ray_sampler in ['flatten', 'in_maskcache'] or cfg.data.dataset_type =='hyper_dataset':\n            sel_i = batch_index_sampler()\n            target = rgb_tr[sel_i]\n            rays_o = rays_o_tr[sel_i]\n            rays_d = rays_d_tr[sel_i]\n            viewdirs = viewdirs_tr[sel_i]\n            times_sel = times_flaten[sel_i]\n            if cfg.data.dataset_type == 'hyper_dataset':\n                if data_class.add_cam == True:\n                    cam_sel = cam_tr[sel_i]\n                    cam_sel = cam_sel.to(device)\n                    render_kwargs.update({'cam_sel':cam_sel})\n                if data_class.use_bg_points == True:\n                    sel_idx = torch.randint(data_class.bg_points.shape[0], [cfg_train.N_rand//3])\n                    bg_points_sel = data_class.bg_points[sel_idx]\n                    bg_points_sel = bg_points_sel.to(device)\n                    render_kwargs.update({'bg_points_sel':bg_points_sel})\n        elif cfg_train.ray_sampler == 'random':\n            sel_b = torch.randint(rgb_tr.shape[0], [cfg_train.N_rand])\n            sel_r = torch.randint(rgb_tr.shape[1], [cfg_train.N_rand])\n            sel_c = torch.randint(rgb_tr.shape[2], [cfg_train.N_rand])\n            target = rgb_tr[sel_b, sel_r, sel_c]\n            rays_o = rays_o_tr[sel_b, sel_r, sel_c]\n            rays_d = rays_d_tr[sel_b, sel_r, sel_c]\n            viewdirs = viewdirs_tr[sel_b, sel_r, sel_c]\n            times_sel = times_flaten[sel_b, sel_r, sel_c]\n        else:\n            raise NotImplementedError\n\n        if cfg.data.load2gpu_on_the_fly:\n            target = target.to(device)\n            rays_o = rays_o.to(device)\n            rays_d = rays_d.to(device)\n            viewdirs = viewdirs.to(device)\n            times_sel = times_sel.to(device)\n\n        # volume rendering\n        render_result = model(rays_o, rays_d, viewdirs, times_sel, global_step=global_step, **render_kwargs)\n\n        # gradient descent step\n        optimizer.zero_grad(set_to_none = True)\n        loss = cfg_train.weight_main * F.mse_loss(render_result['rgb_marched'], target)\n        psnr = utils.mse2psnr(loss.detach())\n        \n        if cfg.data.dataset_type =='hyper_dataset':\n            if data_class.use_bg_points == True:\n                loss = loss+F.mse_loss(render_result['bg_points_delta'],bg_points_sel)\n        if cfg_train.weight_entropy_last > 0:\n            pout = render_result['alphainv_last'].clamp(1e-6, 1-1e-6)\n            entropy_last_loss = -(pout*torch.log(pout) + (1-pout)*torch.log(1-pout)).mean()\n            loss += cfg_train.weight_entropy_last * entropy_last_loss\n        if cfg_train.weight_rgbper > 0:\n            rgbper = (render_result['raw_rgb'] - target[render_result['ray_id']]).pow(2).sum(-1)\n            rgbper_loss = (rgbper * render_result['weights'].detach()).sum() / len(rays_o)\n            loss += cfg_train.weight_rgbper * rgbper_loss\n        loss.backward()\n\n        if global_step<cfg_train.tv_before and global_step>cfg_train.tv_after and global_step%cfg_train.tv_every==0:\n            if cfg_train.weight_tv_feature>0:\n                model.feature_total_variation_add_grad(\n                    cfg_train.weight_tv_feature/len(rays_o), global_step<cfg_train.tv_feature_before)\n        optimizer.step()\n        psnr_lst.append(psnr.item())\n        # update lr\n        decay_steps = cfg_train.lrate_decay * 1000\n        decay_factor = 0.1 ** (1/decay_steps)\n        for i_opt_g, param_group in enumerate(optimizer.param_groups):\n            param_group['lr'] = param_group['lr'] * decay_factor\n\n        # check log & save\n        if global_step%args.i_print == 0:\n            eps_time = time.time() - time0\n            eps_time_str = f'{eps_time//3600:02.0f}:{eps_time//60%60:02.0f}:{eps_time%60:02.0f}'\n            tqdm.write(f'scene_rep_reconstruction : iter {global_step:6d} / '\n                       f'Loss: {loss.item():.9f} / PSNR: {np.mean(psnr_lst):5.2f} / '\n                       f'Eps: {eps_time_str}')\n            psnr_lst = []\n\n        if global_step%(args.fre_test) == 0:\n            render_viewpoints_kwargs = {\n                'model': model,\n                'ndc': cfg.data.ndc,\n                'render_kwargs': {\n                    'near': near,\n                    'far': far,\n                    'bg': 1 if cfg.data.white_bkgd else 0,\n                    'stepsize': cfg_model.stepsize,\n\n                    },\n                }\n            testsavedir = os.path.join(cfg.basedir, cfg.expname, f'{global_step}-test')\n            if os.path.exists(testsavedir) == False:\n                os.makedirs(testsavedir)\n            if cfg.data.dataset_type != 'hyper_dataset': \n                rgbs,disps = render_viewpoints(\n                    render_poses=data_dict['poses'][data_dict['i_test']],\n                    HW=data_dict['HW'][data_dict['i_test']],\n                    Ks=data_dict['Ks'][data_dict['i_test']],\n                    gt_imgs=[data_dict['images'][i].cpu().numpy() for i in data_dict['i_test']],\n                    savedir=testsavedir,\n                    test_times=data_dict['times'][data_dict['i_test']],\n                    eval_psnr=args.eval_psnr, eval_ssim=args.eval_ssim, eval_lpips_alex=args.eval_lpips_alex, eval_lpips_vgg=args.eval_lpips_vgg,\n                    **render_viewpoints_kwargs)\n            else:\n                rgbs,disps = render_viewpoints_hyper(\n                    data_class=data_class,\n                    savedir=testsavedir, all=False, test=True, eval_psnr=args.eval_psnr,\n                    **render_viewpoints_kwargs)\n\n    if global_step != -1:\n        torch.save({\n            'global_step': global_step,\n            'model_kwargs': model.get_kwargs(),\n            'model_state_dict': model.state_dict(),\n        }, last_ckpt_path)\n        print('scene_rep_reconstruction : saved checkpoints at', last_ckpt_path)\n\n\ndef train(args, cfg, data_dict=None):\n\n    # init\n    print('train: start')\n    os.makedirs(os.path.join(cfg.basedir, cfg.expname), exist_ok=True)\n    with open(os.path.join(cfg.basedir, cfg.expname, 'args.txt'), 'w') as file:\n        for arg in sorted(vars(args)):\n            attr = getattr(args, arg)\n            file.write('{} = {}\\n'.format(arg, attr))\n    cfg.dump(os.path.join(cfg.basedir, cfg.expname, 'config.py'))\n\n    # coarse geometry searching\n    if cfg.data.dataset_type == 'hyper_dataset':\n        xyz_min, xyz_max = compute_bbox_by_cam_frustrm_hyper(args = args, cfg = cfg,data_class = data_dict['data_class'])\n    else:\n        xyz_min, xyz_max = compute_bbox_by_cam_frustrm(args = args, cfg = cfg, **data_dict)\n    coarse_ckpt_path = None\n\n    # fine detail reconstruction\n    eps_time = time.time()\n    scene_rep_reconstruction(\n            args=args, cfg=cfg,\n            cfg_model=cfg.model_and_render, cfg_train=cfg.train_config,\n            xyz_min=xyz_min, xyz_max=xyz_max,\n            data_dict=data_dict)\n    eps_loop = time.time() - eps_time\n    eps_time_str = f'{eps_loop//3600:02.0f}:{eps_loop//60%60:02.0f}:{eps_loop%60:02.0f}'\n    print('train: finish (eps time', eps_time_str, ')')\n\nif __name__=='__main__':\n\n    # load setup\n    parser = config_parser()\n    args = parser.parse_args()\n    cfg = mmcv.Config.fromfile(args.config)\n    # init enviroment\n    if torch.cuda.is_available():\n        torch.set_default_tensor_type('torch.cuda.FloatTensor')\n        device = torch.device('cuda')\n    else:\n        device = torch.device('cpu')\n    seed_everything()\n    data_dict = None\n    # load images / poses / camera settings / data split\n    data_dict = load_everything(args = args, cfg = cfg)\n\n    # train\n    if not args.render_only :\n        train(args, cfg, data_dict = data_dict)\n\n    # load model for rendring\n    if args.render_test or args.render_train or args.render_video:\n        if args.ft_path:\n            ckpt_path = args.ft_path\n        else:\n            ckpt_path = os.path.join(cfg.basedir, cfg.expname, 'fine_last.tar')\n        ckpt_name = ckpt_path.split('/')[-1][:-4]\n        model_class = tineuvox.TiNeuVox\n        model = utils.load_model(model_class, ckpt_path).to(device)\n        near=data_dict['near']\n        far=data_dict['far']\n        stepsize = cfg.model_and_render.stepsize\n        render_viewpoints_kwargs = {\n            'model': model,\n            'ndc': cfg.data.ndc,\n            'render_kwargs': {\n                'near': near,\n                'far': far,\n                'bg': 1 if cfg.data.white_bkgd else 0,\n                'stepsize': stepsize,\n                'render_depth': True,\n            },\n        }\n    # render trainset and eval\n    if args.render_train:\n        testsavedir = os.path.join(cfg.basedir, cfg.expname, f'render_train_{ckpt_name}')\n        os.makedirs(testsavedir, exist_ok = True)\n        if cfg.data.dataset_type  != 'hyper_dataset':\n            rgbs, disps = render_viewpoints(\n                    render_poses=data_dict['poses'][data_dict['i_train']],\n                    HW=data_dict['HW'][data_dict['i_train']],\n                    Ks=data_dict['Ks'][data_dict['i_train']],\n                    gt_imgs=[data_dict['images'][i].cpu().numpy() for i in data_dict['i_train']],\n                    savedir=testsavedir,\n                    test_times=data_dict['times'][data_dict['i_train']],\n                    eval_psnr=args.eval_psnr, eval_ssim=args.eval_ssim, eval_lpips_alex=args.eval_lpips_alex, eval_lpips_vgg=args.eval_lpips_vgg,\n                    **render_viewpoints_kwargs)\n        elif cfg.data.dataset_type == 'hyper_dataset':   \n            rgbs,disps = render_viewpoints_hyper(\n                    data_calss=data_dict['data_calss'],\n                    savedir=testsavedir, all=True, test=False,\n                    eval_psnr=args.eval_psnr,\n                    **render_viewpoints_kwargs)\n        else:\n            raise NotImplementedError\n\n        imageio.mimwrite(os.path.join(testsavedir, 'train_video.rgb.mp4'), utils.to8b(rgbs), fps = 30, quality = 8)\n        imageio.mimwrite(os.path.join(testsavedir, 'train_video.disp.mp4'), utils.to8b(disps / np.max(disps)), fps = 30, quality = 8)\n\n    # render testset and eval\n    if args.render_test:\n        testsavedir = os.path.join(cfg.basedir, cfg.expname, f'render_test_{ckpt_name}')\n        os.makedirs(testsavedir, exist_ok=True)\n        if cfg.data.dataset_type  != 'hyper_dataset':\n            rgbs, disps = render_viewpoints(\n                    render_poses=data_dict['poses'][data_dict['i_test']],\n                    HW=data_dict['HW'][data_dict['i_test']],\n                    Ks=data_dict['Ks'][data_dict['i_test']],\n                    gt_imgs=[data_dict['images'][i].cpu().numpy() for i in data_dict['i_test']],\n                    savedir=testsavedir,\n                    test_times=data_dict['times'][data_dict['i_test']],\n                    eval_psnr=args.eval_psnr,eval_ssim = args.eval_ssim, eval_lpips_alex=args.eval_lpips_alex, eval_lpips_vgg=args.eval_lpips_vgg,\n                    **render_viewpoints_kwargs)\n        elif cfg.data.dataset_type == 'hyper_dataset':   \n            rgbs,disps = render_viewpoints_hyper(\n                    data_class=data_dict['data_class'],\n                    savedir=testsavedir,all=True,test=True,\n                    eval_psnr=args.eval_psnr,\n                    **render_viewpoints_kwargs)\n        else:\n            raise NotImplementedError\n\n        imageio.mimwrite(os.path.join(testsavedir, 'test_video.rgb.mp4'), utils.to8b(rgbs), fps=30, quality=8)\n        imageio.mimwrite(os.path.join(testsavedir, 'test_video.disp.mp4'), utils.to8b(disps / np.max(disps)), fps=30, quality=8)\n\n    # render video\n    if args.render_video:\n        if cfg.data.dataset_type  != 'hyper_dataset':\n            testsavedir = os.path.join(cfg.basedir, cfg.expname, f'render_video_{ckpt_name}_time')\n            os.makedirs(testsavedir, exist_ok=True)\n            rgbs, disps = render_viewpoints(\n                    render_poses=data_dict['render_poses'],\n                    HW=data_dict['HW'][data_dict['i_test']][[0]].repeat(len(data_dict['render_poses']), 0),\n                    Ks=data_dict['Ks'][data_dict['i_test']][[0]].repeat(len(data_dict['render_poses']), 0),\n                    render_factor=args.render_video_factor,\n                    savedir=testsavedir,\n                    test_times=data_dict['render_times'],\n                    **render_viewpoints_kwargs)\n            imageio.mimwrite(os.path.join(testsavedir, 'video.rgb.mp4'), utils.to8b(rgbs), fps=30, quality=8)\n            imageio.mimwrite(os.path.join(testsavedir, 'video.disp.mp4'), utils.to8b(disps / np.max(disps)), fps=30, quality =8)\n        else:\n            raise NotImplementedError\n\n    print('Done')\n\n"
  }
]