[
  {
    "path": ".github/workflows/publish-pip.yml",
    "content": "name: PyPI Publish\n\non: push\n\njobs:\n  build-n-publish:\n    runs-on: ubuntu-latest\n    if: startsWith(github.event.ref, 'refs/tags')\n\n    steps:\n      - uses: actions/checkout@v2\n      - name: Set up Python 3.8\n        uses: actions/setup-python@v1\n        with:\n          python-version: 3.8\n      - name: Upgrade pip\n        run: pip install pip --upgrade\n      - name: Install PyTorch (cpu)\n        run: pip install torch==1.7.0+cpu torchvision==0.8.1+cpu -f https://download.pytorch.org/whl/torch_stable.html\n      - name: Install dependencies\n        run: |\n          pip install basicsr\n          pip install facexlib\n          pip install gfpgan\n          pip install -r requirements.txt\n      - name: Build and install\n        run: rm -rf .eggs && pip install -e .\n      - name: Build for distribution\n        run: python setup.py sdist bdist_wheel\n      - name: Publish distribution to PyPI\n        uses: pypa/gh-action-pypi-publish@master\n        with:\n          password: ${{ secrets.PYPI_API_TOKEN }}\n"
  },
  {
    "path": ".github/workflows/pylint.yml",
    "content": "name: PyLint\n\non: [push, pull_request]\n\njobs:\n  build:\n\n    runs-on: ubuntu-latest\n    strategy:\n      matrix:\n        python-version: [3.8]\n\n    steps:\n    - uses: actions/checkout@v2\n    - name: Set up Python ${{ matrix.python-version }}\n      uses: actions/setup-python@v2\n      with:\n        python-version: ${{ matrix.python-version }}\n\n    - name: Install dependencies\n      run: |\n        python -m pip install --upgrade pip\n        pip install codespell flake8 isort yapf\n\n    # modify the folders accordingly\n    - name: Lint\n      run: |\n        codespell\n        flake8 .\n        isort --check-only --diff realesrgan/ scripts/ inference_realesrgan.py setup.py\n        yapf -r -d realesrgan/ scripts/ inference_realesrgan.py setup.py\n"
  },
  {
    "path": ".github/workflows/release.yml",
    "content": "name: release\non:\n  push:\n    tags:\n      - '*'\n\njobs:\n  build:\n    permissions: write-all\n    name: Create Release\n    runs-on: ubuntu-latest\n    steps:\n      - name: Checkout code\n        uses: actions/checkout@v2\n      - name: Create Release\n        id: create_release\n        uses: actions/create-release@v1\n        env:\n          GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }}\n        with:\n          tag_name: ${{ github.ref }}\n          release_name: Real-ESRGAN ${{ github.ref }} Release Note\n          body: |\n            🚀 See you again 😸\n            🚀Have a nice day 😸 and happy everyday 😃\n            🚀 Long time no see ☄️\n\n            ✨ **Highlights**\n            ✅ [Features] Support ...\n\n            🐛 **Bug Fixes**\n\n            🌴 **Improvements**\n\n            📢📢📢\n\n            <p align=\"center\">\n               <img src=\"https://raw.githubusercontent.com/xinntao/Real-ESRGAN/master/assets/realesrgan_logo.png\" height=150>\n            </p>\n          draft: true\n          prerelease: false\n"
  },
  {
    "path": ".gitignore",
    "content": "# ignored folders\ndatasets/*\nexperiments/*\nresults/*\ntb_logger/*\nwandb/*\ntmp/*\nweights/*\n\nversion.py\n\n# 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": ".pre-commit-config.yaml",
    "content": "repos:\n  # flake8\n  - repo: https://github.com/PyCQA/flake8\n    rev: 3.8.3\n    hooks:\n      - id: flake8\n        args: [\"--config=setup.cfg\", \"--ignore=W504, W503\"]\n\n  # modify known_third_party\n  - repo: https://github.com/asottile/seed-isort-config\n    rev: v2.2.0\n    hooks:\n      - id: seed-isort-config\n\n  # isort\n  - repo: https://github.com/timothycrosley/isort\n    rev: 5.2.2\n    hooks:\n      - id: isort\n\n  # yapf\n  - repo: https://github.com/pre-commit/mirrors-yapf\n    rev: v0.30.0\n    hooks:\n      - id: yapf\n\n  # codespell\n  - repo: https://github.com/codespell-project/codespell\n    rev: v2.1.0\n    hooks:\n      - id: codespell\n\n  # pre-commit-hooks\n  - repo: https://github.com/pre-commit/pre-commit-hooks\n    rev: v3.2.0\n    hooks:\n      - id: trailing-whitespace  # Trim trailing whitespace\n      - id: check-yaml  # Attempt to load all yaml files to verify syntax\n      - id: check-merge-conflict  # Check for files that contain merge conflict strings\n      - id: double-quote-string-fixer  # Replace double quoted strings with single quoted strings\n      - id: end-of-file-fixer  # Make sure files end in a newline and only a newline\n      - id: requirements-txt-fixer  # Sort entries in requirements.txt and remove incorrect entry for pkg-resources==0.0.0\n      - id: fix-encoding-pragma  # Remove the coding pragma: # -*- coding: utf-8 -*-\n        args: [\"--remove\"]\n      - id: mixed-line-ending  # Replace or check mixed line ending\n        args: [\"--fix=lf\"]\n"
  },
  {
    "path": ".vscode/settings.json",
    "content": "{\n    \"files.trimTrailingWhitespace\": true,\n    \"editor.wordWrap\": \"on\",\n    \"editor.rulers\": [\n        80,\n        120\n    ],\n    \"editor.renderWhitespace\": \"all\",\n    \"editor.renderControlCharacters\": true,\n    \"python.formatting.provider\": \"yapf\",\n    \"python.formatting.yapfArgs\": [\n        \"--style\",\n        \"{BASED_ON_STYLE = pep8, BLANK_LINE_BEFORE_NESTED_CLASS_OR_DEF = true, SPLIT_BEFORE_EXPRESSION_AFTER_OPENING_PAREN = true, COLUMN_LIMIT = 120}\"\n    ],\n    \"python.linting.flake8Enabled\": true,\n    \"python.linting.flake8Args\": [\n        \"max-line-length=120\"\n    ],\n}\n"
  },
  {
    "path": "CODE_OF_CONDUCT.md",
    "content": "# Contributor Covenant Code of Conduct\n\n## Our Pledge\n\nWe as members, contributors, and leaders pledge to make participation in our\ncommunity a harassment-free experience for everyone, regardless of age, body\nsize, visible or invisible disability, ethnicity, sex characteristics, gender\nidentity and expression, level of experience, education, socio-economic status,\nnationality, personal appearance, race, religion, or sexual identity\nand orientation.\n\nWe pledge to act and interact in ways that contribute to an open, welcoming,\ndiverse, inclusive, and healthy community.\n\n## Our Standards\n\nExamples of behavior that contributes to a positive environment for our\ncommunity include:\n\n* Demonstrating empathy and kindness toward other people\n* Being respectful of differing opinions, viewpoints, and experiences\n* Giving and gracefully accepting constructive feedback\n* Accepting responsibility and apologizing to those affected by our mistakes,\n  and learning from the experience\n* Focusing on what is best not just for us as individuals, but for the\n  overall community\n\nExamples of unacceptable behavior include:\n\n* The use of sexualized language or imagery, and sexual attention or\n  advances of any kind\n* Trolling, insulting or derogatory comments, and personal or political attacks\n* Public or private harassment\n* Publishing others' private information, such as a physical or email\n  address, without their explicit permission\n* Other conduct which could reasonably be considered inappropriate in a\n  professional setting\n\n## Enforcement Responsibilities\n\nCommunity leaders are responsible for clarifying and enforcing our standards of\nacceptable behavior and will take appropriate and fair corrective action in\nresponse to any behavior that they deem inappropriate, threatening, offensive,\nor harmful.\n\nCommunity leaders have the right and responsibility to remove, edit, or reject\ncomments, commits, code, wiki edits, issues, and other contributions that are\nnot aligned to this Code of Conduct, and will communicate reasons for moderation\ndecisions when appropriate.\n\n## Scope\n\nThis Code of Conduct applies within all community spaces, and also applies when\nan individual is officially representing the community in public spaces.\nExamples of representing our community include using an official e-mail address,\nposting via an official social media account, or acting as an appointed\nrepresentative at an online or offline event.\n\n## Enforcement\n\nInstances of abusive, harassing, or otherwise unacceptable behavior may be\nreported to the community leaders responsible for enforcement at\nxintao.wang@outlook.com or xintaowang@tencent.com.\nAll complaints will be reviewed and investigated promptly and fairly.\n\nAll community leaders are obligated to respect the privacy and security of the\nreporter of any incident.\n\n## Enforcement Guidelines\n\nCommunity leaders will follow these Community Impact Guidelines in determining\nthe consequences for any action they deem in violation of this Code of Conduct:\n\n### 1. Correction\n\n**Community Impact**: Use of inappropriate language or other behavior deemed\nunprofessional or unwelcome in the community.\n\n**Consequence**: A private, written warning from community leaders, providing\nclarity around the nature of the violation and an explanation of why the\nbehavior was inappropriate. A public apology may be requested.\n\n### 2. Warning\n\n**Community Impact**: A violation through a single incident or series\nof actions.\n\n**Consequence**: A warning with consequences for continued behavior. No\ninteraction with the people involved, including unsolicited interaction with\nthose enforcing the Code of Conduct, for a specified period of time. This\nincludes avoiding interactions in community spaces as well as external channels\nlike social media. Violating these terms may lead to a temporary or\npermanent ban.\n\n### 3. Temporary Ban\n\n**Community Impact**: A serious violation of community standards, including\nsustained inappropriate behavior.\n\n**Consequence**: A temporary ban from any sort of interaction or public\ncommunication with the community for a specified period of time. No public or\nprivate interaction with the people involved, including unsolicited interaction\nwith those enforcing the Code of Conduct, is allowed during this period.\nViolating these terms may lead to a permanent ban.\n\n### 4. Permanent Ban\n\n**Community Impact**: Demonstrating a pattern of violation of community\nstandards, including sustained inappropriate behavior,  harassment of an\nindividual, or aggression toward or disparagement of classes of individuals.\n\n**Consequence**: A permanent ban from any sort of public interaction within\nthe community.\n\n## Attribution\n\nThis Code of Conduct is adapted from the [Contributor Covenant][homepage],\nversion 2.0, available at\nhttps://www.contributor-covenant.org/version/2/0/code_of_conduct.html.\n\nCommunity Impact Guidelines were inspired by [Mozilla's code of conduct\nenforcement ladder](https://github.com/mozilla/diversity).\n\n[homepage]: https://www.contributor-covenant.org\n\nFor answers to common questions about this code of conduct, see the FAQ at\nhttps://www.contributor-covenant.org/faq. Translations are available at\nhttps://www.contributor-covenant.org/translations.\n"
  },
  {
    "path": "LICENSE",
    "content": "BSD 3-Clause License\n\nCopyright (c) 2021, Xintao Wang\nAll rights reserved.\n\nRedistribution and use in source and binary forms, with or without\nmodification, are permitted provided that the following conditions are met:\n\n1. Redistributions of source code must retain the above copyright notice, this\n   list of conditions and the following disclaimer.\n\n2. Redistributions in binary form must reproduce the above copyright notice,\n   this list of conditions and the following disclaimer in the documentation\n   and/or other materials provided with the distribution.\n\n3. Neither the name of the copyright holder nor the names of its\n   contributors may be used to endorse or promote products derived from\n   this software without specific prior written permission.\n\nTHIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS \"AS IS\"\nAND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE\nIMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE\nDISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE\nFOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL\nDAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR\nSERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER\nCAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,\nOR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE\nOF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.\n"
  },
  {
    "path": "MANIFEST.in",
    "content": "include assets/*\ninclude inputs/*\ninclude scripts/*.py\ninclude inference_realesrgan.py\ninclude VERSION\ninclude LICENSE\ninclude requirements.txt\ninclude weights/README.md\n"
  },
  {
    "path": "README.md",
    "content": "<p align=\"center\">\n  <img src=\"assets/realesrgan_logo.png\" height=120>\n</p>\n\n## <div align=\"center\"><b><a href=\"README.md\">English</a> | <a href=\"README_CN.md\">简体中文</a></b></div>\n\n<div align=\"center\">\n\n👀[**Demos**](#-demos-videos) **|** 🚩[**Updates**](#-updates) **|** ⚡[**Usage**](#-quick-inference) **|** 🏰[**Model Zoo**](docs/model_zoo.md) **|** 🔧[Install](#-dependencies-and-installation)  **|** 💻[Train](docs/Training.md) **|** ❓[FAQ](docs/FAQ.md) **|** 🎨[Contribution](docs/CONTRIBUTING.md)\n\n[![download](https://img.shields.io/github/downloads/xinntao/Real-ESRGAN/total.svg)](https://github.com/xinntao/Real-ESRGAN/releases)\n[![PyPI](https://img.shields.io/pypi/v/realesrgan)](https://pypi.org/project/realesrgan/)\n[![Open issue](https://img.shields.io/github/issues/xinntao/Real-ESRGAN)](https://github.com/xinntao/Real-ESRGAN/issues)\n[![Closed issue](https://img.shields.io/github/issues-closed/xinntao/Real-ESRGAN)](https://github.com/xinntao/Real-ESRGAN/issues)\n[![LICENSE](https://img.shields.io/github/license/xinntao/Real-ESRGAN.svg)](https://github.com/xinntao/Real-ESRGAN/blob/master/LICENSE)\n[![python lint](https://github.com/xinntao/Real-ESRGAN/actions/workflows/pylint.yml/badge.svg)](https://github.com/xinntao/Real-ESRGAN/blob/master/.github/workflows/pylint.yml)\n[![Publish-pip](https://github.com/xinntao/Real-ESRGAN/actions/workflows/publish-pip.yml/badge.svg)](https://github.com/xinntao/Real-ESRGAN/blob/master/.github/workflows/publish-pip.yml)\n\n</div>\n\n🔥 **AnimeVideo-v3 model (动漫视频小模型)**. Please see [[*anime video models*](docs/anime_video_model.md)] and [[*comparisons*](docs/anime_comparisons.md)]<br>\n🔥 **RealESRGAN_x4plus_anime_6B** for anime images **(动漫插图模型)**. Please see [[*anime_model*](docs/anime_model.md)]\n\n<!-- 1. You can try in our website: [ARC Demo](https://arc.tencent.com/en/ai-demos/imgRestore) (now only support RealESRGAN_x4plus_anime_6B) -->\n1. :boom: **Update** online Replicate demo: [![Replicate](https://img.shields.io/static/v1?label=Demo&message=Replicate&color=blue)](https://replicate.com/xinntao/realesrgan)\n1. Online Colab demo for Real-ESRGAN: [![Colab](https://img.shields.io/static/v1?label=Demo&message=Colab&color=orange)](https://colab.research.google.com/drive/1k2Zod6kSHEvraybHl50Lys0LerhyTMCo?usp=sharing) **|** Online Colab demo for for Real-ESRGAN (**anime videos**): [![Colab](https://img.shields.io/static/v1?label=Demo&message=Colab&color=orange)](https://colab.research.google.com/drive/1yNl9ORUxxlL4N0keJa2SEPB61imPQd1B?usp=sharing)\n1. Portable [Windows](https://github.com/xinntao/Real-ESRGAN/releases/download/v0.2.5.0/realesrgan-ncnn-vulkan-20220424-windows.zip) / [Linux](https://github.com/xinntao/Real-ESRGAN/releases/download/v0.2.5.0/realesrgan-ncnn-vulkan-20220424-ubuntu.zip) / [MacOS](https://github.com/xinntao/Real-ESRGAN/releases/download/v0.2.5.0/realesrgan-ncnn-vulkan-20220424-macos.zip) **executable files for Intel/AMD/Nvidia GPU**. You can find more information [here](#portable-executable-files-ncnn). The ncnn implementation is in [Real-ESRGAN-ncnn-vulkan](https://github.com/xinntao/Real-ESRGAN-ncnn-vulkan)\n<!-- 1. You can watch enhanced animations in [Tencent Video](https://v.qq.com/s/topic/v_child/render/fC4iyCAM.html). 欢迎观看[腾讯视频动漫修复](https://v.qq.com/s/topic/v_child/render/fC4iyCAM.html) -->\n\nReal-ESRGAN aims at developing **Practical Algorithms for General Image/Video Restoration**.<br>\nWe extend the powerful ESRGAN to a practical restoration application (namely, Real-ESRGAN), which is trained with pure synthetic data.\n\n🌌 Thanks for your valuable feedbacks/suggestions. All the feedbacks are updated in [feedback.md](docs/feedback.md).\n\n---\n\nIf Real-ESRGAN is helpful, please help to ⭐ this repo or recommend it to your friends 😊 <br>\nOther recommended projects:<br>\n▶️ [GFPGAN](https://github.com/TencentARC/GFPGAN): A practical algorithm for real-world face restoration <br>\n▶️ [BasicSR](https://github.com/xinntao/BasicSR): An open-source image and video restoration toolbox<br>\n▶️ [facexlib](https://github.com/xinntao/facexlib): A collection that provides useful face-relation functions.<br>\n▶️ [HandyView](https://github.com/xinntao/HandyView): A PyQt5-based image viewer that is handy for view and comparison <br>\n▶️ [HandyFigure](https://github.com/xinntao/HandyFigure): Open source of paper figures <br>\n\n---\n\n### 📖 Real-ESRGAN: Training Real-World Blind Super-Resolution with Pure Synthetic Data\n\n> [[Paper](https://arxiv.org/abs/2107.10833)] &emsp; [[YouTube Video](https://www.youtube.com/watch?v=fxHWoDSSvSc)] &emsp; [[B站讲解](https://www.bilibili.com/video/BV1H34y1m7sS/)] &emsp; [[Poster](https://xinntao.github.io/projects/RealESRGAN_src/RealESRGAN_poster.pdf)] &emsp; [[PPT slides](https://docs.google.com/presentation/d/1QtW6Iy8rm8rGLsJ0Ldti6kP-7Qyzy6XL/edit?usp=sharing&ouid=109799856763657548160&rtpof=true&sd=true)]<br>\n> [Xintao Wang](https://xinntao.github.io/), Liangbin Xie, [Chao Dong](https://scholar.google.com.hk/citations?user=OSDCB0UAAAAJ), [Ying Shan](https://scholar.google.com/citations?user=4oXBp9UAAAAJ&hl=en) <br>\n> [Tencent ARC Lab](https://arc.tencent.com/en/ai-demos/imgRestore); Shenzhen Institutes of Advanced Technology, Chinese Academy of Sciences\n\n<p align=\"center\">\n  <img src=\"assets/teaser.jpg\">\n</p>\n\n---\n\n<!---------------------------------- Updates --------------------------->\n## 🚩 Updates\n\n- ✅ Add the **realesr-general-x4v3** model - a tiny small model for general scenes. It also supports the **-dn** option to balance the noise (avoiding over-smooth results). **-dn** is short for denoising strength.\n- ✅ Update the **RealESRGAN AnimeVideo-v3** model. Please see [anime video models](docs/anime_video_model.md) and [comparisons](docs/anime_comparisons.md) for more details.\n- ✅ Add small models for anime videos. More details are in [anime video models](docs/anime_video_model.md).\n- ✅ Add the ncnn implementation [Real-ESRGAN-ncnn-vulkan](https://github.com/xinntao/Real-ESRGAN-ncnn-vulkan).\n- ✅ Add [*RealESRGAN_x4plus_anime_6B.pth*](https://github.com/xinntao/Real-ESRGAN/releases/download/v0.2.2.4/RealESRGAN_x4plus_anime_6B.pth), which is optimized for **anime** images with much smaller model size. More details and comparisons with [waifu2x](https://github.com/nihui/waifu2x-ncnn-vulkan) are in [**anime_model.md**](docs/anime_model.md)\n- ✅ Support finetuning on your own data or paired data (*i.e.*, finetuning ESRGAN). See [here](docs/Training.md#Finetune-Real-ESRGAN-on-your-own-dataset)\n- ✅ Integrate [GFPGAN](https://github.com/TencentARC/GFPGAN) to support **face enhancement**.\n- ✅ Integrated to [Huggingface Spaces](https://huggingface.co/spaces) with [Gradio](https://github.com/gradio-app/gradio). See [Gradio Web Demo](https://huggingface.co/spaces/akhaliq/Real-ESRGAN). Thanks [@AK391](https://github.com/AK391)\n- ✅ Support arbitrary scale with `--outscale` (It actually further resizes outputs with `LANCZOS4`). Add *RealESRGAN_x2plus.pth* model.\n- ✅ [The inference code](inference_realesrgan.py) supports: 1) **tile** options; 2) images with **alpha channel**; 3) **gray** images; 4) **16-bit** images.\n- ✅ The training codes have been released. A detailed guide can be found in [Training.md](docs/Training.md).\n\n---\n\n<!---------------------------------- Demo videos --------------------------->\n## 👀 Demos Videos\n\n#### Bilibili\n\n- [大闹天宫片段](https://www.bilibili.com/video/BV1ja41117zb)\n- [Anime dance cut 动漫魔性舞蹈](https://www.bilibili.com/video/BV1wY4y1L7hT/)\n- [海贼王片段](https://www.bilibili.com/video/BV1i3411L7Gy/)\n\n#### YouTube\n\n## 🔧 Dependencies and Installation\n\n- Python >= 3.7 (Recommend to use [Anaconda](https://www.anaconda.com/download/#linux) or [Miniconda](https://docs.conda.io/en/latest/miniconda.html))\n- [PyTorch >= 1.7](https://pytorch.org/)\n\n### Installation\n\n1. Clone repo\n\n    ```bash\n    git clone https://github.com/xinntao/Real-ESRGAN.git\n    cd Real-ESRGAN\n    ```\n\n1. Install dependent packages\n\n    ```bash\n    # Install basicsr - https://github.com/xinntao/BasicSR\n    # We use BasicSR for both training and inference\n    pip install basicsr\n    # facexlib and gfpgan are for face enhancement\n    pip install facexlib\n    pip install gfpgan\n    pip install -r requirements.txt\n    python setup.py develop\n    ```\n\n---\n\n## ⚡ Quick Inference\n\nThere are usually three ways to inference Real-ESRGAN.\n\n1. [Online inference](#online-inference)\n1. [Portable executable files (NCNN)](#portable-executable-files-ncnn)\n1. [Python script](#python-script)\n\n### Online inference\n\n1. You can try in our website: [ARC Demo](https://arc.tencent.com/en/ai-demos/imgRestore) (now only support RealESRGAN_x4plus_anime_6B)\n1. [Colab Demo](https://colab.research.google.com/drive/1k2Zod6kSHEvraybHl50Lys0LerhyTMCo?usp=sharing) for Real-ESRGAN **|** [Colab Demo](https://colab.research.google.com/drive/1yNl9ORUxxlL4N0keJa2SEPB61imPQd1B?usp=sharing) for Real-ESRGAN (**anime videos**).\n\n### Portable executable files (NCNN)\n\nYou can download [Windows](https://github.com/xinntao/Real-ESRGAN/releases/download/v0.2.5.0/realesrgan-ncnn-vulkan-20220424-windows.zip) / [Linux](https://github.com/xinntao/Real-ESRGAN/releases/download/v0.2.5.0/realesrgan-ncnn-vulkan-20220424-ubuntu.zip) / [MacOS](https://github.com/xinntao/Real-ESRGAN/releases/download/v0.2.5.0/realesrgan-ncnn-vulkan-20220424-macos.zip) **executable files for Intel/AMD/Nvidia GPU**.\n\nThis executable file is **portable** and includes all the binaries and models required. No CUDA or PyTorch environment is needed.<br>\n\nYou can simply run the following command (the Windows example, more information is in the README.md of each executable files):\n\n```bash\n./realesrgan-ncnn-vulkan.exe -i input.jpg -o output.png -n model_name\n```\n\nWe have provided five models:\n\n1. realesrgan-x4plus  (default)\n2. realesrnet-x4plus\n3. realesrgan-x4plus-anime (optimized for anime images, small model size)\n4. realesr-animevideov3 (animation video)\n\nYou can use the `-n` argument for other models, for example, `./realesrgan-ncnn-vulkan.exe -i input.jpg -o output.png -n realesrnet-x4plus`\n\n#### Usage of portable executable files\n\n1. Please refer to [Real-ESRGAN-ncnn-vulkan](https://github.com/xinntao/Real-ESRGAN-ncnn-vulkan#computer-usages) for more details.\n1. Note that it does not support all the functions (such as `outscale`) as the python script `inference_realesrgan.py`.\n\n```console\nUsage: realesrgan-ncnn-vulkan.exe -i infile -o outfile [options]...\n\n  -h                   show this help\n  -i input-path        input image path (jpg/png/webp) or directory\n  -o output-path       output image path (jpg/png/webp) or directory\n  -s scale             upscale ratio (can be 2, 3, 4. default=4)\n  -t tile-size         tile size (>=32/0=auto, default=0) can be 0,0,0 for multi-gpu\n  -m model-path        folder path to the pre-trained models. default=models\n  -n model-name        model name (default=realesr-animevideov3, can be realesr-animevideov3 | realesrgan-x4plus | realesrgan-x4plus-anime | realesrnet-x4plus)\n  -g gpu-id            gpu device to use (default=auto) can be 0,1,2 for multi-gpu\n  -j load:proc:save    thread count for load/proc/save (default=1:2:2) can be 1:2,2,2:2 for multi-gpu\n  -x                   enable tta mode\"\n  -f format            output image format (jpg/png/webp, default=ext/png)\n  -v                   verbose output\n```\n\nNote that it may introduce block inconsistency (and also generate slightly different results from the PyTorch implementation), because this executable file first crops the input image into several tiles, and then processes them separately, finally stitches together.\n\n### Python script\n\n#### Usage of python script\n\n1. You can use X4 model for **arbitrary output size** with the argument `outscale`. The program will further perform cheap resize operation after the Real-ESRGAN output.\n\n```console\nUsage: python inference_realesrgan.py -n RealESRGAN_x4plus -i infile -o outfile [options]...\n\nA common command: python inference_realesrgan.py -n RealESRGAN_x4plus -i infile --outscale 3.5 --face_enhance\n\n  -h                   show this help\n  -i --input           Input image or folder. Default: inputs\n  -o --output          Output folder. Default: results\n  -n --model_name      Model name. Default: RealESRGAN_x4plus\n  -s, --outscale       The final upsampling scale of the image. Default: 4\n  --suffix             Suffix of the restored image. Default: out\n  -t, --tile           Tile size, 0 for no tile during testing. Default: 0\n  --face_enhance       Whether to use GFPGAN to enhance face. Default: False\n  --fp32               Use fp32 precision during inference. Default: fp16 (half precision).\n  --ext                Image extension. Options: auto | jpg | png, auto means using the same extension as inputs. Default: auto\n```\n\n#### Inference general images\n\nDownload pre-trained models: [RealESRGAN_x4plus.pth](https://github.com/xinntao/Real-ESRGAN/releases/download/v0.1.0/RealESRGAN_x4plus.pth)\n\n```bash\nwget https://github.com/xinntao/Real-ESRGAN/releases/download/v0.1.0/RealESRGAN_x4plus.pth -P weights\n```\n\nInference!\n\n```bash\npython inference_realesrgan.py -n RealESRGAN_x4plus -i inputs --face_enhance\n```\n\nResults are in the `results` folder\n\n#### Inference anime images\n\n<p align=\"center\">\n  <img src=\"https://raw.githubusercontent.com/xinntao/public-figures/master/Real-ESRGAN/cmp_realesrgan_anime_1.png\">\n</p>\n\nPre-trained models: [RealESRGAN_x4plus_anime_6B](https://github.com/xinntao/Real-ESRGAN/releases/download/v0.2.2.4/RealESRGAN_x4plus_anime_6B.pth)<br>\n More details and comparisons with [waifu2x](https://github.com/nihui/waifu2x-ncnn-vulkan) are in [**anime_model.md**](docs/anime_model.md)\n\n```bash\n# download model\nwget https://github.com/xinntao/Real-ESRGAN/releases/download/v0.2.2.4/RealESRGAN_x4plus_anime_6B.pth -P weights\n# inference\npython inference_realesrgan.py -n RealESRGAN_x4plus_anime_6B -i inputs\n```\n\nResults are in the `results` folder\n\n---\n\n## BibTeX\n\n    @InProceedings{wang2021realesrgan,\n        author    = {Xintao Wang and Liangbin Xie and Chao Dong and Ying Shan},\n        title     = {Real-ESRGAN: Training Real-World Blind Super-Resolution with Pure Synthetic Data},\n        booktitle = {International Conference on Computer Vision Workshops (ICCVW)},\n        date      = {2021}\n    }\n\n## 📧 Contact\n\nIf you have any question, please email `xintao.wang@outlook.com` or `xintaowang@tencent.com`.\n\n<!---------------------------------- Projects that use Real-ESRGAN --------------------------->\n## 🧩 Projects that use Real-ESRGAN\n\nIf you develop/use Real-ESRGAN in your projects, welcome to let me know.\n\n- NCNN-Android: [RealSR-NCNN-Android](https://github.com/tumuyan/RealSR-NCNN-Android) by [tumuyan](https://github.com/tumuyan)\n- VapourSynth: [vs-realesrgan](https://github.com/HolyWu/vs-realesrgan) by [HolyWu](https://github.com/HolyWu)\n- NCNN: [Real-ESRGAN-ncnn-vulkan](https://github.com/xinntao/Real-ESRGAN-ncnn-vulkan)\n\n&nbsp;&nbsp;&nbsp;&nbsp;**GUI**\n\n- [Waifu2x-Extension-GUI](https://github.com/AaronFeng753/Waifu2x-Extension-GUI) by [AaronFeng753](https://github.com/AaronFeng753)\n- [Squirrel-RIFE](https://github.com/Justin62628/Squirrel-RIFE) by [Justin62628](https://github.com/Justin62628)\n- [Real-GUI](https://github.com/scifx/Real-GUI) by [scifx](https://github.com/scifx)\n- [Real-ESRGAN_GUI](https://github.com/net2cn/Real-ESRGAN_GUI) by [net2cn](https://github.com/net2cn)\n- [Real-ESRGAN-EGUI](https://github.com/WGzeyu/Real-ESRGAN-EGUI) by [WGzeyu](https://github.com/WGzeyu)\n- [anime_upscaler](https://github.com/shangar21/anime_upscaler) by [shangar21](https://github.com/shangar21)\n- [Upscayl](https://github.com/upscayl/upscayl) by [Nayam Amarshe](https://github.com/NayamAmarshe) and [TGS963](https://github.com/TGS963)\n\n## 🤗 Acknowledgement\n\nThanks for all the contributors.\n\n- [AK391](https://github.com/AK391): Integrate RealESRGAN to [Huggingface Spaces](https://huggingface.co/spaces) with [Gradio](https://github.com/gradio-app/gradio). See [Gradio Web Demo](https://huggingface.co/spaces/akhaliq/Real-ESRGAN).\n- [Asiimoviet](https://github.com/Asiimoviet): Translate the README.md to Chinese (中文).\n- [2ji3150](https://github.com/2ji3150): Thanks for the [detailed and valuable feedbacks/suggestions](https://github.com/xinntao/Real-ESRGAN/issues/131).\n- [Jared-02](https://github.com/Jared-02): Translate the Training.md to Chinese (中文).\n"
  },
  {
    "path": "README_CN.md",
    "content": "<p align=\"center\">\n  <img src=\"assets/realesrgan_logo.png\" height=120>\n</p>\n\n## <div align=\"center\"><b><a href=\"README.md\">English</a> | <a href=\"README_CN.md\">简体中文</a></b></div>\n\n[![download](https://img.shields.io/github/downloads/xinntao/Real-ESRGAN/total.svg)](https://github.com/xinntao/Real-ESRGAN/releases)\n[![PyPI](https://img.shields.io/pypi/v/realesrgan)](https://pypi.org/project/realesrgan/)\n[![Open issue](https://img.shields.io/github/issues/xinntao/Real-ESRGAN)](https://github.com/xinntao/Real-ESRGAN/issues)\n[![Closed issue](https://img.shields.io/github/issues-closed/xinntao/Real-ESRGAN)](https://github.com/xinntao/Real-ESRGAN/issues)\n[![LICENSE](https://img.shields.io/github/license/xinntao/Real-ESRGAN.svg)](https://github.com/xinntao/Real-ESRGAN/blob/master/LICENSE)\n[![python lint](https://github.com/xinntao/Real-ESRGAN/actions/workflows/pylint.yml/badge.svg)](https://github.com/xinntao/Real-ESRGAN/blob/master/.github/workflows/pylint.yml)\n[![Publish-pip](https://github.com/xinntao/Real-ESRGAN/actions/workflows/publish-pip.yml/badge.svg)](https://github.com/xinntao/Real-ESRGAN/blob/master/.github/workflows/publish-pip.yml)\n\n:fire: 更新动漫视频的小模型 **RealESRGAN AnimeVideo-v3**. 更多信息在 [[动漫视频模型介绍](docs/anime_video_model.md)] 和 [[比较](docs/anime_comparisons_CN.md)] 中.\n\n1. Real-ESRGAN的[Colab Demo](https://colab.research.google.com/drive/1k2Zod6kSHEvraybHl50Lys0LerhyTMCo?usp=sharing) | Real-ESRGAN**动漫视频** 的[Colab Demo](https://colab.research.google.com/drive/1yNl9ORUxxlL4N0keJa2SEPB61imPQd1B?usp=sharing)\n2. **支持Intel/AMD/Nvidia显卡**的绿色版exe文件： [Windows版](https://github.com/xinntao/Real-ESRGAN/releases/download/v0.2.5.0/realesrgan-ncnn-vulkan-20220424-windows.zip) / [Linux版](https://github.com/xinntao/Real-ESRGAN/releases/download/v0.2.5.0/realesrgan-ncnn-vulkan-20220424-ubuntu.zip) / [macOS版](https://github.com/xinntao/Real-ESRGAN/releases/download/v0.2.5.0/realesrgan-ncnn-vulkan-20220424-macos.zip)，详情请移步[这里](#便携版（绿色版）可执行文件)。NCNN的实现在 [Real-ESRGAN-ncnn-vulkan](https://github.com/xinntao/Real-ESRGAN-ncnn-vulkan)。\n\nReal-ESRGAN 的目标是开发出**实用的图像/视频修复算法**。<br>\n我们在 ESRGAN 的基础上使用纯合成的数据来进行训练，以使其能被应用于实际的图片修复的场景（顾名思义：Real-ESRGAN）。\n\n:art: Real-ESRGAN 需要，也很欢迎你的贡献，如新功能、模型、bug修复、建议、维护等等。详情可以查看[CONTRIBUTING.md](docs/CONTRIBUTING.md)，所有的贡献者都会被列在[此处](README_CN.md#hugs-感谢)。\n\n:milky_way: 感谢大家提供了很好的反馈。这些反馈会逐步更新在 [这个文档](docs/feedback.md)。\n\n:question: 常见的问题可以在[FAQ.md](docs/FAQ.md)中找到答案。（好吧，现在还是空白的=-=||）\n\n---\n\n如果 Real-ESRGAN 对你有帮助，可以给本项目一个 Star :star: ，或者推荐给你的朋友们，谢谢！:blush: <br/>\n其他推荐的项目：<br/>\n:arrow_forward: [GFPGAN](https://github.com/TencentARC/GFPGAN): 实用的人脸复原算法 <br>\n:arrow_forward: [BasicSR](https://github.com/xinntao/BasicSR): 开源的图像和视频工具箱<br>\n:arrow_forward: [facexlib](https://github.com/xinntao/facexlib): 提供与人脸相关的工具箱<br>\n:arrow_forward: [HandyView](https://github.com/xinntao/HandyView): 基于PyQt5的图片查看器，方便查看以及比较 <br>\n\n---\n\n<!---------------------------------- Updates --------------------------->\n<details>\n<summary>🚩<b>更新</b></summary>\n\n- ✅ 更新动漫视频的小模型 **RealESRGAN AnimeVideo-v3**. 更多信息在 [anime video models](docs/anime_video_model.md) 和 [comparisons](docs/anime_comparisons.md)中.\n- ✅ 添加了针对动漫视频的小模型, 更多信息在 [anime video models](docs/anime_video_model.md) 中.\n- ✅ 添加了ncnn 实现：[Real-ESRGAN-ncnn-vulkan](https://github.com/xinntao/Real-ESRGAN-ncnn-vulkan).\n- ✅ 添加了 [*RealESRGAN_x4plus_anime_6B.pth*](https://github.com/xinntao/Real-ESRGAN/releases/download/v0.2.2.4/RealESRGAN_x4plus_anime_6B.pth)，对二次元图片进行了优化，并减少了model的大小。详情 以及 与[waifu2x](https://github.com/nihui/waifu2x-ncnn-vulkan)的对比请查看[**anime_model.md**](docs/anime_model.md)\n- ✅支持用户在自己的数据上进行微调 (finetune)：[详情](docs/Training.md#Finetune-Real-ESRGAN-on-your-own-dataset)\n- ✅ 支持使用[GFPGAN](https://github.com/TencentARC/GFPGAN)**增强人脸**\n- ✅ 通过[Gradio](https://github.com/gradio-app/gradio)添加到了[Huggingface Spaces](https://huggingface.co/spaces)（一个机器学习应用的在线平台）：[Gradio在线版](https://huggingface.co/spaces/akhaliq/Real-ESRGAN)。感谢[@AK391](https://github.com/AK391)\n- ✅ 支持任意比例的缩放：`--outscale`（实际上使用`LANCZOS4`来更进一步调整输出图像的尺寸）。添加了*RealESRGAN_x2plus.pth*模型\n- ✅ [推断脚本](inference_realesrgan.py)支持: 1) 分块处理**tile**; 2) 带**alpha通道**的图像; 3) **灰色**图像; 4) **16-bit**图像.\n- ✅ 训练代码已经发布，具体做法可查看：[Training.md](docs/Training.md)。\n\n</details>\n\n<!---------------------------------- Projects that use Real-ESRGAN --------------------------->\n<details>\n<summary>🧩<b>使用Real-ESRGAN的项目</b></summary>\n\n&nbsp;&nbsp;&nbsp;&nbsp;👋 如果你开发/使用/集成了Real-ESRGAN, 欢迎联系我添加\n\n- NCNN-Android: [RealSR-NCNN-Android](https://github.com/tumuyan/RealSR-NCNN-Android) by [tumuyan](https://github.com/tumuyan)\n- VapourSynth: [vs-realesrgan](https://github.com/HolyWu/vs-realesrgan) by [HolyWu](https://github.com/HolyWu)\n- NCNN: [Real-ESRGAN-ncnn-vulkan](https://github.com/xinntao/Real-ESRGAN-ncnn-vulkan)\n\n&nbsp;&nbsp;&nbsp;&nbsp;**易用的图形界面**\n\n- [Waifu2x-Extension-GUI](https://github.com/AaronFeng753/Waifu2x-Extension-GUI) by [AaronFeng753](https://github.com/AaronFeng753)\n- [Squirrel-RIFE](https://github.com/Justin62628/Squirrel-RIFE) by [Justin62628](https://github.com/Justin62628)\n- [Real-GUI](https://github.com/scifx/Real-GUI) by [scifx](https://github.com/scifx)\n- [Real-ESRGAN_GUI](https://github.com/net2cn/Real-ESRGAN_GUI) by [net2cn](https://github.com/net2cn)\n- [Real-ESRGAN-EGUI](https://github.com/WGzeyu/Real-ESRGAN-EGUI) by [WGzeyu](https://github.com/WGzeyu)\n- [anime_upscaler](https://github.com/shangar21/anime_upscaler) by [shangar21](https://github.com/shangar21)\n- [RealESRGAN-GUI](https://github.com/Baiyuetribe/paper2gui/blob/main/Video%20Super%20Resolution/RealESRGAN-GUI.md) by [Baiyuetribe](https://github.com/Baiyuetribe)\n\n</details>\n\n<details>\n<summary>👀<b>Demo视频（B站）</b></summary>\n\n- [大闹天宫片段](https://www.bilibili.com/video/BV1ja41117zb)\n\n</details>\n\n### :book: Real-ESRGAN: Training Real-World Blind Super-Resolution with Pure Synthetic Data\n\n> [[论文](https://arxiv.org/abs/2107.10833)] &emsp; [项目主页] &emsp; [[YouTube 视频](https://www.youtube.com/watch?v=fxHWoDSSvSc)] &emsp; [[B站视频](https://www.bilibili.com/video/BV1H34y1m7sS/)] &emsp; [[Poster](https://xinntao.github.io/projects/RealESRGAN_src/RealESRGAN_poster.pdf)] &emsp; [[PPT](https://docs.google.com/presentation/d/1QtW6Iy8rm8rGLsJ0Ldti6kP-7Qyzy6XL/edit?usp=sharing&ouid=109799856763657548160&rtpof=true&sd=true)]<br>\n> [Xintao Wang](https://xinntao.github.io/), Liangbin Xie, [Chao Dong](https://scholar.google.com.hk/citations?user=OSDCB0UAAAAJ), [Ying Shan](https://scholar.google.com/citations?user=4oXBp9UAAAAJ&hl=en) <br>\n> Tencent ARC Lab; Shenzhen Institutes of Advanced Technology, Chinese Academy of Sciences\n\n<p align=\"center\">\n  <img src=\"assets/teaser.jpg\">\n</p>\n\n---\n\n我们提供了一套训练好的模型（*RealESRGAN_x4plus.pth*)，可以进行4倍的超分辨率。<br>\n**现在的 Real-ESRGAN 还是有几率失败的，因为现实生活的降质过程比较复杂。**<br>\n而且，本项目对**人脸以及文字之类**的效果还不是太好，但是我们会持续进行优化的。<br>\n\nReal-ESRGAN 将会被长期支持，我会在空闲的时间中持续维护更新。\n\n这些是未来计划的几个新功能：\n\n- [ ] 优化人脸\n- [ ] 优化文字\n- [x] 优化动画图像\n- [ ] 支持更多的超分辨率比例\n- [ ] 可调节的复原\n\n如果你有好主意或需求，欢迎在 issue 或 discussion 中提出。<br/>\n如果你有一些 Real-ESRGAN 中有问题的照片，你也可以在 issue 或者 discussion 中发出来。我会留意（但是不一定能解决:stuck_out_tongue:）。如果有必要的话，我还会专门开一页来记录那些有待解决的图像。\n\n---\n\n### 便携版（绿色版）可执行文件\n\n你可以下载**支持Intel/AMD/Nvidia显卡**的绿色版exe文件： [Windows版](https://github.com/xinntao/Real-ESRGAN/releases/download/v0.2.5.0/realesrgan-ncnn-vulkan-20220424-windows.zip) / [Linux版](https://github.com/xinntao/Real-ESRGAN/releases/download/v0.2.5.0/realesrgan-ncnn-vulkan-20220424-ubuntu.zip) / [macOS版](https://github.com/xinntao/Real-ESRGAN/releases/download/v0.2.5.0/realesrgan-ncnn-vulkan-20220424-macos.zip)。\n\n绿色版指的是这些exe你可以直接运行（放U盘里拷走都没问题），因为里面已经有所需的文件和模型了。它不需要 CUDA 或者 PyTorch运行环境。<br>\n\n你可以通过下面这个命令来运行（Windows版本的例子，更多信息请查看对应版本的README.md）：\n\n```bash\n./realesrgan-ncnn-vulkan.exe -i 输入图像.jpg -o 输出图像.png -n 模型名字\n```\n\n我们提供了五种模型：\n\n1. realesrgan-x4plus（默认）\n2. reaesrnet-x4plus\n3. realesrgan-x4plus-anime（针对动漫插画图像优化，有更小的体积）\n4. realesr-animevideov3 (针对动漫视频)\n\n你可以通过`-n`参数来使用其他模型，例如`./realesrgan-ncnn-vulkan.exe -i 二次元图片.jpg -o 二刺螈图片.png -n realesrgan-x4plus-anime`\n\n### 可执行文件的用法\n\n1. 更多细节可以参考 [Real-ESRGAN-ncnn-vulkan](https://github.com/xinntao/Real-ESRGAN-ncnn-vulkan#computer-usages).\n2. 注意：可执行文件并没有支持 python 脚本 `inference_realesrgan.py` 中所有的功能，比如 `outscale` 选项) .\n\n```console\nUsage: realesrgan-ncnn-vulkan.exe -i infile -o outfile [options]...\n\n  -h                   show this help\n  -i input-path        input image path (jpg/png/webp) or directory\n  -o output-path       output image path (jpg/png/webp) or directory\n  -s scale             upscale ratio (can be 2, 3, 4. default=4)\n  -t tile-size         tile size (>=32/0=auto, default=0) can be 0,0,0 for multi-gpu\n  -m model-path        folder path to the pre-trained models. default=models\n  -n model-name        model name (default=realesr-animevideov3, can be realesr-animevideov3 | realesrgan-x4plus | realesrgan-x4plus-anime | realesrnet-x4plus)\n  -g gpu-id            gpu device to use (default=auto) can be 0,1,2 for multi-gpu\n  -j load:proc:save    thread count for load/proc/save (default=1:2:2) can be 1:2,2,2:2 for multi-gpu\n  -x                   enable tta mode\"\n  -f format            output image format (jpg/png/webp, default=ext/png)\n  -v                   verbose output\n```\n\n由于这些exe文件会把图像分成几个板块，然后来分别进行处理，再合成导出，输出的图像可能会有一点割裂感（而且可能跟PyTorch的输出不太一样）\n\n---\n\n## :wrench: 依赖以及安装\n\n- Python >= 3.7 (推荐使用[Anaconda](https://www.anaconda.com/download/#linux)或[Miniconda](https://docs.conda.io/en/latest/miniconda.html))\n- [PyTorch >= 1.7](https://pytorch.org/)\n\n#### 安装\n\n1. 把项目克隆到本地\n\n    ```bash\n    git clone https://github.com/xinntao/Real-ESRGAN.git\n    cd Real-ESRGAN\n    ```\n\n2. 安装各种依赖\n\n    ```bash\n    # 安装 basicsr - https://github.com/xinntao/BasicSR\n    # 我们使用BasicSR来训练以及推断\n    pip install basicsr\n    # facexlib和gfpgan是用来增强人脸的\n    pip install facexlib\n    pip install gfpgan\n    pip install -r requirements.txt\n    python setup.py develop\n    ```\n\n## :zap: 快速上手\n\n### 普通图片\n\n下载我们训练好的模型: [RealESRGAN_x4plus.pth](https://github.com/xinntao/Real-ESRGAN/releases/download/v0.1.0/RealESRGAN_x4plus.pth)\n\n```bash\nwget https://github.com/xinntao/Real-ESRGAN/releases/download/v0.1.0/RealESRGAN_x4plus.pth -P weights\n```\n\n推断!\n\n```bash\npython inference_realesrgan.py -n RealESRGAN_x4plus -i inputs --face_enhance\n```\n\n结果在`results`文件夹\n\n### 动画图片\n\n<p align=\"center\">\n  <img src=\"https://raw.githubusercontent.com/xinntao/public-figures/master/Real-ESRGAN/cmp_realesrgan_anime_1.png\">\n</p>\n\n训练好的模型: [RealESRGAN_x4plus_anime_6B](https://github.com/xinntao/Real-ESRGAN/releases/download/v0.2.2.4/RealESRGAN_x4plus_anime_6B.pth)<br>\n有关[waifu2x](https://github.com/nihui/waifu2x-ncnn-vulkan)的更多信息和对比在[**anime_model.md**](docs/anime_model.md)中。\n\n```bash\n# 下载模型\nwget https://github.com/xinntao/Real-ESRGAN/releases/download/v0.2.2.4/RealESRGAN_x4plus_anime_6B.pth -P weights\n# 推断\npython inference_realesrgan.py -n RealESRGAN_x4plus_anime_6B -i inputs\n```\n\n结果在`results`文件夹\n\n### Python 脚本的用法\n\n1. 虽然你使用了 X4 模型，但是你可以 **输出任意尺寸比例的图片**，只要实用了 `outscale` 参数. 程序会进一步对模型的输出图像进行缩放。\n\n```console\nUsage: python inference_realesrgan.py -n RealESRGAN_x4plus -i infile -o outfile [options]...\n\nA common command: python inference_realesrgan.py -n RealESRGAN_x4plus -i infile --outscale 3.5 --face_enhance\n\n  -h                   show this help\n  -i --input           Input image or folder. Default: inputs\n  -o --output          Output folder. Default: results\n  -n --model_name      Model name. Default: RealESRGAN_x4plus\n  -s, --outscale       The final upsampling scale of the image. Default: 4\n  --suffix             Suffix of the restored image. Default: out\n  -t, --tile           Tile size, 0 for no tile during testing. Default: 0\n  --face_enhance       Whether to use GFPGAN to enhance face. Default: False\n  --fp32               Whether to use half precision during inference. Default: False\n  --ext                Image extension. Options: auto | jpg | png, auto means using the same extension as inputs. Default: auto\n```\n\n## :european_castle: 模型库\n\n请参见 [docs/model_zoo.md](docs/model_zoo.md)\n\n## :computer: 训练，在你的数据上微调（Fine-tune）\n\n这里有一份详细的指南：[Training.md](docs/Training.md).\n\n## BibTeX 引用\n\n    @Article{wang2021realesrgan,\n        title={Real-ESRGAN: Training Real-World Blind Super-Resolution with Pure Synthetic Data},\n        author={Xintao Wang and Liangbin Xie and Chao Dong and Ying Shan},\n        journal={arXiv:2107.10833},\n        year={2021}\n    }\n\n## :e-mail: 联系我们\n\n如果你有任何问题，请通过 `xintao.wang@outlook.com` 或 `xintaowang@tencent.com` 联系我们。\n\n## :hugs: 感谢\n\n感谢所有的贡献者大大们~\n\n- [AK391](https://github.com/AK391): 通过[Gradio](https://github.com/gradio-app/gradio)添加到了[Huggingface Spaces](https://huggingface.co/spaces)（一个机器学习应用的在线平台）：[Gradio在线版](https://huggingface.co/spaces/akhaliq/Real-ESRGAN)。\n- [Asiimoviet](https://github.com/Asiimoviet): 把 README.md 文档 翻译成了中文。\n- [2ji3150](https://github.com/2ji3150): 感谢详尽并且富有价值的[反馈、建议](https://github.com/xinntao/Real-ESRGAN/issues/131).\n- [Jared-02](https://github.com/Jared-02): 把 Training.md 文档 翻译成了中文。\n"
  },
  {
    "path": "VERSION",
    "content": "0.3.0\n"
  },
  {
    "path": "cog.yaml",
    "content": "# This file is used for constructing replicate env\nimage: \"r8.im/tencentarc/realesrgan\"\n\nbuild:\n  gpu: true\n  python_version: \"3.8\"\n  system_packages:\n    - \"libgl1-mesa-glx\"\n    - \"libglib2.0-0\"\n  python_packages:\n    - \"torch==1.7.1\"\n    - \"torchvision==0.8.2\"\n    - \"numpy==1.21.1\"\n    - \"lmdb==1.2.1\"\n    - \"opencv-python==4.5.3.56\"\n    - \"PyYAML==5.4.1\"\n    - \"tqdm==4.62.2\"\n    - \"yapf==0.31.0\"\n    - \"basicsr==1.4.2\"\n    - \"facexlib==0.2.5\"\n\npredict: \"cog_predict.py:Predictor\"\n"
  },
  {
    "path": "cog_predict.py",
    "content": "# flake8: noqa\n# This file is used for deploying replicate models\n# running: cog predict -i img=@inputs/00017_gray.png -i version='General - v3' -i scale=2 -i face_enhance=True -i tile=0\n# push: cog push r8.im/xinntao/realesrgan\n\nimport os\n\nos.system('pip install gfpgan')\nos.system('python setup.py develop')\n\nimport cv2\nimport shutil\nimport tempfile\nimport torch\nfrom basicsr.archs.rrdbnet_arch import RRDBNet\nfrom basicsr.archs.srvgg_arch import SRVGGNetCompact\n\nfrom realesrgan.utils import RealESRGANer\n\ntry:\n    from cog import BasePredictor, Input, Path\n    from gfpgan import GFPGANer\nexcept Exception:\n    print('please install cog and realesrgan package')\n\n\nclass Predictor(BasePredictor):\n\n    def setup(self):\n        os.makedirs('output', exist_ok=True)\n        # download weights\n        if not os.path.exists('weights/realesr-general-x4v3.pth'):\n            os.system(\n                'wget https://github.com/xinntao/Real-ESRGAN/releases/download/v0.2.5.0/realesr-general-x4v3.pth -P ./weights'\n            )\n        if not os.path.exists('weights/GFPGANv1.4.pth'):\n            os.system('wget https://github.com/TencentARC/GFPGAN/releases/download/v1.3.0/GFPGANv1.4.pth -P ./weights')\n        if not os.path.exists('weights/RealESRGAN_x4plus.pth'):\n            os.system(\n                'wget https://github.com/xinntao/Real-ESRGAN/releases/download/v0.1.0/RealESRGAN_x4plus.pth -P ./weights'\n            )\n        if not os.path.exists('weights/RealESRGAN_x4plus_anime_6B.pth'):\n            os.system(\n                'wget https://github.com/xinntao/Real-ESRGAN/releases/download/v0.2.2.4/RealESRGAN_x4plus_anime_6B.pth -P ./weights'\n            )\n        if not os.path.exists('weights/realesr-animevideov3.pth'):\n            os.system(\n                'wget https://github.com/xinntao/Real-ESRGAN/releases/download/v0.2.5.0/realesr-animevideov3.pth -P ./weights'\n            )\n\n    def choose_model(self, scale, version, tile=0):\n        half = True if torch.cuda.is_available() else False\n        if version == 'General - RealESRGANplus':\n            model = RRDBNet(num_in_ch=3, num_out_ch=3, num_feat=64, num_block=23, num_grow_ch=32, scale=4)\n            model_path = 'weights/RealESRGAN_x4plus.pth'\n            self.upsampler = RealESRGANer(\n                scale=4, model_path=model_path, model=model, tile=tile, tile_pad=10, pre_pad=0, half=half)\n        elif version == 'General - v3':\n            model = SRVGGNetCompact(num_in_ch=3, num_out_ch=3, num_feat=64, num_conv=32, upscale=4, act_type='prelu')\n            model_path = 'weights/realesr-general-x4v3.pth'\n            self.upsampler = RealESRGANer(\n                scale=4, model_path=model_path, model=model, tile=tile, tile_pad=10, pre_pad=0, half=half)\n        elif version == 'Anime - anime6B':\n            model = RRDBNet(num_in_ch=3, num_out_ch=3, num_feat=64, num_block=6, num_grow_ch=32, scale=4)\n            model_path = 'weights/RealESRGAN_x4plus_anime_6B.pth'\n            self.upsampler = RealESRGANer(\n                scale=4, model_path=model_path, model=model, tile=tile, tile_pad=10, pre_pad=0, half=half)\n        elif version == 'AnimeVideo - v3':\n            model = SRVGGNetCompact(num_in_ch=3, num_out_ch=3, num_feat=64, num_conv=16, upscale=4, act_type='prelu')\n            model_path = 'weights/realesr-animevideov3.pth'\n            self.upsampler = RealESRGANer(\n                scale=4, model_path=model_path, model=model, tile=tile, tile_pad=10, pre_pad=0, half=half)\n\n        self.face_enhancer = GFPGANer(\n            model_path='weights/GFPGANv1.4.pth',\n            upscale=scale,\n            arch='clean',\n            channel_multiplier=2,\n            bg_upsampler=self.upsampler)\n\n    def predict(\n        self,\n        img: Path = Input(description='Input'),\n        version: str = Input(\n            description='RealESRGAN version. Please see [Readme] below for more descriptions',\n            choices=['General - RealESRGANplus', 'General - v3', 'Anime - anime6B', 'AnimeVideo - v3'],\n            default='General - v3'),\n        scale: float = Input(description='Rescaling factor', default=2),\n        face_enhance: bool = Input(\n            description='Enhance faces with GFPGAN. Note that it does not work for anime images/vidoes', default=False),\n        tile: int = Input(\n            description=\n            'Tile size. Default is 0, that is no tile. When encountering the out-of-GPU-memory issue, please specify it, e.g., 400 or 200',\n            default=0)\n    ) -> Path:\n        if tile <= 100 or tile is None:\n            tile = 0\n        print(f'img: {img}. version: {version}. scale: {scale}. face_enhance: {face_enhance}. tile: {tile}.')\n        try:\n            extension = os.path.splitext(os.path.basename(str(img)))[1]\n            img = cv2.imread(str(img), cv2.IMREAD_UNCHANGED)\n            if len(img.shape) == 3 and img.shape[2] == 4:\n                img_mode = 'RGBA'\n            elif len(img.shape) == 2:\n                img_mode = None\n                img = cv2.cvtColor(img, cv2.COLOR_GRAY2BGR)\n            else:\n                img_mode = None\n\n            h, w = img.shape[0:2]\n            if h < 300:\n                img = cv2.resize(img, (w * 2, h * 2), interpolation=cv2.INTER_LANCZOS4)\n\n            self.choose_model(scale, version, tile)\n\n            try:\n                if face_enhance:\n                    _, _, output = self.face_enhancer.enhance(\n                        img, has_aligned=False, only_center_face=False, paste_back=True)\n                else:\n                    output, _ = self.upsampler.enhance(img, outscale=scale)\n            except RuntimeError as error:\n                print('Error', error)\n                print('If you encounter CUDA out of memory, try to set \"tile\" to a smaller size, e.g., 400.')\n\n            if img_mode == 'RGBA':  # RGBA images should be saved in png format\n                extension = 'png'\n            # save_path = f'output/out.{extension}'\n            # cv2.imwrite(save_path, output)\n            out_path = Path(tempfile.mkdtemp()) / f'out.{extension}'\n            cv2.imwrite(str(out_path), output)\n        except Exception as error:\n            print('global exception: ', error)\n        finally:\n            clean_folder('output')\n        return out_path\n\n\ndef clean_folder(folder):\n    for filename in os.listdir(folder):\n        file_path = os.path.join(folder, filename)\n        try:\n            if os.path.isfile(file_path) or os.path.islink(file_path):\n                os.unlink(file_path)\n            elif os.path.isdir(file_path):\n                shutil.rmtree(file_path)\n        except Exception as e:\n            print(f'Failed to delete {file_path}. Reason: {e}')\n"
  },
  {
    "path": "docs/CONTRIBUTING.md",
    "content": "# Contributing to Real-ESRGAN\n\n:art: Real-ESRGAN needs your contributions. Any contributions are welcome, such as new features/models/typo fixes/suggestions/maintenance, *etc*. See [CONTRIBUTING.md](docs/CONTRIBUTING.md). All contributors are list [here](README.md#hugs-acknowledgement).\n\nWe like open-source and want to develop practical algorithms for general image restoration. However, individual strength is limited. So, any kinds of contributions are welcome, such as:\n\n- New features\n- New models (your fine-tuned models)\n- Bug fixes\n- Typo fixes\n- Suggestions\n- Maintenance\n- Documents\n- *etc*\n\n## Workflow\n\n1. Fork and pull the latest Real-ESRGAN repository\n1. Checkout a new branch (do not use master branch for PRs)\n1. Commit your changes\n1. Create a PR\n\n**Note**:\n\n1. Please check the code style and linting\n    1. The style configuration is specified in [setup.cfg](setup.cfg)\n    1. If you use VSCode, the settings are configured in [.vscode/settings.json](.vscode/settings.json)\n1. Strongly recommend using `pre-commit hook`. It will check your code style and linting before your commit.\n    1. In the root path of project folder, run `pre-commit install`\n    1. The pre-commit configuration is listed in [.pre-commit-config.yaml](.pre-commit-config.yaml)\n1. Better to [open a discussion](https://github.com/xinntao/Real-ESRGAN/discussions) before large changes.\n    1. Welcome to discuss :sunglasses:. I will try my best to join the discussion.\n\n## TODO List\n\n:zero: The most straightforward way of improving model performance is to fine-tune on some specific datasets.\n\nHere are some TODOs:\n\n- [ ] optimize for human faces\n- [ ] optimize for texts\n- [ ] support controllable restoration strength\n\n:one: There are also [several issues](https://github.com/xinntao/Real-ESRGAN/issues) that require helpers to improve. If you can help, please let me know :smile:\n"
  },
  {
    "path": "docs/FAQ.md",
    "content": "# FAQ\n\n1. **Q: How to select models?**<br>\nA: Please refer to [docs/model_zoo.md](docs/model_zoo.md)\n\n1. **Q: Can `face_enhance` be used for anime images/animation videos?**<br>\nA: No, it can only be used for real faces. It is recommended not to use this option for anime images/animation videos to save GPU memory.\n\n1. **Q: Error \"slow_conv2d_cpu\" not implemented for 'Half'**<br>\nA: In order to save GPU memory consumption and speed up inference, Real-ESRGAN uses half precision (fp16) during inference by default. However, some operators for half inference are not implemented in CPU mode. You need to add **`--fp32` option** for the commands. For example, `python inference_realesrgan.py -n RealESRGAN_x4plus.pth -i inputs --fp32`.\n"
  },
  {
    "path": "docs/Training.md",
    "content": "# :computer: How to Train/Finetune Real-ESRGAN\n\n- [Train Real-ESRGAN](#train-real-esrgan)\n  - [Overview](#overview)\n  - [Dataset Preparation](#dataset-preparation)\n  - [Train Real-ESRNet](#Train-Real-ESRNet)\n  - [Train Real-ESRGAN](#Train-Real-ESRGAN)\n- [Finetune Real-ESRGAN on your own dataset](#Finetune-Real-ESRGAN-on-your-own-dataset)\n  - [Generate degraded images on the fly](#Generate-degraded-images-on-the-fly)\n  - [Use paired training data](#use-your-own-paired-data)\n\n[English](Training.md) **|** [简体中文](Training_CN.md)\n\n## Train Real-ESRGAN\n\n### Overview\n\nThe training has been divided into two stages. These two stages have the same data synthesis process and training pipeline, except for the loss functions. Specifically,\n\n1. We first train Real-ESRNet with L1 loss from the pre-trained model ESRGAN.\n1. We then use the trained Real-ESRNet model as an initialization of the generator, and train the Real-ESRGAN with a combination of L1 loss, perceptual loss and GAN loss.\n\n### Dataset Preparation\n\nWe use DF2K (DIV2K and Flickr2K) + OST datasets for our training. Only HR images are required. <br>\nYou can download from :\n\n1. DIV2K: http://data.vision.ee.ethz.ch/cvl/DIV2K/DIV2K_train_HR.zip\n2. Flickr2K: https://cv.snu.ac.kr/research/EDSR/Flickr2K.tar\n3. OST: https://openmmlab.oss-cn-hangzhou.aliyuncs.com/datasets/OST_dataset.zip\n\nHere are steps for data preparation.\n\n#### Step 1: [Optional] Generate multi-scale images\n\nFor the DF2K dataset, we use a multi-scale strategy, *i.e.*, we downsample HR images to obtain several Ground-Truth images with different scales. <br>\nYou can use the [scripts/generate_multiscale_DF2K.py](scripts/generate_multiscale_DF2K.py) script to generate multi-scale images. <br>\nNote that this step can be omitted if you just want to have a fast try.\n\n```bash\npython scripts/generate_multiscale_DF2K.py --input datasets/DF2K/DF2K_HR --output datasets/DF2K/DF2K_multiscale\n```\n\n#### Step 2: [Optional] Crop to sub-images\n\nWe then crop DF2K images into sub-images for faster IO and processing.<br>\nThis step is optional if your IO is enough or your disk space is limited.\n\nYou can use the [scripts/extract_subimages.py](scripts/extract_subimages.py) script. Here is the example:\n\n```bash\n python scripts/extract_subimages.py --input datasets/DF2K/DF2K_multiscale --output datasets/DF2K/DF2K_multiscale_sub --crop_size 400 --step 200\n```\n\n#### Step 3: Prepare a txt for meta information\n\nYou need to prepare a txt file containing the image paths. The following are some examples in `meta_info_DF2Kmultiscale+OST_sub.txt` (As different users may have different sub-images partitions, this file is not suitable for your purpose and you need to prepare your own txt file):\n\n```txt\nDF2K_HR_sub/000001_s001.png\nDF2K_HR_sub/000001_s002.png\nDF2K_HR_sub/000001_s003.png\n...\n```\n\nYou can use the [scripts/generate_meta_info.py](scripts/generate_meta_info.py) script to generate the txt file. <br>\nYou can merge several folders into one meta_info txt. Here is the example:\n\n```bash\n python scripts/generate_meta_info.py --input datasets/DF2K/DF2K_HR datasets/DF2K/DF2K_multiscale --root datasets/DF2K datasets/DF2K --meta_info datasets/DF2K/meta_info/meta_info_DF2Kmultiscale.txt\n```\n\n### Train Real-ESRNet\n\n1. Download pre-trained model [ESRGAN](https://github.com/xinntao/Real-ESRGAN/releases/download/v0.1.1/ESRGAN_SRx4_DF2KOST_official-ff704c30.pth) into `experiments/pretrained_models`.\n    ```bash\n    wget https://github.com/xinntao/Real-ESRGAN/releases/download/v0.1.1/ESRGAN_SRx4_DF2KOST_official-ff704c30.pth -P experiments/pretrained_models\n    ```\n1. Modify the content in the option file `options/train_realesrnet_x4plus.yml` accordingly:\n    ```yml\n    train:\n        name: DF2K+OST\n        type: RealESRGANDataset\n        dataroot_gt: datasets/DF2K  # modify to the root path of your folder\n        meta_info: realesrgan/meta_info/meta_info_DF2Kmultiscale+OST_sub.txt  # modify to your own generate meta info txt\n        io_backend:\n            type: disk\n    ```\n1. If you want to perform validation during training, uncomment those lines and modify accordingly:\n    ```yml\n      # Uncomment these for validation\n      # val:\n      #   name: validation\n      #   type: PairedImageDataset\n      #   dataroot_gt: path_to_gt\n      #   dataroot_lq: path_to_lq\n      #   io_backend:\n      #     type: disk\n\n    ...\n\n      # Uncomment these for validation\n      # validation settings\n      # val:\n      #   val_freq: !!float 5e3\n      #   save_img: True\n\n      #   metrics:\n      #     psnr: # metric name, can be arbitrary\n      #       type: calculate_psnr\n      #       crop_border: 4\n      #       test_y_channel: false\n    ```\n1. Before the formal training, you may run in the `--debug` mode to see whether everything is OK. We use four GPUs for training:\n    ```bash\n    CUDA_VISIBLE_DEVICES=0,1,2,3 \\\n    python -m torch.distributed.launch --nproc_per_node=4 --master_port=4321 realesrgan/train.py -opt options/train_realesrnet_x4plus.yml --launcher pytorch --debug\n    ```\n\n    Train with **a single GPU** in the *debug* mode:\n    ```bash\n    python realesrgan/train.py -opt options/train_realesrnet_x4plus.yml --debug\n    ```\n1. The formal training. We use four GPUs for training. We use the `--auto_resume` argument to automatically resume the training if necessary.\n    ```bash\n    CUDA_VISIBLE_DEVICES=0,1,2,3 \\\n    python -m torch.distributed.launch --nproc_per_node=4 --master_port=4321 realesrgan/train.py -opt options/train_realesrnet_x4plus.yml --launcher pytorch --auto_resume\n    ```\n\n    Train with **a single GPU**:\n    ```bash\n    python realesrgan/train.py -opt options/train_realesrnet_x4plus.yml --auto_resume\n    ```\n\n### Train Real-ESRGAN\n\n1. After the training of Real-ESRNet, you now have the file `experiments/train_RealESRNetx4plus_1000k_B12G4_fromESRGAN/model/net_g_1000000.pth`. If you need to specify the pre-trained path to other files, modify the `pretrain_network_g` value in the option file `train_realesrgan_x4plus.yml`.\n1. Modify the option file `train_realesrgan_x4plus.yml` accordingly. Most modifications are similar to those listed above.\n1. Before the formal training, you may run in the `--debug` mode to see whether everything is OK. We use four GPUs for training:\n    ```bash\n    CUDA_VISIBLE_DEVICES=0,1,2,3 \\\n    python -m torch.distributed.launch --nproc_per_node=4 --master_port=4321 realesrgan/train.py -opt options/train_realesrgan_x4plus.yml --launcher pytorch --debug\n    ```\n\n    Train with **a single GPU** in the *debug* mode:\n    ```bash\n    python realesrgan/train.py -opt options/train_realesrgan_x4plus.yml --debug\n    ```\n1. The formal training. We use four GPUs for training. We use the `--auto_resume` argument to automatically resume the training if necessary.\n    ```bash\n    CUDA_VISIBLE_DEVICES=0,1,2,3 \\\n    python -m torch.distributed.launch --nproc_per_node=4 --master_port=4321 realesrgan/train.py -opt options/train_realesrgan_x4plus.yml --launcher pytorch --auto_resume\n    ```\n\n    Train with **a single GPU**:\n    ```bash\n    python realesrgan/train.py -opt options/train_realesrgan_x4plus.yml --auto_resume\n    ```\n\n## Finetune Real-ESRGAN on your own dataset\n\nYou can finetune Real-ESRGAN on your own dataset. Typically, the fine-tuning process can be divided into two cases:\n\n1. [Generate degraded images on the fly](#Generate-degraded-images-on-the-fly)\n1. [Use your own **paired** data](#Use-paired-training-data)\n\n### Generate degraded images on the fly\n\nOnly high-resolution images are required. The low-quality images are generated with the degradation process described in Real-ESRGAN during training.\n\n**1. Prepare dataset**\n\nSee [this section](#dataset-preparation) for more details.\n\n**2. Download pre-trained models**\n\nDownload pre-trained models into `experiments/pretrained_models`.\n\n- *RealESRGAN_x4plus.pth*:\n    ```bash\n    wget https://github.com/xinntao/Real-ESRGAN/releases/download/v0.1.0/RealESRGAN_x4plus.pth -P experiments/pretrained_models\n    ```\n\n- *RealESRGAN_x4plus_netD.pth*:\n    ```bash\n    wget https://github.com/xinntao/Real-ESRGAN/releases/download/v0.2.2.3/RealESRGAN_x4plus_netD.pth -P experiments/pretrained_models\n    ```\n\n**3. Finetune**\n\nModify [options/finetune_realesrgan_x4plus.yml](options/finetune_realesrgan_x4plus.yml) accordingly, especially the `datasets` part:\n\n```yml\ntrain:\n    name: DF2K+OST\n    type: RealESRGANDataset\n    dataroot_gt: datasets/DF2K  # modify to the root path of your folder\n    meta_info: realesrgan/meta_info/meta_info_DF2Kmultiscale+OST_sub.txt  # modify to your own generate meta info txt\n    io_backend:\n        type: disk\n```\n\nWe use four GPUs for training. We use the `--auto_resume` argument to automatically resume the training if necessary.\n\n```bash\nCUDA_VISIBLE_DEVICES=0,1,2,3 \\\npython -m torch.distributed.launch --nproc_per_node=4 --master_port=4321 realesrgan/train.py -opt options/finetune_realesrgan_x4plus.yml --launcher pytorch --auto_resume\n```\n\nFinetune with **a single GPU**:\n```bash\npython realesrgan/train.py -opt options/finetune_realesrgan_x4plus.yml --auto_resume\n```\n\n### Use your own paired data\n\nYou can also finetune RealESRGAN with your own paired data. It is more similar to fine-tuning ESRGAN.\n\n**1. Prepare dataset**\n\nAssume that you already have two folders:\n\n- **gt folder** (Ground-truth, high-resolution images): *datasets/DF2K/DIV2K_train_HR_sub*\n- **lq folder** (Low quality, low-resolution images): *datasets/DF2K/DIV2K_train_LR_bicubic_X4_sub*\n\nThen, you can prepare the meta_info txt file using the script [scripts/generate_meta_info_pairdata.py](scripts/generate_meta_info_pairdata.py):\n\n```bash\npython scripts/generate_meta_info_pairdata.py --input datasets/DF2K/DIV2K_train_HR_sub datasets/DF2K/DIV2K_train_LR_bicubic_X4_sub --meta_info datasets/DF2K/meta_info/meta_info_DIV2K_sub_pair.txt\n```\n\n**2. Download pre-trained models**\n\nDownload pre-trained models into `experiments/pretrained_models`.\n\n- *RealESRGAN_x4plus.pth*\n    ```bash\n    wget https://github.com/xinntao/Real-ESRGAN/releases/download/v0.1.0/RealESRGAN_x4plus.pth -P experiments/pretrained_models\n    ```\n\n- *RealESRGAN_x4plus_netD.pth*\n    ```bash\n    wget https://github.com/xinntao/Real-ESRGAN/releases/download/v0.2.2.3/RealESRGAN_x4plus_netD.pth -P experiments/pretrained_models\n    ```\n\n**3. Finetune**\n\nModify [options/finetune_realesrgan_x4plus_pairdata.yml](options/finetune_realesrgan_x4plus_pairdata.yml) accordingly, especially the `datasets` part:\n\n```yml\ntrain:\n    name: DIV2K\n    type: RealESRGANPairedDataset\n    dataroot_gt: datasets/DF2K  # modify to the root path of your folder\n    dataroot_lq: datasets/DF2K  # modify to the root path of your folder\n    meta_info: datasets/DF2K/meta_info/meta_info_DIV2K_sub_pair.txt  # modify to your own generate meta info txt\n    io_backend:\n        type: disk\n```\n\nWe use four GPUs for training. We use the `--auto_resume` argument to automatically resume the training if necessary.\n\n```bash\nCUDA_VISIBLE_DEVICES=0,1,2,3 \\\npython -m torch.distributed.launch --nproc_per_node=4 --master_port=4321 realesrgan/train.py -opt options/finetune_realesrgan_x4plus_pairdata.yml --launcher pytorch --auto_resume\n```\n\nFinetune with **a single GPU**:\n```bash\npython realesrgan/train.py -opt options/finetune_realesrgan_x4plus_pairdata.yml --auto_resume\n```\n"
  },
  {
    "path": "docs/Training_CN.md",
    "content": "# :computer: 如何训练/微调 Real-ESRGAN\n\n- [训练 Real-ESRGAN](#训练-real-esrgan)\n  - [概述](#概述)\n  - [准备数据集](#准备数据集)\n  - [训练 Real-ESRNet 模型](#训练-real-esrnet-模型)\n  - [训练 Real-ESRGAN 模型](#训练-real-esrgan-模型)\n- [用自己的数据集微调 Real-ESRGAN](#用自己的数据集微调-real-esrgan)\n  - [动态生成降级图像](#动态生成降级图像)\n  - [使用已配对的数据](#使用已配对的数据)\n\n[English](Training.md) **|** [简体中文](Training_CN.md)\n\n## 训练 Real-ESRGAN\n\n### 概述\n\n训练分为两个步骤。除了 loss 函数外，这两个步骤拥有相同数据合成以及训练的一条龙流程。具体点说：\n\n1. 首先使用 L1 loss 训练 Real-ESRNet 模型，其中 L1 loss 来自预先训练的 ESRGAN 模型。\n\n2. 然后我们将 Real-ESRNet 模型作为生成器初始化，结合L1 loss、感知 loss、GAN loss 三者的参数对 Real-ESRGAN 进行训练。\n\n### 准备数据集\n\n我们使用 DF2K ( DIV2K 和 Flickr2K ) + OST 数据集进行训练。只需要HR图像！<br>\n下面是网站链接:\n1. DIV2K: http://data.vision.ee.ethz.ch/cvl/DIV2K/DIV2K_train_HR.zip\n2. Flickr2K: https://cv.snu.ac.kr/research/EDSR/Flickr2K.tar\n3. OST: https://openmmlab.oss-cn-hangzhou.aliyuncs.com/datasets/OST_dataset.zip\n\n以下是数据的准备步骤。\n\n#### 第1步：【可选】生成多尺寸图片\n\n针对 DF2K 数据集，我们使用多尺寸缩放策略，*换言之*，我们对 HR 图像进行下采样，就能获得多尺寸的标准参考（Ground-Truth）图像。 <br>\n您可以使用这个 [scripts/generate_multiscale_DF2K.py](scripts/generate_multiscale_DF2K.py) 脚本快速生成多尺寸的图像。<br>\n注意：如果您只想简单试试，那么可以跳过此步骤。\n\n```bash\npython scripts/generate_multiscale_DF2K.py --input datasets/DF2K/DF2K_HR --output datasets/DF2K/DF2K_multiscale\n```\n\n#### 第2步：【可选】裁切为子图像\n\n我们可以将 DF2K 图像裁切为子图像，以加快 IO 和处理速度。<br>\n如果你的 IO 够好或储存空间有限，那么此步骤是可选的。<br>\n\n您可以使用脚本 [scripts/extract_subimages.py](scripts/extract_subimages.py)。这是使用示例:\n\n```bash\n python scripts/extract_subimages.py --input datasets/DF2K/DF2K_multiscale --output datasets/DF2K/DF2K_multiscale_sub --crop_size 400 --step 200\n```\n\n#### 第3步：准备元信息 txt\n\n您需要准备一个包含图像路径的 txt 文件。下面是 `meta_info_DF2Kmultiscale+OST_sub.txt` 中的部分展示（由于各个用户可能有截然不同的子图像划分，这个文件不适合你的需求，你得准备自己的 txt 文件)：\n\n```txt\nDF2K_HR_sub/000001_s001.png\nDF2K_HR_sub/000001_s002.png\nDF2K_HR_sub/000001_s003.png\n...\n```\n\n你可以使用该脚本 [scripts/generate_meta_info.py](scripts/generate_meta_info.py) 生成包含图像路径的 txt 文件。<br>\n你还可以合并多个文件夹的图像路径到一个元信息（meta_info）txt。这是使用示例:\n\n```bash\n python scripts/generate_meta_info.py --input datasets/DF2K/DF2K_HR, datasets/DF2K/DF2K_multiscale --root datasets/DF2K, datasets/DF2K --meta_info datasets/DF2K/meta_info/meta_info_DF2Kmultiscale.txt\n```\n\n### 训练 Real-ESRNet 模型\n\n1. 下载预先训练的模型 [ESRGAN](https://github.com/xinntao/Real-ESRGAN/releases/download/v0.1.1/ESRGAN_SRx4_DF2KOST_official-ff704c30.pth)，放到 `experiments/pretrained_models`目录下。\n    ```bash\n    wget https://github.com/xinntao/Real-ESRGAN/releases/download/v0.1.1/ESRGAN_SRx4_DF2KOST_official-ff704c30.pth -P experiments/pretrained_models\n    ```\n2. 相应地修改选项文件 `options/train_realesrnet_x4plus.yml` 中的内容：\n    ```yml\n    train:\n        name: DF2K+OST\n        type: RealESRGANDataset\n        dataroot_gt: datasets/DF2K  # 修改为你的数据集文件夹根目录\n        meta_info: realesrgan/meta_info/meta_info_DF2Kmultiscale+OST_sub.txt  # 修改为你自己生成的元信息txt\n        io_backend:\n            type: disk\n    ```\n3. 如果你想在训练过程中执行验证，就取消注释这些内容并进行相应的修改：\n    ```yml\n      # 取消注释这些以进行验证\n      # val:\n      #   name: validation\n      #   type: PairedImageDataset\n      #   dataroot_gt: path_to_gt\n      #   dataroot_lq: path_to_lq\n      #   io_backend:\n      #     type: disk\n\n    ...\n\n      # 取消注释这些以进行验证\n      # 验证设置\n      # val:\n      #   val_freq: !!float 5e3\n      #   save_img: True\n\n      #   metrics:\n      #     psnr: # 指标名称，可以是任意的\n      #       type: calculate_psnr\n      #       crop_border: 4\n      #       test_y_channel: false\n    ```\n4. 正式训练之前，你可以用 `--debug` 模式检查是否正常运行。我们用了4个GPU进行训练：\n    ```bash\n    CUDA_VISIBLE_DEVICES=0,1,2,3 \\\n    python -m torch.distributed.launch --nproc_per_node=4 --master_port=4321 realesrgan/train.py -opt options/train_realesrnet_x4plus.yml --launcher pytorch --debug\n    ```\n\n    用 **1个GPU** 训练的 debug 模式示例:\n    ```bash\n    python realesrgan/train.py -opt options/train_realesrnet_x4plus.yml --debug\n    ```\n5. 正式训练开始。我们用了4个GPU进行训练。还可以使用参数 `--auto_resume` 在必要时自动恢复训练。\n    ```bash\n    CUDA_VISIBLE_DEVICES=0,1,2,3 \\\n    python -m torch.distributed.launch --nproc_per_node=4 --master_port=4321 realesrgan/train.py -opt options/train_realesrnet_x4plus.yml --launcher pytorch --auto_resume\n    ```\n\n    用 **1个GPU** 训练：\n    ```bash\n    python realesrgan/train.py -opt options/train_realesrnet_x4plus.yml --auto_resume\n    ```\n\n### 训练 Real-ESRGAN 模型\n\n1. 训练 Real-ESRNet 模型后，您得到了这个 `experiments/train_RealESRNetx4plus_1000k_B12G4_fromESRGAN/model/net_g_1000000.pth` 文件。如果需要指定预训练路径到其他文件，请修改选项文件 `train_realesrgan_x4plus.yml` 中 `pretrain_network_g` 的值。\n1. 修改选项文件 `train_realesrgan_x4plus.yml` 的内容。大多数修改与上节提到的类似。\n1. 正式训练之前，你可以以 `--debug` 模式检查是否正常运行。我们使用了4个GPU进行训练：\n    ```bash\n    CUDA_VISIBLE_DEVICES=0,1,2,3 \\\n    python -m torch.distributed.launch --nproc_per_node=4 --master_port=4321 realesrgan/train.py -opt options/train_realesrgan_x4plus.yml --launcher pytorch --debug\n    ```\n\n    用 **1个GPU** 训练的 debug 模式示例:\n    ```bash\n    python realesrgan/train.py -opt options/train_realesrgan_x4plus.yml --debug\n    ```\n1. 正式训练开始。我们使用4个GPU进行训练。还可以使用参数 `--auto_resume` 在必要时自动恢复训练。\n    ```bash\n    CUDA_VISIBLE_DEVICES=0,1,2,3 \\\n    python -m torch.distributed.launch --nproc_per_node=4 --master_port=4321 realesrgan/train.py -opt options/train_realesrgan_x4plus.yml --launcher pytorch --auto_resume\n    ```\n\n    用 **1个GPU** 训练：\n    ```bash\n    python realesrgan/train.py -opt options/train_realesrgan_x4plus.yml --auto_resume\n    ```\n\n## 用自己的数据集微调 Real-ESRGAN\n\n你可以用自己的数据集微调 Real-ESRGAN。一般地，微调（Fine-Tune）程序可以分为两种类型:\n\n1. [动态生成降级图像](#动态生成降级图像)\n2. [使用**已配对**的数据](#使用已配对的数据)\n\n### 动态生成降级图像\n\n只需要高分辨率图像。在训练过程中，使用 Real-ESRGAN 描述的降级模型生成低质量图像。\n\n**1. 准备数据集**\n\n完整信息请参见[本节](#准备数据集)。\n\n**2. 下载预训练模型**\n\n下载预先训练的模型到 `experiments/pretrained_models` 目录下。\n\n- *RealESRGAN_x4plus.pth*:\n    ```bash\n    wget https://github.com/xinntao/Real-ESRGAN/releases/download/v0.1.0/RealESRGAN_x4plus.pth -P experiments/pretrained_models\n    ```\n\n- *RealESRGAN_x4plus_netD.pth*:\n    ```bash\n    wget https://github.com/xinntao/Real-ESRGAN/releases/download/v0.2.2.3/RealESRGAN_x4plus_netD.pth -P experiments/pretrained_models\n    ```\n\n**3. 微调**\n\n修改选项文件 [options/finetune_realesrgan_x4plus.yml](options/finetune_realesrgan_x4plus.yml) ，特别是 `datasets` 部分：\n\n```yml\ntrain:\n    name: DF2K+OST\n    type: RealESRGANDataset\n    dataroot_gt: datasets/DF2K   # 修改为你的数据集文件夹根目录\n    meta_info: realesrgan/meta_info/meta_info_DF2Kmultiscale+OST_sub.txt  # 修改为你自己生成的元信息txt\n    io_backend:\n        type: disk\n```\n\n我们使用4个GPU进行训练。还可以使用参数 `--auto_resume` 在必要时自动恢复训练。\n\n```bash\nCUDA_VISIBLE_DEVICES=0,1,2,3 \\\npython -m torch.distributed.launch --nproc_per_node=4 --master_port=4321 realesrgan/train.py -opt options/finetune_realesrgan_x4plus.yml --launcher pytorch --auto_resume\n```\n\n用 **1个GPU** 训练：\n```bash\npython realesrgan/train.py -opt options/finetune_realesrgan_x4plus.yml --auto_resume\n```\n\n### 使用已配对的数据\n\n你还可以用自己已经配对的数据微调 RealESRGAN。这个过程更类似于微调 ESRGAN。\n\n**1. 准备数据集**\n\n假设你已经有两个文件夹（folder）:\n\n- **gt folder**（标准参考，高分辨率图像）：*datasets/DF2K/DIV2K_train_HR_sub*\n- **lq folder**（低质量，低分辨率图像）：*datasets/DF2K/DIV2K_train_LR_bicubic_X4_sub*\n\n然后，您可以使用脚本 [scripts/generate_meta_info_pairdata.py](scripts/generate_meta_info_pairdata.py) 生成元信息（meta_info）txt 文件。\n\n```bash\npython scripts/generate_meta_info_pairdata.py --input datasets/DF2K/DIV2K_train_HR_sub datasets/DF2K/DIV2K_train_LR_bicubic_X4_sub --meta_info datasets/DF2K/meta_info/meta_info_DIV2K_sub_pair.txt\n```\n\n**2. 下载预训练模型**\n\n下载预先训练的模型到 `experiments/pretrained_models` 目录下。\n\n- *RealESRGAN_x4plus.pth*:\n    ```bash\n    wget https://github.com/xinntao/Real-ESRGAN/releases/download/v0.1.0/RealESRGAN_x4plus.pth -P experiments/pretrained_models\n    ```\n\n- *RealESRGAN_x4plus_netD.pth*:\n    ```bash\n    wget https://github.com/xinntao/Real-ESRGAN/releases/download/v0.2.2.3/RealESRGAN_x4plus_netD.pth -P experiments/pretrained_models\n    ```\n\n**3. 微调**\n\n修改选项文件 [options/finetune_realesrgan_x4plus_pairdata.yml](options/finetune_realesrgan_x4plus_pairdata.yml) ，特别是 `datasets` 部分：\n\n```yml\ntrain:\n    name: DIV2K\n    type: RealESRGANPairedDataset\n    dataroot_gt: datasets/DF2K  # 修改为你的 gt folder 文件夹根目录\n    dataroot_lq: datasets/DF2K  # 修改为你的 lq folder 文件夹根目录\n    meta_info: datasets/DF2K/meta_info/meta_info_DIV2K_sub_pair.txt  # 修改为你自己生成的元信息txt\n    io_backend:\n        type: disk\n```\n\n我们使用4个GPU进行训练。还可以使用参数 `--auto_resume` 在必要时自动恢复训练。\n\n```bash\nCUDA_VISIBLE_DEVICES=0,1,2,3 \\\npython -m torch.distributed.launch --nproc_per_node=4 --master_port=4321 realesrgan/train.py -opt options/finetune_realesrgan_x4plus_pairdata.yml --launcher pytorch --auto_resume\n```\n\n用 **1个GPU** 训练：\n```bash\npython realesrgan/train.py -opt options/finetune_realesrgan_x4plus_pairdata.yml --auto_resume\n```\n"
  },
  {
    "path": "docs/anime_comparisons.md",
    "content": "# Comparisons among different anime models\n\n[English](anime_comparisons.md) **|** [简体中文](anime_comparisons_CN.md)\n\n## Update News\n\n- 2022/04/24: Release **AnimeVideo-v3**. We have made the following improvements:\n  - **better naturalness**\n  - **Fewer artifacts**\n  - **more faithful to the original colors**\n  - **better texture restoration**\n  - **better background restoration**\n\n## Comparisons\n\nWe have compared our RealESRGAN-AnimeVideo-v3 with the following methods.\nOur RealESRGAN-AnimeVideo-v3 can achieve better results with faster inference speed.\n\n- [waifu2x](https://github.com/nihui/waifu2x-ncnn-vulkan) with the hyperparameters: `tile=0`, `noiselevel=2`\n- [Real-CUGAN](https://github.com/bilibili/ailab/tree/main/Real-CUGAN): we use the [20220227](https://github.com/bilibili/ailab/releases/tag/Real-CUGAN-add-faster-low-memory-mode) version, the hyperparameters are: `cache_mode=0`, `tile=0`, `alpha=1`.\n- our RealESRGAN-AnimeVideo-v3\n\n## Results\n\nYou may need to **zoom in** for comparing details, or **click the image** to see in the full size. Please note that the images\nin the table below are the resized and cropped patches from the original images, you can download the original inputs and outputs from [Google Drive](https://drive.google.com/drive/folders/1bc_Hje1Nqop9NDkUvci2VACSjL7HZMRp?usp=sharing) .\n\n**More natural results, better background restoration**\n| Input | waifu2x | Real-CUGAN | RealESRGAN<br>AnimeVideo-v3 |\n| :---: | :---:        |     :---:      |  :---:      |\n|![157083983-bec52c67-9a5e-4eed-afef-01fe6cd2af85_patch](https://user-images.githubusercontent.com/11482921/164452769-5d8cb4f8-1708-42d2-b941-f44a6f136feb.png) | ![](https://user-images.githubusercontent.com/11482921/164452767-c825cdec-f721-4ff1-aef1-fec41f146c4c.png) | ![](https://user-images.githubusercontent.com/11482921/164452755-3be50895-e3d4-432d-a7b9-9085c2a8e771.png) | ![](https://user-images.githubusercontent.com/11482921/164452771-be300656-379a-4323-a755-df8025a8c451.png) |\n|![a0010_patch](https://user-images.githubusercontent.com/11482921/164454047-22eeb493-3fa9-4142-9fc2-6f2a1c074cd5.png) | ![](https://user-images.githubusercontent.com/11482921/164454046-d5e79f8f-00a0-4b55-bc39-295d0d69747a.png) | ![](https://user-images.githubusercontent.com/11482921/164454040-87886b11-9d08-48bd-862f-0d4aed72eb19.png) | ![](https://user-images.githubusercontent.com/11482921/164454055-73dc9f02-286e-4d5c-8f70-c13742e08f42.png) |\n|![00000044_patch](https://user-images.githubusercontent.com/11482921/164451232-bacf64fc-e55a-44db-afbb-6b31ab0f8973.png) | ![](https://user-images.githubusercontent.com/11482921/164451318-f309b61a-75b8-4b74-b5f3-595725f1cf0b.png) | ![](https://user-images.githubusercontent.com/11482921/164451348-994f8a35-adbe-4a4b-9c61-feaa294af06a.png) | ![](https://user-images.githubusercontent.com/11482921/164451361-9b7d376e-6f75-4648-b752-542b44845d1c.png) |\n\n**Fewer artifacts, better detailed textures**\n| Input | waifu2x | Real-CUGAN | RealESRGAN<br>AnimeVideo-v3 |\n| :---: | :---:        |     :---:      |  :---:      |\n|![00000053_patch](https://user-images.githubusercontent.com/11482921/164448411-148a7e5c-cfcd-4504-8bc7-e318eb883bb6.png) | ![](https://user-images.githubusercontent.com/11482921/164448633-dfc15224-b6d2-4403-a3c9-4bb819979364.png) | ![](https://user-images.githubusercontent.com/11482921/164448771-0d359509-5293-4d4c-8e3c-86a2a314ea88.png) | ![](https://user-images.githubusercontent.com/11482921/164448848-1a4ff99e-075b-4458-9db7-2c89e8160aa0.png) |\n|![Disney_v4_22_018514_s2_patch](https://user-images.githubusercontent.com/11482921/164451898-83311cdf-bd3e-450f-b9f6-34d7fea3ab79.png) | ![](https://user-images.githubusercontent.com/11482921/164451894-6c56521c-6561-40d6-a3a5-8dde2c167b8a.png) | ![](https://user-images.githubusercontent.com/11482921/164451888-af9b47e3-39dc-4f3e-b0d7-d372d8191e2a.png) | ![](https://user-images.githubusercontent.com/11482921/164451901-31ca4dd4-9847-4baa-8cde-ad50f4053dcf.png) |\n|![Japan_v2_0_007261_s2_patch](https://user-images.githubusercontent.com/11482921/164454578-73c77392-77de-49c5-b03c-c36631723192.png) | ![](https://user-images.githubusercontent.com/11482921/164454574-b1ede5f0-4520-4eaa-8f59-086751a34e62.png) | ![](https://user-images.githubusercontent.com/11482921/164454567-4cb3fdd8-6a2d-4016-85b2-a305a8ff80e4.png) | ![](https://user-images.githubusercontent.com/11482921/164454583-7f243f20-eca3-4500-ac43-eb058a4a101a.png) |\n|![huluxiongdi_2_patch](https://user-images.githubusercontent.com/11482921/164453482-0726c842-337e-40ec-bf6c-f902ee956a8b.png) | ![](https://user-images.githubusercontent.com/11482921/164453480-71d5e091-5bfa-4c77-9c57-4e37f66ca0a3.png) | ![](https://user-images.githubusercontent.com/11482921/164453468-c295d3c9-3661-45f0-9ecd-406a1877f76e.png) | ![](https://user-images.githubusercontent.com/11482921/164453486-3091887c-587c-450e-b6fe-905cb518d57e.png) |\n\n**Other better results**\n| Input | waifu2x | Real-CUGAN | RealESRGAN<br>AnimeVideo-v3 |\n| :---: | :---:        |     :---:      |  :---:      |\n|![Japan_v2_1_128525_s1_patch](https://user-images.githubusercontent.com/11482921/164454933-67697f7c-b6ef-47dc-bfca-822a78af8acf.png) | ![](https://user-images.githubusercontent.com/11482921/164454931-9450de7c-f0b3-4638-9c1e-0668e0c41ef0.png) | ![](https://user-images.githubusercontent.com/11482921/164454926-ed746976-786d-41c5-8a83-7693cd774c3a.png) | ![](https://user-images.githubusercontent.com/11482921/164454936-8abdf0f0-fb30-40eb-8281-3b46c0bcb9ae.png) |\n|![tianshuqitan_2_patch](https://user-images.githubusercontent.com/11482921/164456948-807c1476-90b6-4507-81da-cb986d01600c.png) | ![](https://user-images.githubusercontent.com/11482921/164456943-25e89de9-d7e5-4f61-a2e1-96786af6ae9e.png) | ![](https://user-images.githubusercontent.com/11482921/164456954-b468c447-59f5-4594-9693-3683e44ba3e6.png) | ![](https://user-images.githubusercontent.com/11482921/164456957-640f910c-3b04-407c-ac20-044d72e19735.png) |\n|![00000051_patch](https://user-images.githubusercontent.com/11482921/164456044-e9a6b3fa-b24e-4eb7-acf9-1f7746551b1e.png) ![00000051_patch](https://user-images.githubusercontent.com/11482921/164456421-b67245b0-767d-4250-9105-80bbe507ecfc.png) | ![](https://user-images.githubusercontent.com/11482921/164456040-85763cf2-cb28-4ba3-abb6-1dbb48c55713.png) ![](https://user-images.githubusercontent.com/11482921/164456419-59cf342e-bc1e-4044-868c-e1090abad313.png) | ![](https://user-images.githubusercontent.com/11482921/164456031-4244bb7b-8649-4e01-86f4-40c2099c5afd.png) ![](https://user-images.githubusercontent.com/11482921/164456411-b6afcbe9-c054-448d-a6df-96d3ba3047f8.png) | ![](https://user-images.githubusercontent.com/11482921/164456035-12e270be-fd52-46d4-b18a-3d3b680731fe.png) ![](https://user-images.githubusercontent.com/11482921/164456417-dcaa8b62-f497-427d-b2d2-f390f1200fb9.png) |\n|![00000099_patch](https://user-images.githubusercontent.com/11482921/164455312-6411b6e1-5823-4131-a4b0-a6be8a9ae89f.png) | ![](https://user-images.githubusercontent.com/11482921/164455310-f2b99646-3a22-47a4-805b-dc451ac86ddb.png) | ![](https://user-images.githubusercontent.com/11482921/164455294-35471b42-2826-4451-b7ec-6de01344954c.png) | ![](https://user-images.githubusercontent.com/11482921/164455305-fa4c9758-564a-4081-8b4e-f11057a0404d.png) |\n|![00000016_patch](https://user-images.githubusercontent.com/11482921/164455672-447353c9-2da2-4fcb-ba4a-7dd6b94c19c1.png) | ![](https://user-images.githubusercontent.com/11482921/164455669-df384631-baaa-42f8-9150-40f658471558.png) | ![](https://user-images.githubusercontent.com/11482921/164455657-68006bf0-138d-4981-aaca-8aa927d2f78a.png) | ![](https://user-images.githubusercontent.com/11482921/164455664-0342b93e-a62a-4b36-a90e-7118f3f1e45d.png) |\n\n## Inference Speed\n\n### PyTorch\n\nNote that we only report the **model** time, and ignore the IO time.\n\n| GPU | Input Resolution | waifu2x | Real-CUGAN | RealESRGAN-AnimeVideo-v3\n| :---: | :---:         |  :---:        |     :---:      |  :---:      |\n| V100 | 1921 x 1080 | - | 3.4 fps | **10.0** fps |\n| V100 | 1280 x 720 | - | 7.2 fps | **22.6** fps |\n| V100 | 640 x 480 | - | 24.4 fps | **65.9** fps |\n\n### ncnn\n\n- [ ] TODO\n"
  },
  {
    "path": "docs/anime_comparisons_CN.md",
    "content": "# 动漫视频模型比较\n\n[English](anime_comparisons.md) **|** [简体中文](anime_comparisons_CN.md)\n\n## 更新\n\n- 2022/04/24: 发布 **AnimeVideo-v3**. 主要做了以下更新：\n  - **更自然**\n  - **更少瑕疵**\n  - **颜色保持得更好**\n  - **更好的纹理恢复**\n  - **虚化背景处理**\n\n## 比较\n\n我们将 RealESRGAN-AnimeVideo-v3 与以下方法进行了比较。我们的 RealESRGAN-AnimeVideo-v3 可以以更快的推理速度获得更好的结果。\n\n- [waifu2x](https://github.com/nihui/waifu2x-ncnn-vulkan). 超参数: `tile=0`, `noiselevel=2`\n- [Real-CUGAN](https://github.com/bilibili/ailab/tree/main/Real-CUGAN): 我们使用了[20220227](https://github.com/bilibili/ailab/releases/tag/Real-CUGAN-add-faster-low-memory-mode)版本, 超参: `cache_mode=0`, `tile=0`, `alpha=1`.\n- 我们的 RealESRGAN-AnimeVideo-v3\n\n## 结果\n\n您可能需要**放大**以比较详细信息, 或者**单击图像**以查看完整尺寸。 请注意下面表格的图片是从原图里裁剪patch并且resize后的结果，您可以从\n[Google Drive](https://drive.google.com/drive/folders/1bc_Hje1Nqop9NDkUvci2VACSjL7HZMRp?usp=sharing) 里下载原始的输入和输出。\n\n**更自然的结果，更好的虚化背景恢复**\n\n| 输入 | waifu2x | Real-CUGAN | RealESRGAN<br>AnimeVideo-v3 |\n| :---: | :---:        |     :---:      |  :---:      |\n|![157083983-bec52c67-9a5e-4eed-afef-01fe6cd2af85_patch](https://user-images.githubusercontent.com/11482921/164452769-5d8cb4f8-1708-42d2-b941-f44a6f136feb.png) | ![](https://user-images.githubusercontent.com/11482921/164452767-c825cdec-f721-4ff1-aef1-fec41f146c4c.png) | ![](https://user-images.githubusercontent.com/11482921/164452755-3be50895-e3d4-432d-a7b9-9085c2a8e771.png) | ![](https://user-images.githubusercontent.com/11482921/164452771-be300656-379a-4323-a755-df8025a8c451.png) |\n|![a0010_patch](https://user-images.githubusercontent.com/11482921/164454047-22eeb493-3fa9-4142-9fc2-6f2a1c074cd5.png) | ![](https://user-images.githubusercontent.com/11482921/164454046-d5e79f8f-00a0-4b55-bc39-295d0d69747a.png) | ![](https://user-images.githubusercontent.com/11482921/164454040-87886b11-9d08-48bd-862f-0d4aed72eb19.png) | ![](https://user-images.githubusercontent.com/11482921/164454055-73dc9f02-286e-4d5c-8f70-c13742e08f42.png) |\n|![00000044_patch](https://user-images.githubusercontent.com/11482921/164451232-bacf64fc-e55a-44db-afbb-6b31ab0f8973.png) | ![](https://user-images.githubusercontent.com/11482921/164451318-f309b61a-75b8-4b74-b5f3-595725f1cf0b.png) | ![](https://user-images.githubusercontent.com/11482921/164451348-994f8a35-adbe-4a4b-9c61-feaa294af06a.png) | ![](https://user-images.githubusercontent.com/11482921/164451361-9b7d376e-6f75-4648-b752-542b44845d1c.png) |\n\n**更少瑕疵，更好的细节纹理**\n\n| 输入 | waifu2x | Real-CUGAN | RealESRGAN<br>AnimeVideo-v3 |\n| :---: | :---:        |     :---:      |  :---:      |\n|![00000053_patch](https://user-images.githubusercontent.com/11482921/164448411-148a7e5c-cfcd-4504-8bc7-e318eb883bb6.png) | ![](https://user-images.githubusercontent.com/11482921/164448633-dfc15224-b6d2-4403-a3c9-4bb819979364.png) | ![](https://user-images.githubusercontent.com/11482921/164448771-0d359509-5293-4d4c-8e3c-86a2a314ea88.png) | ![](https://user-images.githubusercontent.com/11482921/164448848-1a4ff99e-075b-4458-9db7-2c89e8160aa0.png) |\n|![Disney_v4_22_018514_s2_patch](https://user-images.githubusercontent.com/11482921/164451898-83311cdf-bd3e-450f-b9f6-34d7fea3ab79.png) | ![](https://user-images.githubusercontent.com/11482921/164451894-6c56521c-6561-40d6-a3a5-8dde2c167b8a.png) | ![](https://user-images.githubusercontent.com/11482921/164451888-af9b47e3-39dc-4f3e-b0d7-d372d8191e2a.png) | ![](https://user-images.githubusercontent.com/11482921/164451901-31ca4dd4-9847-4baa-8cde-ad50f4053dcf.png) |\n|![Japan_v2_0_007261_s2_patch](https://user-images.githubusercontent.com/11482921/164454578-73c77392-77de-49c5-b03c-c36631723192.png) | ![](https://user-images.githubusercontent.com/11482921/164454574-b1ede5f0-4520-4eaa-8f59-086751a34e62.png) | ![](https://user-images.githubusercontent.com/11482921/164454567-4cb3fdd8-6a2d-4016-85b2-a305a8ff80e4.png) | ![](https://user-images.githubusercontent.com/11482921/164454583-7f243f20-eca3-4500-ac43-eb058a4a101a.png) |\n|![huluxiongdi_2_patch](https://user-images.githubusercontent.com/11482921/164453482-0726c842-337e-40ec-bf6c-f902ee956a8b.png) | ![](https://user-images.githubusercontent.com/11482921/164453480-71d5e091-5bfa-4c77-9c57-4e37f66ca0a3.png) | ![](https://user-images.githubusercontent.com/11482921/164453468-c295d3c9-3661-45f0-9ecd-406a1877f76e.png) | ![](https://user-images.githubusercontent.com/11482921/164453486-3091887c-587c-450e-b6fe-905cb518d57e.png) |\n\n**其他更好的结果**\n\n| 输入 | waifu2x | Real-CUGAN | RealESRGAN<br>AnimeVideo-v3 |\n| :---: | :---:        |     :---:      |  :---:      |\n|![Japan_v2_1_128525_s1_patch](https://user-images.githubusercontent.com/11482921/164454933-67697f7c-b6ef-47dc-bfca-822a78af8acf.png) | ![](https://user-images.githubusercontent.com/11482921/164454931-9450de7c-f0b3-4638-9c1e-0668e0c41ef0.png) | ![](https://user-images.githubusercontent.com/11482921/164454926-ed746976-786d-41c5-8a83-7693cd774c3a.png) | ![](https://user-images.githubusercontent.com/11482921/164454936-8abdf0f0-fb30-40eb-8281-3b46c0bcb9ae.png) |\n|![tianshuqitan_2_patch](https://user-images.githubusercontent.com/11482921/164456948-807c1476-90b6-4507-81da-cb986d01600c.png) | ![](https://user-images.githubusercontent.com/11482921/164456943-25e89de9-d7e5-4f61-a2e1-96786af6ae9e.png) | ![](https://user-images.githubusercontent.com/11482921/164456954-b468c447-59f5-4594-9693-3683e44ba3e6.png) | ![](https://user-images.githubusercontent.com/11482921/164456957-640f910c-3b04-407c-ac20-044d72e19735.png) |\n|![00000051_patch](https://user-images.githubusercontent.com/11482921/164456044-e9a6b3fa-b24e-4eb7-acf9-1f7746551b1e.png) ![00000051_patch](https://user-images.githubusercontent.com/11482921/164456421-b67245b0-767d-4250-9105-80bbe507ecfc.png) | ![](https://user-images.githubusercontent.com/11482921/164456040-85763cf2-cb28-4ba3-abb6-1dbb48c55713.png) ![](https://user-images.githubusercontent.com/11482921/164456419-59cf342e-bc1e-4044-868c-e1090abad313.png) | ![](https://user-images.githubusercontent.com/11482921/164456031-4244bb7b-8649-4e01-86f4-40c2099c5afd.png) ![](https://user-images.githubusercontent.com/11482921/164456411-b6afcbe9-c054-448d-a6df-96d3ba3047f8.png) | ![](https://user-images.githubusercontent.com/11482921/164456035-12e270be-fd52-46d4-b18a-3d3b680731fe.png) ![](https://user-images.githubusercontent.com/11482921/164456417-dcaa8b62-f497-427d-b2d2-f390f1200fb9.png) |\n|![00000099_patch](https://user-images.githubusercontent.com/11482921/164455312-6411b6e1-5823-4131-a4b0-a6be8a9ae89f.png) | ![](https://user-images.githubusercontent.com/11482921/164455310-f2b99646-3a22-47a4-805b-dc451ac86ddb.png) | ![](https://user-images.githubusercontent.com/11482921/164455294-35471b42-2826-4451-b7ec-6de01344954c.png) | ![](https://user-images.githubusercontent.com/11482921/164455305-fa4c9758-564a-4081-8b4e-f11057a0404d.png) |\n|![00000016_patch](https://user-images.githubusercontent.com/11482921/164455672-447353c9-2da2-4fcb-ba4a-7dd6b94c19c1.png) | ![](https://user-images.githubusercontent.com/11482921/164455669-df384631-baaa-42f8-9150-40f658471558.png) | ![](https://user-images.githubusercontent.com/11482921/164455657-68006bf0-138d-4981-aaca-8aa927d2f78a.png) | ![](https://user-images.githubusercontent.com/11482921/164455664-0342b93e-a62a-4b36-a90e-7118f3f1e45d.png) |\n\n## 推理速度比较\n\n### PyTorch\n\n请注意，我们只报告了**模型推理**的时间, 而忽略了读写硬盘的时间.\n\n| GPU | 输入尺寸 | waifu2x | Real-CUGAN | RealESRGAN-AnimeVideo-v3\n| :---: | :---:         |  :---:        |     :---:      |  :---:      |\n| V100 | 1921 x 1080 | - | 3.4 fps | **10.0** fps |\n| V100 | 1280 x 720 | - | 7.2 fps | **22.6** fps |\n| V100 | 640 x 480 | - | 24.4 fps | **65.9** fps |\n\n### ncnn\n\n- [ ] TODO\n"
  },
  {
    "path": "docs/anime_model.md",
    "content": "# Anime Model\n\n:white_check_mark: We add [*RealESRGAN_x4plus_anime_6B.pth*](https://github.com/xinntao/Real-ESRGAN/releases/download/v0.2.2.4/RealESRGAN_x4plus_anime_6B.pth), which is optimized for **anime** images with much smaller model size.\n\n- [How to Use](#how-to-use)\n  - [PyTorch Inference](#pytorch-inference)\n  - [ncnn Executable File](#ncnn-executable-file)\n- [Comparisons with waifu2x](#comparisons-with-waifu2x)\n- [Comparisons with Sliding Bars](#comparisons-with-sliding-bars)\n\n<p align=\"center\">\n  <img src=\"https://raw.githubusercontent.com/xinntao/public-figures/master/Real-ESRGAN/cmp_realesrgan_anime_1.png\">\n</p>\n\nThe following is a video comparison with sliding bar. You may need to use the full-screen mode for better visual quality, as the original image is large; otherwise, you may encounter aliasing issue.\n\n<https://user-images.githubusercontent.com/17445847/131535127-613250d4-f754-4e20-9720-2f9608ad0675.mp4>\n\n## How to Use\n\n### PyTorch Inference\n\nPre-trained models: [RealESRGAN_x4plus_anime_6B](https://github.com/xinntao/Real-ESRGAN/releases/download/v0.2.2.4/RealESRGAN_x4plus_anime_6B.pth)\n\n```bash\n# download model\nwget https://github.com/xinntao/Real-ESRGAN/releases/download/v0.2.2.4/RealESRGAN_x4plus_anime_6B.pth -P weights\n# inference\npython inference_realesrgan.py -n RealESRGAN_x4plus_anime_6B -i inputs\n```\n\n### ncnn Executable File\n\nDownload the latest portable [Windows](https://github.com/xinntao/Real-ESRGAN/releases/download/v0.2.5.0/realesrgan-ncnn-vulkan-20220424-windows.zip) / [Linux](https://github.com/xinntao/Real-ESRGAN/releases/download/v0.2.5.0/realesrgan-ncnn-vulkan-20220424-ubuntu.zip) / [MacOS](https://github.com/xinntao/Real-ESRGAN/releases/download/v0.2.5.0/realesrgan-ncnn-vulkan-20220424-macos.zip) **executable files for Intel/AMD/Nvidia GPU**.\n\nTaking the Windows as example, run:\n\n```bash\n./realesrgan-ncnn-vulkan.exe -i input.jpg -o output.png -n realesrgan-x4plus-anime\n```\n\n## Comparisons with waifu2x\n\nWe compare Real-ESRGAN-anime with [waifu2x](https://github.com/nihui/waifu2x-ncnn-vulkan). We use the `-n 2 -s 4` for waifu2x.\n\n<p align=\"center\">\n  <img src=\"https://raw.githubusercontent.com/xinntao/public-figures/master/Real-ESRGAN/cmp_realesrgan_anime_1.png\">\n</p>\n<p align=\"center\">\n  <img src=\"https://raw.githubusercontent.com/xinntao/public-figures/master/Real-ESRGAN/cmp_realesrgan_anime_2.png\">\n</p>\n<p align=\"center\">\n  <img src=\"https://raw.githubusercontent.com/xinntao/public-figures/master/Real-ESRGAN/cmp_realesrgan_anime_3.png\">\n</p>\n<p align=\"center\">\n  <img src=\"https://raw.githubusercontent.com/xinntao/public-figures/master/Real-ESRGAN/cmp_realesrgan_anime_4.png\">\n</p>\n<p align=\"center\">\n  <img src=\"https://raw.githubusercontent.com/xinntao/public-figures/master/Real-ESRGAN/cmp_realesrgan_anime_5.png\">\n</p>\n\n## Comparisons with Sliding Bars\n\nThe following are video comparisons with sliding bar. You may need to use the full-screen mode for better visual quality, as the original image is large; otherwise, you may encounter aliasing issue.\n\n<https://user-images.githubusercontent.com/17445847/131536647-a2fbf896-b495-4a9f-b1dd-ca7bbc90101a.mp4>\n\n<https://user-images.githubusercontent.com/17445847/131536742-6d9d82b6-9765-4296-a15f-18f9aeaa5465.mp4>\n"
  },
  {
    "path": "docs/anime_video_model.md",
    "content": "# Anime Video Models\n\n:white_check_mark: We add small models that are optimized for anime videos :-)<br>\nMore comparisons can be found in [anime_comparisons.md](anime_comparisons.md)\n\n- [How to Use](#how-to-use)\n- [PyTorch Inference](#pytorch-inference)\n- [ncnn Executable File](#ncnn-executable-file)\n  - [Step 1: Use ffmpeg to extract frames from video](#step-1-use-ffmpeg-to-extract-frames-from-video)\n  - [Step 2: Inference with Real-ESRGAN executable file](#step-2-inference-with-real-esrgan-executable-file)\n  - [Step 3: Merge the enhanced frames back into a video](#step-3-merge-the-enhanced-frames-back-into-a-video)\n- [More Demos](#more-demos)\n\n| Models                                                                                                                             | Scale | Description                    |\n| ---------------------------------------------------------------------------------------------------------------------------------- | :---- | :----------------------------- |\n| [realesr-animevideov3](https://github.com/xinntao/Real-ESRGAN/releases/download/v0.2.5.0/realesr-animevideov3.pth) | X4 <sup>1</sup>   | Anime video model with XS size |\n\nNote: <br>\n<sup>1</sup> This model can also be used for X1, X2, X3.\n\n---\n\nThe following are some demos (best view in the full screen mode).\n\n<https://user-images.githubusercontent.com/17445847/145706977-98bc64a4-af27-481c-8abe-c475e15db7ff.MP4>\n\n<https://user-images.githubusercontent.com/17445847/145707055-6a4b79cb-3d9d-477f-8610-c6be43797133.MP4>\n\n<https://user-images.githubusercontent.com/17445847/145783523-f4553729-9f03-44a8-a7cc-782aadf67b50.MP4>\n\n## How to Use\n\n### PyTorch Inference\n\n```bash\n# download model\nwget https://github.com/xinntao/Real-ESRGAN/releases/download/v0.2.5.0/realesr-animevideov3.pth -P weights\n# single gpu and single process inference\nCUDA_VISIBLE_DEVICES=0 python inference_realesrgan_video.py -i inputs/video/onepiece_demo.mp4 -n realesr-animevideov3 -s 2 --suffix outx2\n# single gpu and multi process inference (you can use multi-processing to improve GPU utilization)\nCUDA_VISIBLE_DEVICES=0 python inference_realesrgan_video.py -i inputs/video/onepiece_demo.mp4 -n realesr-animevideov3 -s 2 --suffix outx2 --num_process_per_gpu 2\n# multi gpu and multi process inference\nCUDA_VISIBLE_DEVICES=0,1,2,3 python inference_realesrgan_video.py -i inputs/video/onepiece_demo.mp4 -n realesr-animevideov3 -s 2 --suffix outx2 --num_process_per_gpu 2\n```\n\n```console\nUsage:\n--num_process_per_gpu    The total number of process is num_gpu * num_process_per_gpu. The bottleneck of\n                         the program lies on the IO, so the GPUs are usually not fully utilized. To alleviate\n                         this issue, you can use multi-processing by setting this parameter. As long as it\n                         does not exceed the CUDA memory\n--extract_frame_first    If you encounter ffmpeg error when using multi-processing, you can turn this option on.\n```\n\n### NCNN Executable File\n\n#### Step 1: Use ffmpeg to extract frames from video\n\n```bash\nffmpeg -i onepiece_demo.mp4 -qscale:v 1 -qmin 1 -qmax 1 -vsync 0 tmp_frames/frame%08d.png\n```\n\n- Remember to create the folder `tmp_frames` ahead\n\n#### Step 2: Inference with Real-ESRGAN executable file\n\n1. Download the latest portable [Windows](https://github.com/xinntao/Real-ESRGAN/releases/download/v0.2.5.0/realesrgan-ncnn-vulkan-20220424-windows.zip) / [Linux](https://github.com/xinntao/Real-ESRGAN/releases/download/v0.2.5.0/realesrgan-ncnn-vulkan-20220424-ubuntu.zip) / [MacOS](https://github.com/xinntao/Real-ESRGAN/releases/download/v0.2.5.0/realesrgan-ncnn-vulkan-20220424-macos.zip) **executable files for Intel/AMD/Nvidia GPU**\n\n1. Taking the Windows as example, run:\n\n    ```bash\n    ./realesrgan-ncnn-vulkan.exe -i tmp_frames -o out_frames -n realesr-animevideov3 -s 2 -f jpg\n    ```\n\n    - Remember to create the folder `out_frames` ahead\n\n#### Step 3: Merge the enhanced frames back into a video\n\n1. First obtain fps from input videos by\n\n    ```bash\n    ffmpeg -i onepiece_demo.mp4\n    ```\n\n    ```console\n    Usage:\n    -i                   input video path\n    ```\n\n    You will get the output similar to the following screenshot.\n\n    <p align=\"center\">\n        <img src=\"https://user-images.githubusercontent.com/17445847/145710145-c4f3accf-b82f-4307-9f20-3803a2c73f57.png\">\n    </p>\n\n2. Merge frames\n\n    ```bash\n    ffmpeg -r 23.98 -i out_frames/frame%08d.jpg -c:v libx264 -r 23.98 -pix_fmt yuv420p output.mp4\n    ```\n\n    ```console\n    Usage:\n    -i                   input video path\n    -c:v                 video encoder (usually we use libx264)\n    -r                   fps, remember to modify it to meet your needs\n    -pix_fmt             pixel format in video\n    ```\n\n    If you also want to copy audio from the input videos, run:\n\n     ```bash\n    ffmpeg -r 23.98 -i out_frames/frame%08d.jpg -i onepiece_demo.mp4 -map 0:v:0 -map 1:a:0 -c:a copy -c:v libx264 -r 23.98 -pix_fmt yuv420p output_w_audio.mp4\n    ```\n\n    ```console\n    Usage:\n    -i                   input video path, here we use two input streams\n    -c:v                 video encoder (usually we use libx264)\n    -r                   fps, remember to modify it to meet your needs\n    -pix_fmt             pixel format in video\n    ```\n\n## More Demos\n\n- Input video for One Piece:\n\n    <https://user-images.githubusercontent.com/17445847/145706822-0e83d9c4-78ef-40ee-b2a4-d8b8c3692d17.mp4>\n\n- Out video for One Piece\n\n    <https://user-images.githubusercontent.com/17445847/164960481-759658cf-fcb8-480c-b888-cecb606e8744.mp4>\n\n**More comparisons**\n\n<https://user-images.githubusercontent.com/17445847/145707458-04a5e9b9-2edd-4d1f-b400-380a72e5f5e6.MP4>\n"
  },
  {
    "path": "docs/feedback.md",
    "content": "# Feedback 反馈\n\n## 动漫插画模型\n\n1. 视频处理不了: 目前的模型，不是针对视频的，所以视频效果很很不好。我们在探究针对视频的模型了\n1. 景深虚化有问题: 现在的模型把一些景深 和 特意的虚化 都复原了，感觉不好。这个后面我们会考虑把这个信息结合进入。一个简单的做法是识别景深和虚化，然后作为条件告诉神经网络，哪些地方复原强一些，哪些地方复原要弱一些\n1. 不可以调节: 像 Waifu2X 可以调节。可以根据自己的喜好，做调整，但是 Real-ESRGAN-anime 并不可以。导致有些恢复效果过了\n1. 把原来的风格改变了: 不同的动漫插画都有自己的风格，现在的 Real-ESRGAN-anime 倾向于恢复成一种风格（这是受到训练数据集影响的）。风格是动漫很重要的一个要素，所以要尽可能保持\n1. 模型太大: 目前的模型处理太慢，能够更快。这个我们有相关的工作在探究，希望能够尽快有结果，并应用到 Real-ESRGAN 这一系列的模型上\n\nThanks for the [detailed and valuable feedbacks/suggestions](https://github.com/xinntao/Real-ESRGAN/issues/131) by [2ji3150](https://github.com/2ji3150).\n"
  },
  {
    "path": "docs/model_zoo.md",
    "content": "# :european_castle: Model Zoo\n\n- [For General Images](#for-general-images)\n- [For Anime Images](#for-anime-images)\n- [For Anime Videos](#for-anime-videos)\n\n---\n\n## For General Images\n\n| Models                                                                                                                          | Scale | Description                                  |\n| ------------------------------------------------------------------------------------------------------------------------------- | :---- | :------------------------------------------- |\n| [RealESRGAN_x4plus](https://github.com/xinntao/Real-ESRGAN/releases/download/v0.1.0/RealESRGAN_x4plus.pth)                      | X4    | X4 model for general images                  |\n| [RealESRGAN_x2plus](https://github.com/xinntao/Real-ESRGAN/releases/download/v0.2.1/RealESRGAN_x2plus.pth)                      | X2    | X2 model for general images                  |\n| [RealESRNet_x4plus](https://github.com/xinntao/Real-ESRGAN/releases/download/v0.1.1/RealESRNet_x4plus.pth)                      | X4    | X4 model with MSE loss (over-smooth effects) |\n| [official ESRGAN_x4](https://github.com/xinntao/Real-ESRGAN/releases/download/v0.1.1/ESRGAN_SRx4_DF2KOST_official-ff704c30.pth) | X4    | official ESRGAN model                        |\n| [realesr-general-x4v3](https://github.com/xinntao/Real-ESRGAN/releases/download/v0.2.5.0/realesr-general-x4v3.pth) | X4 (can also be used for X1, X2, X3) | A tiny small model (consume much fewer GPU memory and time); not too strong deblur and denoise capacity |\n\nThe following models are **discriminators**, which are usually used for fine-tuning.\n\n| Models                                                                                                                 | Corresponding model |\n| ---------------------------------------------------------------------------------------------------------------------- | :------------------ |\n| [RealESRGAN_x4plus_netD](https://github.com/xinntao/Real-ESRGAN/releases/download/v0.2.2.3/RealESRGAN_x4plus_netD.pth) | RealESRGAN_x4plus   |\n| [RealESRGAN_x2plus_netD](https://github.com/xinntao/Real-ESRGAN/releases/download/v0.2.2.3/RealESRGAN_x2plus_netD.pth) | RealESRGAN_x2plus   |\n\n## For Anime Images / Illustrations\n\n| Models                                                                                                                         | Scale | Description                                                 |\n| ------------------------------------------------------------------------------------------------------------------------------ | :---- | :---------------------------------------------------------- |\n| [RealESRGAN_x4plus_anime_6B](https://github.com/xinntao/Real-ESRGAN/releases/download/v0.2.2.4/RealESRGAN_x4plus_anime_6B.pth) | X4    | Optimized for anime images; 6 RRDB blocks (smaller network) |\n\nThe following models are **discriminators**, which are usually used for fine-tuning.\n\n| Models                                                                                                                                   | Corresponding model        |\n| ---------------------------------------------------------------------------------------------------------------------------------------- | :------------------------- |\n| [RealESRGAN_x4plus_anime_6B_netD](https://github.com/xinntao/Real-ESRGAN/releases/download/v0.2.2.4/RealESRGAN_x4plus_anime_6B_netD.pth) | RealESRGAN_x4plus_anime_6B |\n\n## For Animation Videos\n\n| Models                                                                                                                             | Scale | Description                    |\n| ---------------------------------------------------------------------------------------------------------------------------------- | :---- | :----------------------------- |\n| [realesr-animevideov3](https://github.com/xinntao/Real-ESRGAN/releases/download/v0.2.5.0/realesr-animevideov3.pth) | X4<sup>1</sup>    | Anime video model with XS size |\n\nNote: <br>\n<sup>1</sup> This model can also be used for X1, X2, X3.\n\nThe following models are **discriminators**, which are usually used for fine-tuning.\n\nTODO\n"
  },
  {
    "path": "docs/ncnn_conversion.md",
    "content": "# Instructions on converting to NCNN models\n\n1. Convert to onnx model with `scripts/pytorch2onnx.py`. Remember to modify codes accordingly\n1. Convert onnx model to ncnn model\n    1. `cd ncnn-master\\ncnn\\build\\tools\\onnx`\n    1. `onnx2ncnn.exe realesrgan-x4.onnx realesrgan-x4-raw.param realesrgan-x4-raw.bin`\n1. Optimize ncnn model\n    1. fp16 mode\n        1. `cd ncnn-master\\ncnn\\build\\tools`\n        1. `ncnnoptimize.exe realesrgan-x4-raw.param realesrgan-x4-raw.bin realesrgan-x4.param realesrgan-x4.bin 1`\n1. Modify the blob name in `realesrgan-x4.param`: `data` and `output`\n"
  },
  {
    "path": "inference_realesrgan.py",
    "content": "import argparse\nimport cv2\nimport glob\nimport os\nfrom basicsr.archs.rrdbnet_arch import RRDBNet\nfrom basicsr.utils.download_util import load_file_from_url\n\nfrom realesrgan import RealESRGANer\nfrom realesrgan.archs.srvgg_arch import SRVGGNetCompact\n\n\ndef main():\n    \"\"\"Inference demo for Real-ESRGAN.\n    \"\"\"\n    parser = argparse.ArgumentParser()\n    parser.add_argument('-i', '--input', type=str, default='inputs', help='Input image or folder')\n    parser.add_argument(\n        '-n',\n        '--model_name',\n        type=str,\n        default='RealESRGAN_x4plus',\n        help=('Model names: RealESRGAN_x4plus | RealESRNet_x4plus | RealESRGAN_x4plus_anime_6B | RealESRGAN_x2plus | '\n              'realesr-animevideov3 | realesr-general-x4v3'))\n    parser.add_argument('-o', '--output', type=str, default='results', help='Output folder')\n    parser.add_argument(\n        '-dn',\n        '--denoise_strength',\n        type=float,\n        default=0.5,\n        help=('Denoise strength. 0 for weak denoise (keep noise), 1 for strong denoise ability. '\n              'Only used for the realesr-general-x4v3 model'))\n    parser.add_argument('-s', '--outscale', type=float, default=4, help='The final upsampling scale of the image')\n    parser.add_argument(\n        '--model_path', type=str, default=None, help='[Option] Model path. Usually, you do not need to specify it')\n    parser.add_argument('--suffix', type=str, default='out', help='Suffix of the restored image')\n    parser.add_argument('-t', '--tile', type=int, default=0, help='Tile size, 0 for no tile during testing')\n    parser.add_argument('--tile_pad', type=int, default=10, help='Tile padding')\n    parser.add_argument('--pre_pad', type=int, default=0, help='Pre padding size at each border')\n    parser.add_argument('--face_enhance', action='store_true', help='Use GFPGAN to enhance face')\n    parser.add_argument(\n        '--fp32', action='store_true', help='Use fp32 precision during inference. Default: fp16 (half precision).')\n    parser.add_argument(\n        '--alpha_upsampler',\n        type=str,\n        default='realesrgan',\n        help='The upsampler for the alpha channels. Options: realesrgan | bicubic')\n    parser.add_argument(\n        '--ext',\n        type=str,\n        default='auto',\n        help='Image extension. Options: auto | jpg | png, auto means using the same extension as inputs')\n    parser.add_argument(\n        '-g', '--gpu-id', type=int, default=None, help='gpu device to use (default=None) can be 0,1,2 for multi-gpu')\n\n    args = parser.parse_args()\n\n    # determine models according to model names\n    args.model_name = args.model_name.split('.')[0]\n    if args.model_name == 'RealESRGAN_x4plus':  # x4 RRDBNet model\n        model = RRDBNet(num_in_ch=3, num_out_ch=3, num_feat=64, num_block=23, num_grow_ch=32, scale=4)\n        netscale = 4\n        file_url = ['https://github.com/xinntao/Real-ESRGAN/releases/download/v0.1.0/RealESRGAN_x4plus.pth']\n    elif args.model_name == 'RealESRNet_x4plus':  # x4 RRDBNet model\n        model = RRDBNet(num_in_ch=3, num_out_ch=3, num_feat=64, num_block=23, num_grow_ch=32, scale=4)\n        netscale = 4\n        file_url = ['https://github.com/xinntao/Real-ESRGAN/releases/download/v0.1.1/RealESRNet_x4plus.pth']\n    elif args.model_name == 'RealESRGAN_x4plus_anime_6B':  # x4 RRDBNet model with 6 blocks\n        model = RRDBNet(num_in_ch=3, num_out_ch=3, num_feat=64, num_block=6, num_grow_ch=32, scale=4)\n        netscale = 4\n        file_url = ['https://github.com/xinntao/Real-ESRGAN/releases/download/v0.2.2.4/RealESRGAN_x4plus_anime_6B.pth']\n    elif args.model_name == 'RealESRGAN_x2plus':  # x2 RRDBNet model\n        model = RRDBNet(num_in_ch=3, num_out_ch=3, num_feat=64, num_block=23, num_grow_ch=32, scale=2)\n        netscale = 2\n        file_url = ['https://github.com/xinntao/Real-ESRGAN/releases/download/v0.2.1/RealESRGAN_x2plus.pth']\n    elif args.model_name == 'realesr-animevideov3':  # x4 VGG-style model (XS size)\n        model = SRVGGNetCompact(num_in_ch=3, num_out_ch=3, num_feat=64, num_conv=16, upscale=4, act_type='prelu')\n        netscale = 4\n        file_url = ['https://github.com/xinntao/Real-ESRGAN/releases/download/v0.2.5.0/realesr-animevideov3.pth']\n    elif args.model_name == 'realesr-general-x4v3':  # x4 VGG-style model (S size)\n        model = SRVGGNetCompact(num_in_ch=3, num_out_ch=3, num_feat=64, num_conv=32, upscale=4, act_type='prelu')\n        netscale = 4\n        file_url = [\n            'https://github.com/xinntao/Real-ESRGAN/releases/download/v0.2.5.0/realesr-general-wdn-x4v3.pth',\n            'https://github.com/xinntao/Real-ESRGAN/releases/download/v0.2.5.0/realesr-general-x4v3.pth'\n        ]\n\n    # determine model paths\n    if args.model_path is not None:\n        model_path = args.model_path\n    else:\n        model_path = os.path.join('weights', args.model_name + '.pth')\n        if not os.path.isfile(model_path):\n            ROOT_DIR = os.path.dirname(os.path.abspath(__file__))\n            for url in file_url:\n                # model_path will be updated\n                model_path = load_file_from_url(\n                    url=url, model_dir=os.path.join(ROOT_DIR, 'weights'), progress=True, file_name=None)\n\n    # use dni to control the denoise strength\n    dni_weight = None\n    if args.model_name == 'realesr-general-x4v3' and args.denoise_strength != 1:\n        wdn_model_path = model_path.replace('realesr-general-x4v3', 'realesr-general-wdn-x4v3')\n        model_path = [model_path, wdn_model_path]\n        dni_weight = [args.denoise_strength, 1 - args.denoise_strength]\n\n    # restorer\n    upsampler = RealESRGANer(\n        scale=netscale,\n        model_path=model_path,\n        dni_weight=dni_weight,\n        model=model,\n        tile=args.tile,\n        tile_pad=args.tile_pad,\n        pre_pad=args.pre_pad,\n        half=not args.fp32,\n        gpu_id=args.gpu_id)\n\n    if args.face_enhance:  # Use GFPGAN for face enhancement\n        from gfpgan import GFPGANer\n        face_enhancer = GFPGANer(\n            model_path='https://github.com/TencentARC/GFPGAN/releases/download/v1.3.0/GFPGANv1.3.pth',\n            upscale=args.outscale,\n            arch='clean',\n            channel_multiplier=2,\n            bg_upsampler=upsampler)\n    os.makedirs(args.output, exist_ok=True)\n\n    if os.path.isfile(args.input):\n        paths = [args.input]\n    else:\n        paths = sorted(glob.glob(os.path.join(args.input, '*')))\n\n    for idx, path in enumerate(paths):\n        imgname, extension = os.path.splitext(os.path.basename(path))\n        print('Testing', idx, imgname)\n\n        img = cv2.imread(path, cv2.IMREAD_UNCHANGED)\n        if len(img.shape) == 3 and img.shape[2] == 4:\n            img_mode = 'RGBA'\n        else:\n            img_mode = None\n\n        try:\n            if args.face_enhance:\n                _, _, output = face_enhancer.enhance(img, has_aligned=False, only_center_face=False, paste_back=True)\n            else:\n                output, _ = upsampler.enhance(img, outscale=args.outscale)\n        except RuntimeError as error:\n            print('Error', error)\n            print('If you encounter CUDA out of memory, try to set --tile with a smaller number.')\n        else:\n            if args.ext == 'auto':\n                extension = extension[1:]\n            else:\n                extension = args.ext\n            if img_mode == 'RGBA':  # RGBA images should be saved in png format\n                extension = 'png'\n            if args.suffix == '':\n                save_path = os.path.join(args.output, f'{imgname}.{extension}')\n            else:\n                save_path = os.path.join(args.output, f'{imgname}_{args.suffix}.{extension}')\n            cv2.imwrite(save_path, output)\n\n\nif __name__ == '__main__':\n    main()\n"
  },
  {
    "path": "inference_realesrgan_video.py",
    "content": "import argparse\nimport cv2\nimport glob\nimport mimetypes\nimport numpy as np\nimport os\nimport shutil\nimport subprocess\nimport torch\nfrom basicsr.archs.rrdbnet_arch import RRDBNet\nfrom basicsr.utils.download_util import load_file_from_url\nfrom os import path as osp\nfrom tqdm import tqdm\n\nfrom realesrgan import RealESRGANer\nfrom realesrgan.archs.srvgg_arch import SRVGGNetCompact\n\ntry:\n    import ffmpeg\nexcept ImportError:\n    import pip\n    pip.main(['install', '--user', 'ffmpeg-python'])\n    import ffmpeg\n\n\ndef get_video_meta_info(video_path):\n    ret = {}\n    probe = ffmpeg.probe(video_path)\n    video_streams = [stream for stream in probe['streams'] if stream['codec_type'] == 'video']\n    has_audio = any(stream['codec_type'] == 'audio' for stream in probe['streams'])\n    ret['width'] = video_streams[0]['width']\n    ret['height'] = video_streams[0]['height']\n    ret['fps'] = eval(video_streams[0]['avg_frame_rate'])\n    ret['audio'] = ffmpeg.input(video_path).audio if has_audio else None\n    ret['nb_frames'] = int(video_streams[0]['nb_frames'])\n    return ret\n\n\ndef get_sub_video(args, num_process, process_idx):\n    if num_process == 1:\n        return args.input\n    meta = get_video_meta_info(args.input)\n    duration = int(meta['nb_frames'] / meta['fps'])\n    part_time = duration // num_process\n    print(f'duration: {duration}, part_time: {part_time}')\n    os.makedirs(osp.join(args.output, f'{args.video_name}_inp_tmp_videos'), exist_ok=True)\n    out_path = osp.join(args.output, f'{args.video_name}_inp_tmp_videos', f'{process_idx:03d}.mp4')\n    cmd = [\n        args.ffmpeg_bin, f'-i {args.input}', '-ss', f'{part_time * process_idx}',\n        f'-to {part_time * (process_idx + 1)}' if process_idx != num_process - 1 else '', '-async 1', out_path, '-y'\n    ]\n    print(' '.join(cmd))\n    subprocess.call(' '.join(cmd), shell=True)\n    return out_path\n\n\nclass Reader:\n\n    def __init__(self, args, total_workers=1, worker_idx=0):\n        self.args = args\n        input_type = mimetypes.guess_type(args.input)[0]\n        self.input_type = 'folder' if input_type is None else input_type\n        self.paths = []  # for image&folder type\n        self.audio = None\n        self.input_fps = None\n        if self.input_type.startswith('video'):\n            video_path = get_sub_video(args, total_workers, worker_idx)\n            self.stream_reader = (\n                ffmpeg.input(video_path).output('pipe:', format='rawvideo', pix_fmt='bgr24',\n                                                loglevel='error').run_async(\n                                                    pipe_stdin=True, pipe_stdout=True, cmd=args.ffmpeg_bin))\n            meta = get_video_meta_info(video_path)\n            self.width = meta['width']\n            self.height = meta['height']\n            self.input_fps = meta['fps']\n            self.audio = meta['audio']\n            self.nb_frames = meta['nb_frames']\n\n        else:\n            if self.input_type.startswith('image'):\n                self.paths = [args.input]\n            else:\n                paths = sorted(glob.glob(os.path.join(args.input, '*')))\n                tot_frames = len(paths)\n                num_frame_per_worker = tot_frames // total_workers + (1 if tot_frames % total_workers else 0)\n                self.paths = paths[num_frame_per_worker * worker_idx:num_frame_per_worker * (worker_idx + 1)]\n\n            self.nb_frames = len(self.paths)\n            assert self.nb_frames > 0, 'empty folder'\n            from PIL import Image\n            tmp_img = Image.open(self.paths[0])\n            self.width, self.height = tmp_img.size\n        self.idx = 0\n\n    def get_resolution(self):\n        return self.height, self.width\n\n    def get_fps(self):\n        if self.args.fps is not None:\n            return self.args.fps\n        elif self.input_fps is not None:\n            return self.input_fps\n        return 24\n\n    def get_audio(self):\n        return self.audio\n\n    def __len__(self):\n        return self.nb_frames\n\n    def get_frame_from_stream(self):\n        img_bytes = self.stream_reader.stdout.read(self.width * self.height * 3)  # 3 bytes for one pixel\n        if not img_bytes:\n            return None\n        img = np.frombuffer(img_bytes, np.uint8).reshape([self.height, self.width, 3])\n        return img\n\n    def get_frame_from_list(self):\n        if self.idx >= self.nb_frames:\n            return None\n        img = cv2.imread(self.paths[self.idx])\n        self.idx += 1\n        return img\n\n    def get_frame(self):\n        if self.input_type.startswith('video'):\n            return self.get_frame_from_stream()\n        else:\n            return self.get_frame_from_list()\n\n    def close(self):\n        if self.input_type.startswith('video'):\n            self.stream_reader.stdin.close()\n            self.stream_reader.wait()\n\n\nclass Writer:\n\n    def __init__(self, args, audio, height, width, video_save_path, fps):\n        out_width, out_height = int(width * args.outscale), int(height * args.outscale)\n        if out_height > 2160:\n            print('You are generating video that is larger than 4K, which will be very slow due to IO speed.',\n                  'We highly recommend to decrease the outscale(aka, -s).')\n\n        if audio is not None:\n            self.stream_writer = (\n                ffmpeg.input('pipe:', format='rawvideo', pix_fmt='bgr24', s=f'{out_width}x{out_height}',\n                             framerate=fps).output(\n                                 audio,\n                                 video_save_path,\n                                 pix_fmt='yuv420p',\n                                 vcodec='libx264',\n                                 loglevel='error',\n                                 acodec='copy').overwrite_output().run_async(\n                                     pipe_stdin=True, pipe_stdout=True, cmd=args.ffmpeg_bin))\n        else:\n            self.stream_writer = (\n                ffmpeg.input('pipe:', format='rawvideo', pix_fmt='bgr24', s=f'{out_width}x{out_height}',\n                             framerate=fps).output(\n                                 video_save_path, pix_fmt='yuv420p', vcodec='libx264',\n                                 loglevel='error').overwrite_output().run_async(\n                                     pipe_stdin=True, pipe_stdout=True, cmd=args.ffmpeg_bin))\n\n    def write_frame(self, frame):\n        frame = frame.astype(np.uint8).tobytes()\n        self.stream_writer.stdin.write(frame)\n\n    def close(self):\n        self.stream_writer.stdin.close()\n        self.stream_writer.wait()\n\n\ndef inference_video(args, video_save_path, device=None, total_workers=1, worker_idx=0):\n    # ---------------------- determine models according to model names ---------------------- #\n    args.model_name = args.model_name.split('.pth')[0]\n    if args.model_name == 'RealESRGAN_x4plus':  # x4 RRDBNet model\n        model = RRDBNet(num_in_ch=3, num_out_ch=3, num_feat=64, num_block=23, num_grow_ch=32, scale=4)\n        netscale = 4\n        file_url = ['https://github.com/xinntao/Real-ESRGAN/releases/download/v0.1.0/RealESRGAN_x4plus.pth']\n    elif args.model_name == 'RealESRNet_x4plus':  # x4 RRDBNet model\n        model = RRDBNet(num_in_ch=3, num_out_ch=3, num_feat=64, num_block=23, num_grow_ch=32, scale=4)\n        netscale = 4\n        file_url = ['https://github.com/xinntao/Real-ESRGAN/releases/download/v0.1.1/RealESRNet_x4plus.pth']\n    elif args.model_name == 'RealESRGAN_x4plus_anime_6B':  # x4 RRDBNet model with 6 blocks\n        model = RRDBNet(num_in_ch=3, num_out_ch=3, num_feat=64, num_block=6, num_grow_ch=32, scale=4)\n        netscale = 4\n        file_url = ['https://github.com/xinntao/Real-ESRGAN/releases/download/v0.2.2.4/RealESRGAN_x4plus_anime_6B.pth']\n    elif args.model_name == 'RealESRGAN_x2plus':  # x2 RRDBNet model\n        model = RRDBNet(num_in_ch=3, num_out_ch=3, num_feat=64, num_block=23, num_grow_ch=32, scale=2)\n        netscale = 2\n        file_url = ['https://github.com/xinntao/Real-ESRGAN/releases/download/v0.2.1/RealESRGAN_x2plus.pth']\n    elif args.model_name == 'realesr-animevideov3':  # x4 VGG-style model (XS size)\n        model = SRVGGNetCompact(num_in_ch=3, num_out_ch=3, num_feat=64, num_conv=16, upscale=4, act_type='prelu')\n        netscale = 4\n        file_url = ['https://github.com/xinntao/Real-ESRGAN/releases/download/v0.2.5.0/realesr-animevideov3.pth']\n    elif args.model_name == 'realesr-general-x4v3':  # x4 VGG-style model (S size)\n        model = SRVGGNetCompact(num_in_ch=3, num_out_ch=3, num_feat=64, num_conv=32, upscale=4, act_type='prelu')\n        netscale = 4\n        file_url = [\n            'https://github.com/xinntao/Real-ESRGAN/releases/download/v0.2.5.0/realesr-general-wdn-x4v3.pth',\n            'https://github.com/xinntao/Real-ESRGAN/releases/download/v0.2.5.0/realesr-general-x4v3.pth'\n        ]\n\n    # ---------------------- determine model paths ---------------------- #\n    model_path = os.path.join('weights', args.model_name + '.pth')\n    if not os.path.isfile(model_path):\n        ROOT_DIR = os.path.dirname(os.path.abspath(__file__))\n        for url in file_url:\n            # model_path will be updated\n            model_path = load_file_from_url(\n                url=url, model_dir=os.path.join(ROOT_DIR, 'weights'), progress=True, file_name=None)\n\n    # use dni to control the denoise strength\n    dni_weight = None\n    if args.model_name == 'realesr-general-x4v3' and args.denoise_strength != 1:\n        wdn_model_path = model_path.replace('realesr-general-x4v3', 'realesr-general-wdn-x4v3')\n        model_path = [model_path, wdn_model_path]\n        dni_weight = [args.denoise_strength, 1 - args.denoise_strength]\n\n    # restorer\n    upsampler = RealESRGANer(\n        scale=netscale,\n        model_path=model_path,\n        dni_weight=dni_weight,\n        model=model,\n        tile=args.tile,\n        tile_pad=args.tile_pad,\n        pre_pad=args.pre_pad,\n        half=not args.fp32,\n        device=device,\n    )\n\n    if 'anime' in args.model_name and args.face_enhance:\n        print('face_enhance is not supported in anime models, we turned this option off for you. '\n              'if you insist on turning it on, please manually comment the relevant lines of code.')\n        args.face_enhance = False\n\n    if args.face_enhance:  # Use GFPGAN for face enhancement\n        from gfpgan import GFPGANer\n        face_enhancer = GFPGANer(\n            model_path='https://github.com/TencentARC/GFPGAN/releases/download/v1.3.0/GFPGANv1.3.pth',\n            upscale=args.outscale,\n            arch='clean',\n            channel_multiplier=2,\n            bg_upsampler=upsampler)  # TODO support custom device\n    else:\n        face_enhancer = None\n\n    reader = Reader(args, total_workers, worker_idx)\n    audio = reader.get_audio()\n    height, width = reader.get_resolution()\n    fps = reader.get_fps()\n    writer = Writer(args, audio, height, width, video_save_path, fps)\n\n    pbar = tqdm(total=len(reader), unit='frame', desc='inference')\n    while True:\n        img = reader.get_frame()\n        if img is None:\n            break\n\n        try:\n            if args.face_enhance:\n                _, _, output = face_enhancer.enhance(img, has_aligned=False, only_center_face=False, paste_back=True)\n            else:\n                output, _ = upsampler.enhance(img, outscale=args.outscale)\n        except RuntimeError as error:\n            print('Error', error)\n            print('If you encounter CUDA out of memory, try to set --tile with a smaller number.')\n        else:\n            writer.write_frame(output)\n\n        torch.cuda.synchronize(device)\n        pbar.update(1)\n\n    reader.close()\n    writer.close()\n\n\ndef run(args):\n    args.video_name = osp.splitext(os.path.basename(args.input))[0]\n    video_save_path = osp.join(args.output, f'{args.video_name}_{args.suffix}.mp4')\n\n    if args.extract_frame_first:\n        tmp_frames_folder = osp.join(args.output, f'{args.video_name}_inp_tmp_frames')\n        os.makedirs(tmp_frames_folder, exist_ok=True)\n        os.system(f'ffmpeg -i {args.input} -qscale:v 1 -qmin 1 -qmax 1 -vsync 0  {tmp_frames_folder}/frame%08d.png')\n        args.input = tmp_frames_folder\n\n    num_gpus = torch.cuda.device_count()\n    num_process = num_gpus * args.num_process_per_gpu\n    if num_process == 1:\n        inference_video(args, video_save_path)\n        return\n\n    ctx = torch.multiprocessing.get_context('spawn')\n    pool = ctx.Pool(num_process)\n    os.makedirs(osp.join(args.output, f'{args.video_name}_out_tmp_videos'), exist_ok=True)\n    pbar = tqdm(total=num_process, unit='sub_video', desc='inference')\n    for i in range(num_process):\n        sub_video_save_path = osp.join(args.output, f'{args.video_name}_out_tmp_videos', f'{i:03d}.mp4')\n        pool.apply_async(\n            inference_video,\n            args=(args, sub_video_save_path, torch.device(i % num_gpus), num_process, i),\n            callback=lambda arg: pbar.update(1))\n    pool.close()\n    pool.join()\n\n    # combine sub videos\n    # prepare vidlist.txt\n    with open(f'{args.output}/{args.video_name}_vidlist.txt', 'w') as f:\n        for i in range(num_process):\n            f.write(f'file \\'{args.video_name}_out_tmp_videos/{i:03d}.mp4\\'\\n')\n\n    cmd = [\n        args.ffmpeg_bin, '-f', 'concat', '-safe', '0', '-i', f'{args.output}/{args.video_name}_vidlist.txt', '-c',\n        'copy', f'{video_save_path}'\n    ]\n    print(' '.join(cmd))\n    subprocess.call(cmd)\n    shutil.rmtree(osp.join(args.output, f'{args.video_name}_out_tmp_videos'))\n    if osp.exists(osp.join(args.output, f'{args.video_name}_inp_tmp_videos')):\n        shutil.rmtree(osp.join(args.output, f'{args.video_name}_inp_tmp_videos'))\n    os.remove(f'{args.output}/{args.video_name}_vidlist.txt')\n\n\ndef main():\n    \"\"\"Inference demo for Real-ESRGAN.\n    It mainly for restoring anime videos.\n\n    \"\"\"\n    parser = argparse.ArgumentParser()\n    parser.add_argument('-i', '--input', type=str, default='inputs', help='Input video, image or folder')\n    parser.add_argument(\n        '-n',\n        '--model_name',\n        type=str,\n        default='realesr-animevideov3',\n        help=('Model names: realesr-animevideov3 | RealESRGAN_x4plus_anime_6B | RealESRGAN_x4plus | RealESRNet_x4plus |'\n              ' RealESRGAN_x2plus | realesr-general-x4v3'\n              'Default:realesr-animevideov3'))\n    parser.add_argument('-o', '--output', type=str, default='results', help='Output folder')\n    parser.add_argument(\n        '-dn',\n        '--denoise_strength',\n        type=float,\n        default=0.5,\n        help=('Denoise strength. 0 for weak denoise (keep noise), 1 for strong denoise ability. '\n              'Only used for the realesr-general-x4v3 model'))\n    parser.add_argument('-s', '--outscale', type=float, default=4, help='The final upsampling scale of the image')\n    parser.add_argument('--suffix', type=str, default='out', help='Suffix of the restored video')\n    parser.add_argument('-t', '--tile', type=int, default=0, help='Tile size, 0 for no tile during testing')\n    parser.add_argument('--tile_pad', type=int, default=10, help='Tile padding')\n    parser.add_argument('--pre_pad', type=int, default=0, help='Pre padding size at each border')\n    parser.add_argument('--face_enhance', action='store_true', help='Use GFPGAN to enhance face')\n    parser.add_argument(\n        '--fp32', action='store_true', help='Use fp32 precision during inference. Default: fp16 (half precision).')\n    parser.add_argument('--fps', type=float, default=None, help='FPS of the output video')\n    parser.add_argument('--ffmpeg_bin', type=str, default='ffmpeg', help='The path to ffmpeg')\n    parser.add_argument('--extract_frame_first', action='store_true')\n    parser.add_argument('--num_process_per_gpu', type=int, default=1)\n\n    parser.add_argument(\n        '--alpha_upsampler',\n        type=str,\n        default='realesrgan',\n        help='The upsampler for the alpha channels. Options: realesrgan | bicubic')\n    parser.add_argument(\n        '--ext',\n        type=str,\n        default='auto',\n        help='Image extension. Options: auto | jpg | png, auto means using the same extension as inputs')\n    args = parser.parse_args()\n\n    args.input = args.input.rstrip('/').rstrip('\\\\')\n    os.makedirs(args.output, exist_ok=True)\n\n    if mimetypes.guess_type(args.input)[0] is not None and mimetypes.guess_type(args.input)[0].startswith('video'):\n        is_video = True\n    else:\n        is_video = False\n\n    if is_video and args.input.endswith('.flv'):\n        mp4_path = args.input.replace('.flv', '.mp4')\n        os.system(f'ffmpeg -i {args.input} -codec copy {mp4_path}')\n        args.input = mp4_path\n\n    if args.extract_frame_first and not is_video:\n        args.extract_frame_first = False\n\n    run(args)\n\n    if args.extract_frame_first:\n        tmp_frames_folder = osp.join(args.output, f'{args.video_name}_inp_tmp_frames')\n        shutil.rmtree(tmp_frames_folder)\n\n\nif __name__ == '__main__':\n    main()\n"
  },
  {
    "path": "options/finetune_realesrgan_x4plus.yml",
    "content": "# general settings\nname: finetune_RealESRGANx4plus_400k\nmodel_type: RealESRGANModel\nscale: 4\nnum_gpu: auto\nmanual_seed: 0\n\n# ----------------- options for synthesizing training data in RealESRGANModel ----------------- #\n# USM the ground-truth\nl1_gt_usm: True\npercep_gt_usm: True\ngan_gt_usm: False\n\n# the first degradation process\nresize_prob: [0.2, 0.7, 0.1]  # up, down, keep\nresize_range: [0.15, 1.5]\ngaussian_noise_prob: 0.5\nnoise_range: [1, 30]\npoisson_scale_range: [0.05, 3]\ngray_noise_prob: 0.4\njpeg_range: [30, 95]\n\n# the second degradation process\nsecond_blur_prob: 0.8\nresize_prob2: [0.3, 0.4, 0.3]  # up, down, keep\nresize_range2: [0.3, 1.2]\ngaussian_noise_prob2: 0.5\nnoise_range2: [1, 25]\npoisson_scale_range2: [0.05, 2.5]\ngray_noise_prob2: 0.4\njpeg_range2: [30, 95]\n\ngt_size: 256\nqueue_size: 180\n\n# dataset and data loader settings\ndatasets:\n  train:\n    name: DF2K+OST\n    type: RealESRGANDataset\n    dataroot_gt: datasets/DF2K\n    meta_info: datasets/DF2K/meta_info/meta_info_DF2Kmultiscale+OST_sub.txt\n    io_backend:\n      type: disk\n\n    blur_kernel_size: 21\n    kernel_list: ['iso', 'aniso', 'generalized_iso', 'generalized_aniso', 'plateau_iso', 'plateau_aniso']\n    kernel_prob: [0.45, 0.25, 0.12, 0.03, 0.12, 0.03]\n    sinc_prob: 0.1\n    blur_sigma: [0.2, 3]\n    betag_range: [0.5, 4]\n    betap_range: [1, 2]\n\n    blur_kernel_size2: 21\n    kernel_list2: ['iso', 'aniso', 'generalized_iso', 'generalized_aniso', 'plateau_iso', 'plateau_aniso']\n    kernel_prob2: [0.45, 0.25, 0.12, 0.03, 0.12, 0.03]\n    sinc_prob2: 0.1\n    blur_sigma2: [0.2, 1.5]\n    betag_range2: [0.5, 4]\n    betap_range2: [1, 2]\n\n    final_sinc_prob: 0.8\n\n    gt_size: 256\n    use_hflip: True\n    use_rot: False\n\n    # data loader\n    use_shuffle: true\n    num_worker_per_gpu: 5\n    batch_size_per_gpu: 12\n    dataset_enlarge_ratio: 1\n    prefetch_mode: ~\n\n  # Uncomment these for validation\n  # val:\n  #   name: validation\n  #   type: PairedImageDataset\n  #   dataroot_gt: path_to_gt\n  #   dataroot_lq: path_to_lq\n  #   io_backend:\n  #     type: disk\n\n# network structures\nnetwork_g:\n  type: RRDBNet\n  num_in_ch: 3\n  num_out_ch: 3\n  num_feat: 64\n  num_block: 23\n  num_grow_ch: 32\n\nnetwork_d:\n  type: UNetDiscriminatorSN\n  num_in_ch: 3\n  num_feat: 64\n  skip_connection: True\n\n# path\npath:\n  # use the pre-trained Real-ESRNet model\n  pretrain_network_g: experiments/pretrained_models/RealESRNet_x4plus.pth\n  param_key_g: params_ema\n  strict_load_g: true\n  pretrain_network_d: experiments/pretrained_models/RealESRGAN_x4plus_netD.pth\n  param_key_d: params\n  strict_load_d: true\n  resume_state: ~\n\n# training settings\ntrain:\n  ema_decay: 0.999\n  optim_g:\n    type: Adam\n    lr: !!float 1e-4\n    weight_decay: 0\n    betas: [0.9, 0.99]\n  optim_d:\n    type: Adam\n    lr: !!float 1e-4\n    weight_decay: 0\n    betas: [0.9, 0.99]\n\n  scheduler:\n    type: MultiStepLR\n    milestones: [400000]\n    gamma: 0.5\n\n  total_iter: 400000\n  warmup_iter: -1  # no warm up\n\n  # losses\n  pixel_opt:\n    type: L1Loss\n    loss_weight: 1.0\n    reduction: mean\n  # perceptual loss (content and style losses)\n  perceptual_opt:\n    type: PerceptualLoss\n    layer_weights:\n      # before relu\n      'conv1_2': 0.1\n      'conv2_2': 0.1\n      'conv3_4': 1\n      'conv4_4': 1\n      'conv5_4': 1\n    vgg_type: vgg19\n    use_input_norm: true\n    perceptual_weight: !!float 1.0\n    style_weight: 0\n    range_norm: false\n    criterion: l1\n  # gan loss\n  gan_opt:\n    type: GANLoss\n    gan_type: vanilla\n    real_label_val: 1.0\n    fake_label_val: 0.0\n    loss_weight: !!float 1e-1\n\n  net_d_iters: 1\n  net_d_init_iters: 0\n\n# Uncomment these for validation\n# validation settings\n# val:\n#   val_freq: !!float 5e3\n#   save_img: True\n\n#   metrics:\n#     psnr: # metric name\n#       type: calculate_psnr\n#       crop_border: 4\n#       test_y_channel: false\n\n# logging settings\nlogger:\n  print_freq: 100\n  save_checkpoint_freq: !!float 5e3\n  use_tb_logger: true\n  wandb:\n    project: ~\n    resume_id: ~\n\n# dist training settings\ndist_params:\n  backend: nccl\n  port: 29500\n"
  },
  {
    "path": "options/finetune_realesrgan_x4plus_pairdata.yml",
    "content": "# general settings\nname: finetune_RealESRGANx4plus_400k_pairdata\nmodel_type: RealESRGANModel\nscale: 4\nnum_gpu: auto\nmanual_seed: 0\n\n# USM the ground-truth\nl1_gt_usm: True\npercep_gt_usm: True\ngan_gt_usm: False\n\nhigh_order_degradation: False # do not use the high-order degradation generation process\n\n# dataset and data loader settings\ndatasets:\n  train:\n    name: DIV2K\n    type: RealESRGANPairedDataset\n    dataroot_gt: datasets/DF2K\n    dataroot_lq: datasets/DF2K\n    meta_info: datasets/DF2K/meta_info/meta_info_DIV2K_sub_pair.txt\n    io_backend:\n      type: disk\n\n    gt_size: 256\n    use_hflip: True\n    use_rot: False\n\n    # data loader\n    use_shuffle: true\n    num_worker_per_gpu: 5\n    batch_size_per_gpu: 12\n    dataset_enlarge_ratio: 1\n    prefetch_mode: ~\n\n  # Uncomment these for validation\n  # val:\n  #   name: validation\n  #   type: PairedImageDataset\n  #   dataroot_gt: path_to_gt\n  #   dataroot_lq: path_to_lq\n  #   io_backend:\n  #     type: disk\n\n# network structures\nnetwork_g:\n  type: RRDBNet\n  num_in_ch: 3\n  num_out_ch: 3\n  num_feat: 64\n  num_block: 23\n  num_grow_ch: 32\n\nnetwork_d:\n  type: UNetDiscriminatorSN\n  num_in_ch: 3\n  num_feat: 64\n  skip_connection: True\n\n# path\npath:\n  # use the pre-trained Real-ESRNet model\n  pretrain_network_g: experiments/pretrained_models/RealESRNet_x4plus.pth\n  param_key_g: params_ema\n  strict_load_g: true\n  pretrain_network_d: experiments/pretrained_models/RealESRGAN_x4plus_netD.pth\n  param_key_d: params\n  strict_load_d: true\n  resume_state: ~\n\n# training settings\ntrain:\n  ema_decay: 0.999\n  optim_g:\n    type: Adam\n    lr: !!float 1e-4\n    weight_decay: 0\n    betas: [0.9, 0.99]\n  optim_d:\n    type: Adam\n    lr: !!float 1e-4\n    weight_decay: 0\n    betas: [0.9, 0.99]\n\n  scheduler:\n    type: MultiStepLR\n    milestones: [400000]\n    gamma: 0.5\n\n  total_iter: 400000\n  warmup_iter: -1  # no warm up\n\n  # losses\n  pixel_opt:\n    type: L1Loss\n    loss_weight: 1.0\n    reduction: mean\n  # perceptual loss (content and style losses)\n  perceptual_opt:\n    type: PerceptualLoss\n    layer_weights:\n      # before relu\n      'conv1_2': 0.1\n      'conv2_2': 0.1\n      'conv3_4': 1\n      'conv4_4': 1\n      'conv5_4': 1\n    vgg_type: vgg19\n    use_input_norm: true\n    perceptual_weight: !!float 1.0\n    style_weight: 0\n    range_norm: false\n    criterion: l1\n  # gan loss\n  gan_opt:\n    type: GANLoss\n    gan_type: vanilla\n    real_label_val: 1.0\n    fake_label_val: 0.0\n    loss_weight: !!float 1e-1\n\n  net_d_iters: 1\n  net_d_init_iters: 0\n\n# Uncomment these for validation\n# validation settings\n# val:\n#   val_freq: !!float 5e3\n#   save_img: True\n\n#   metrics:\n#     psnr: # metric name\n#       type: calculate_psnr\n#       crop_border: 4\n#       test_y_channel: false\n\n# logging settings\nlogger:\n  print_freq: 100\n  save_checkpoint_freq: !!float 5e3\n  use_tb_logger: true\n  wandb:\n    project: ~\n    resume_id: ~\n\n# dist training settings\ndist_params:\n  backend: nccl\n  port: 29500\n"
  },
  {
    "path": "options/train_realesrgan_x2plus.yml",
    "content": "# general settings\nname: train_RealESRGANx2plus_400k_B12G4\nmodel_type: RealESRGANModel\nscale: 2\nnum_gpu: auto  # auto: can infer from your visible devices automatically. official: 4 GPUs\nmanual_seed: 0\n\n# ----------------- options for synthesizing training data in RealESRGANModel ----------------- #\n# USM the ground-truth\nl1_gt_usm: True\npercep_gt_usm: True\ngan_gt_usm: False\n\n# the first degradation process\nresize_prob: [0.2, 0.7, 0.1]  # up, down, keep\nresize_range: [0.15, 1.5]\ngaussian_noise_prob: 0.5\nnoise_range: [1, 30]\npoisson_scale_range: [0.05, 3]\ngray_noise_prob: 0.4\njpeg_range: [30, 95]\n\n# the second degradation process\nsecond_blur_prob: 0.8\nresize_prob2: [0.3, 0.4, 0.3]  # up, down, keep\nresize_range2: [0.3, 1.2]\ngaussian_noise_prob2: 0.5\nnoise_range2: [1, 25]\npoisson_scale_range2: [0.05, 2.5]\ngray_noise_prob2: 0.4\njpeg_range2: [30, 95]\n\ngt_size: 256\nqueue_size: 180\n\n# dataset and data loader settings\ndatasets:\n  train:\n    name: DF2K+OST\n    type: RealESRGANDataset\n    dataroot_gt: datasets/DF2K\n    meta_info: datasets/DF2K/meta_info/meta_info_DF2Kmultiscale+OST_sub.txt\n    io_backend:\n      type: disk\n\n    blur_kernel_size: 21\n    kernel_list: ['iso', 'aniso', 'generalized_iso', 'generalized_aniso', 'plateau_iso', 'plateau_aniso']\n    kernel_prob: [0.45, 0.25, 0.12, 0.03, 0.12, 0.03]\n    sinc_prob: 0.1\n    blur_sigma: [0.2, 3]\n    betag_range: [0.5, 4]\n    betap_range: [1, 2]\n\n    blur_kernel_size2: 21\n    kernel_list2: ['iso', 'aniso', 'generalized_iso', 'generalized_aniso', 'plateau_iso', 'plateau_aniso']\n    kernel_prob2: [0.45, 0.25, 0.12, 0.03, 0.12, 0.03]\n    sinc_prob2: 0.1\n    blur_sigma2: [0.2, 1.5]\n    betag_range2: [0.5, 4]\n    betap_range2: [1, 2]\n\n    final_sinc_prob: 0.8\n\n    gt_size: 256\n    use_hflip: True\n    use_rot: False\n\n    # data loader\n    use_shuffle: true\n    num_worker_per_gpu: 5\n    batch_size_per_gpu: 12\n    dataset_enlarge_ratio: 1\n    prefetch_mode: ~\n\n  # Uncomment these for validation\n  # val:\n  #   name: validation\n  #   type: PairedImageDataset\n  #   dataroot_gt: path_to_gt\n  #   dataroot_lq: path_to_lq\n  #   io_backend:\n  #     type: disk\n\n# network structures\nnetwork_g:\n  type: RRDBNet\n  num_in_ch: 3\n  num_out_ch: 3\n  num_feat: 64\n  num_block: 23\n  num_grow_ch: 32\n  scale: 2\n\nnetwork_d:\n  type: UNetDiscriminatorSN\n  num_in_ch: 3\n  num_feat: 64\n  skip_connection: True\n\n# path\npath:\n  # use the pre-trained Real-ESRNet model\n  pretrain_network_g: experiments/pretrained_models/RealESRNet_x2plus.pth\n  param_key_g: params_ema\n  strict_load_g: true\n  resume_state: ~\n\n# training settings\ntrain:\n  ema_decay: 0.999\n  optim_g:\n    type: Adam\n    lr: !!float 1e-4\n    weight_decay: 0\n    betas: [0.9, 0.99]\n  optim_d:\n    type: Adam\n    lr: !!float 1e-4\n    weight_decay: 0\n    betas: [0.9, 0.99]\n\n  scheduler:\n    type: MultiStepLR\n    milestones: [400000]\n    gamma: 0.5\n\n  total_iter: 400000\n  warmup_iter: -1  # no warm up\n\n  # losses\n  pixel_opt:\n    type: L1Loss\n    loss_weight: 1.0\n    reduction: mean\n  # perceptual loss (content and style losses)\n  perceptual_opt:\n    type: PerceptualLoss\n    layer_weights:\n      # before relu\n      'conv1_2': 0.1\n      'conv2_2': 0.1\n      'conv3_4': 1\n      'conv4_4': 1\n      'conv5_4': 1\n    vgg_type: vgg19\n    use_input_norm: true\n    perceptual_weight: !!float 1.0\n    style_weight: 0\n    range_norm: false\n    criterion: l1\n  # gan loss\n  gan_opt:\n    type: GANLoss\n    gan_type: vanilla\n    real_label_val: 1.0\n    fake_label_val: 0.0\n    loss_weight: !!float 1e-1\n\n  net_d_iters: 1\n  net_d_init_iters: 0\n\n# Uncomment these for validation\n# validation settings\n# val:\n#   val_freq: !!float 5e3\n#   save_img: True\n\n#   metrics:\n#     psnr: # metric name\n#       type: calculate_psnr\n#       crop_border: 4\n#       test_y_channel: false\n\n# logging settings\nlogger:\n  print_freq: 100\n  save_checkpoint_freq: !!float 5e3\n  use_tb_logger: true\n  wandb:\n    project: ~\n    resume_id: ~\n\n# dist training settings\ndist_params:\n  backend: nccl\n  port: 29500\n"
  },
  {
    "path": "options/train_realesrgan_x4plus.yml",
    "content": "# general settings\nname: train_RealESRGANx4plus_400k_B12G4\nmodel_type: RealESRGANModel\nscale: 4\nnum_gpu: auto  # auto: can infer from your visible devices automatically. official: 4 GPUs\nmanual_seed: 0\n\n# ----------------- options for synthesizing training data in RealESRGANModel ----------------- #\n# USM the ground-truth\nl1_gt_usm: True\npercep_gt_usm: True\ngan_gt_usm: False\n\n# the first degradation process\nresize_prob: [0.2, 0.7, 0.1]  # up, down, keep\nresize_range: [0.15, 1.5]\ngaussian_noise_prob: 0.5\nnoise_range: [1, 30]\npoisson_scale_range: [0.05, 3]\ngray_noise_prob: 0.4\njpeg_range: [30, 95]\n\n# the second degradation process\nsecond_blur_prob: 0.8\nresize_prob2: [0.3, 0.4, 0.3]  # up, down, keep\nresize_range2: [0.3, 1.2]\ngaussian_noise_prob2: 0.5\nnoise_range2: [1, 25]\npoisson_scale_range2: [0.05, 2.5]\ngray_noise_prob2: 0.4\njpeg_range2: [30, 95]\n\ngt_size: 256\nqueue_size: 180\n\n# dataset and data loader settings\ndatasets:\n  train:\n    name: DF2K+OST\n    type: RealESRGANDataset\n    dataroot_gt: datasets/DF2K\n    meta_info: datasets/DF2K/meta_info/meta_info_DF2Kmultiscale+OST_sub.txt\n    io_backend:\n      type: disk\n\n    blur_kernel_size: 21\n    kernel_list: ['iso', 'aniso', 'generalized_iso', 'generalized_aniso', 'plateau_iso', 'plateau_aniso']\n    kernel_prob: [0.45, 0.25, 0.12, 0.03, 0.12, 0.03]\n    sinc_prob: 0.1\n    blur_sigma: [0.2, 3]\n    betag_range: [0.5, 4]\n    betap_range: [1, 2]\n\n    blur_kernel_size2: 21\n    kernel_list2: ['iso', 'aniso', 'generalized_iso', 'generalized_aniso', 'plateau_iso', 'plateau_aniso']\n    kernel_prob2: [0.45, 0.25, 0.12, 0.03, 0.12, 0.03]\n    sinc_prob2: 0.1\n    blur_sigma2: [0.2, 1.5]\n    betag_range2: [0.5, 4]\n    betap_range2: [1, 2]\n\n    final_sinc_prob: 0.8\n\n    gt_size: 256\n    use_hflip: True\n    use_rot: False\n\n    # data loader\n    use_shuffle: true\n    num_worker_per_gpu: 5\n    batch_size_per_gpu: 12\n    dataset_enlarge_ratio: 1\n    prefetch_mode: ~\n\n  # Uncomment these for validation\n  # val:\n  #   name: validation\n  #   type: PairedImageDataset\n  #   dataroot_gt: path_to_gt\n  #   dataroot_lq: path_to_lq\n  #   io_backend:\n  #     type: disk\n\n# network structures\nnetwork_g:\n  type: RRDBNet\n  num_in_ch: 3\n  num_out_ch: 3\n  num_feat: 64\n  num_block: 23\n  num_grow_ch: 32\n\nnetwork_d:\n  type: UNetDiscriminatorSN\n  num_in_ch: 3\n  num_feat: 64\n  skip_connection: True\n\n# path\npath:\n  # use the pre-trained Real-ESRNet model\n  pretrain_network_g: experiments/pretrained_models/RealESRNet_x4plus.pth\n  param_key_g: params_ema\n  strict_load_g: true\n  resume_state: ~\n\n# training settings\ntrain:\n  ema_decay: 0.999\n  optim_g:\n    type: Adam\n    lr: !!float 1e-4\n    weight_decay: 0\n    betas: [0.9, 0.99]\n  optim_d:\n    type: Adam\n    lr: !!float 1e-4\n    weight_decay: 0\n    betas: [0.9, 0.99]\n\n  scheduler:\n    type: MultiStepLR\n    milestones: [400000]\n    gamma: 0.5\n\n  total_iter: 400000\n  warmup_iter: -1  # no warm up\n\n  # losses\n  pixel_opt:\n    type: L1Loss\n    loss_weight: 1.0\n    reduction: mean\n  # perceptual loss (content and style losses)\n  perceptual_opt:\n    type: PerceptualLoss\n    layer_weights:\n      # before relu\n      'conv1_2': 0.1\n      'conv2_2': 0.1\n      'conv3_4': 1\n      'conv4_4': 1\n      'conv5_4': 1\n    vgg_type: vgg19\n    use_input_norm: true\n    perceptual_weight: !!float 1.0\n    style_weight: 0\n    range_norm: false\n    criterion: l1\n  # gan loss\n  gan_opt:\n    type: GANLoss\n    gan_type: vanilla\n    real_label_val: 1.0\n    fake_label_val: 0.0\n    loss_weight: !!float 1e-1\n\n  net_d_iters: 1\n  net_d_init_iters: 0\n\n# Uncomment these for validation\n# validation settings\n# val:\n#   val_freq: !!float 5e3\n#   save_img: True\n\n#   metrics:\n#     psnr: # metric name\n#       type: calculate_psnr\n#       crop_border: 4\n#       test_y_channel: false\n\n# logging settings\nlogger:\n  print_freq: 100\n  save_checkpoint_freq: !!float 5e3\n  use_tb_logger: true\n  wandb:\n    project: ~\n    resume_id: ~\n\n# dist training settings\ndist_params:\n  backend: nccl\n  port: 29500\n"
  },
  {
    "path": "options/train_realesrnet_x2plus.yml",
    "content": "# general settings\nname: train_RealESRNetx2plus_1000k_B12G4\nmodel_type: RealESRNetModel\nscale: 2\nnum_gpu: auto  # auto: can infer from your visible devices automatically. official: 4 GPUs\nmanual_seed: 0\n\n# ----------------- options for synthesizing training data in RealESRNetModel ----------------- #\ngt_usm: True  # USM the ground-truth\n\n# the first degradation process\nresize_prob: [0.2, 0.7, 0.1]  # up, down, keep\nresize_range: [0.15, 1.5]\ngaussian_noise_prob: 0.5\nnoise_range: [1, 30]\npoisson_scale_range: [0.05, 3]\ngray_noise_prob: 0.4\njpeg_range: [30, 95]\n\n# the second degradation process\nsecond_blur_prob: 0.8\nresize_prob2: [0.3, 0.4, 0.3]  # up, down, keep\nresize_range2: [0.3, 1.2]\ngaussian_noise_prob2: 0.5\nnoise_range2: [1, 25]\npoisson_scale_range2: [0.05, 2.5]\ngray_noise_prob2: 0.4\njpeg_range2: [30, 95]\n\ngt_size: 256\nqueue_size: 180\n\n# dataset and data loader settings\ndatasets:\n  train:\n    name: DF2K+OST\n    type: RealESRGANDataset\n    dataroot_gt: datasets/DF2K\n    meta_info: datasets/DF2K/meta_info/meta_info_DF2Kmultiscale+OST_sub.txt\n    io_backend:\n      type: disk\n\n    blur_kernel_size: 21\n    kernel_list: ['iso', 'aniso', 'generalized_iso', 'generalized_aniso', 'plateau_iso', 'plateau_aniso']\n    kernel_prob: [0.45, 0.25, 0.12, 0.03, 0.12, 0.03]\n    sinc_prob: 0.1\n    blur_sigma: [0.2, 3]\n    betag_range: [0.5, 4]\n    betap_range: [1, 2]\n\n    blur_kernel_size2: 21\n    kernel_list2: ['iso', 'aniso', 'generalized_iso', 'generalized_aniso', 'plateau_iso', 'plateau_aniso']\n    kernel_prob2: [0.45, 0.25, 0.12, 0.03, 0.12, 0.03]\n    sinc_prob2: 0.1\n    blur_sigma2: [0.2, 1.5]\n    betag_range2: [0.5, 4]\n    betap_range2: [1, 2]\n\n    final_sinc_prob: 0.8\n\n    gt_size: 256\n    use_hflip: True\n    use_rot: False\n\n    # data loader\n    use_shuffle: true\n    num_worker_per_gpu: 5\n    batch_size_per_gpu: 12\n    dataset_enlarge_ratio: 1\n    prefetch_mode: ~\n\n  # Uncomment these for validation\n  # val:\n  #   name: validation\n  #   type: PairedImageDataset\n  #   dataroot_gt: path_to_gt\n  #   dataroot_lq: path_to_lq\n  #   io_backend:\n  #     type: disk\n\n# network structures\nnetwork_g:\n  type: RRDBNet\n  num_in_ch: 3\n  num_out_ch: 3\n  num_feat: 64\n  num_block: 23\n  num_grow_ch: 32\n  scale: 2\n\n# path\npath:\n  pretrain_network_g: experiments/pretrained_models/RealESRGAN_x4plus.pth\n  param_key_g: params_ema\n  strict_load_g: False\n  resume_state: ~\n\n# training settings\ntrain:\n  ema_decay: 0.999\n  optim_g:\n    type: Adam\n    lr: !!float 2e-4\n    weight_decay: 0\n    betas: [0.9, 0.99]\n\n  scheduler:\n    type: MultiStepLR\n    milestones: [1000000]\n    gamma: 0.5\n\n  total_iter: 1000000\n  warmup_iter: -1  # no warm up\n\n  # losses\n  pixel_opt:\n    type: L1Loss\n    loss_weight: 1.0\n    reduction: mean\n\n# Uncomment these for validation\n# validation settings\n# val:\n#   val_freq: !!float 5e3\n#   save_img: True\n\n#   metrics:\n#     psnr: # metric name\n#       type: calculate_psnr\n#       crop_border: 4\n#       test_y_channel: false\n\n# logging settings\nlogger:\n  print_freq: 100\n  save_checkpoint_freq: !!float 5e3\n  use_tb_logger: true\n  wandb:\n    project: ~\n    resume_id: ~\n\n# dist training settings\ndist_params:\n  backend: nccl\n  port: 29500\n"
  },
  {
    "path": "options/train_realesrnet_x4plus.yml",
    "content": "# general settings\nname: train_RealESRNetx4plus_1000k_B12G4\nmodel_type: RealESRNetModel\nscale: 4\nnum_gpu: auto  # auto: can infer from your visible devices automatically. official: 4 GPUs\nmanual_seed: 0\n\n# ----------------- options for synthesizing training data in RealESRNetModel ----------------- #\ngt_usm: True  # USM the ground-truth\n\n# the first degradation process\nresize_prob: [0.2, 0.7, 0.1]  # up, down, keep\nresize_range: [0.15, 1.5]\ngaussian_noise_prob: 0.5\nnoise_range: [1, 30]\npoisson_scale_range: [0.05, 3]\ngray_noise_prob: 0.4\njpeg_range: [30, 95]\n\n# the second degradation process\nsecond_blur_prob: 0.8\nresize_prob2: [0.3, 0.4, 0.3]  # up, down, keep\nresize_range2: [0.3, 1.2]\ngaussian_noise_prob2: 0.5\nnoise_range2: [1, 25]\npoisson_scale_range2: [0.05, 2.5]\ngray_noise_prob2: 0.4\njpeg_range2: [30, 95]\n\ngt_size: 256\nqueue_size: 180\n\n# dataset and data loader settings\ndatasets:\n  train:\n    name: DF2K+OST\n    type: RealESRGANDataset\n    dataroot_gt: datasets/DF2K\n    meta_info: datasets/DF2K/meta_info/meta_info_DF2Kmultiscale+OST_sub.txt\n    io_backend:\n      type: disk\n\n    blur_kernel_size: 21\n    kernel_list: ['iso', 'aniso', 'generalized_iso', 'generalized_aniso', 'plateau_iso', 'plateau_aniso']\n    kernel_prob: [0.45, 0.25, 0.12, 0.03, 0.12, 0.03]\n    sinc_prob: 0.1\n    blur_sigma: [0.2, 3]\n    betag_range: [0.5, 4]\n    betap_range: [1, 2]\n\n    blur_kernel_size2: 21\n    kernel_list2: ['iso', 'aniso', 'generalized_iso', 'generalized_aniso', 'plateau_iso', 'plateau_aniso']\n    kernel_prob2: [0.45, 0.25, 0.12, 0.03, 0.12, 0.03]\n    sinc_prob2: 0.1\n    blur_sigma2: [0.2, 1.5]\n    betag_range2: [0.5, 4]\n    betap_range2: [1, 2]\n\n    final_sinc_prob: 0.8\n\n    gt_size: 256\n    use_hflip: True\n    use_rot: False\n\n    # data loader\n    use_shuffle: true\n    num_worker_per_gpu: 5\n    batch_size_per_gpu: 12\n    dataset_enlarge_ratio: 1\n    prefetch_mode: ~\n\n  # Uncomment these for validation\n  # val:\n  #   name: validation\n  #   type: PairedImageDataset\n  #   dataroot_gt: path_to_gt\n  #   dataroot_lq: path_to_lq\n  #   io_backend:\n  #     type: disk\n\n# network structures\nnetwork_g:\n  type: RRDBNet\n  num_in_ch: 3\n  num_out_ch: 3\n  num_feat: 64\n  num_block: 23\n  num_grow_ch: 32\n\n# path\npath:\n  pretrain_network_g: experiments/pretrained_models/ESRGAN_SRx4_DF2KOST_official-ff704c30.pth\n  param_key_g: params_ema\n  strict_load_g: true\n  resume_state: ~\n\n# training settings\ntrain:\n  ema_decay: 0.999\n  optim_g:\n    type: Adam\n    lr: !!float 2e-4\n    weight_decay: 0\n    betas: [0.9, 0.99]\n\n  scheduler:\n    type: MultiStepLR\n    milestones: [1000000]\n    gamma: 0.5\n\n  total_iter: 1000000\n  warmup_iter: -1  # no warm up\n\n  # losses\n  pixel_opt:\n    type: L1Loss\n    loss_weight: 1.0\n    reduction: mean\n\n# Uncomment these for validation\n# validation settings\n# val:\n#   val_freq: !!float 5e3\n#   save_img: True\n\n#   metrics:\n#     psnr: # metric name\n#       type: calculate_psnr\n#       crop_border: 4\n#       test_y_channel: false\n\n# logging settings\nlogger:\n  print_freq: 100\n  save_checkpoint_freq: !!float 5e3\n  use_tb_logger: true\n  wandb:\n    project: ~\n    resume_id: ~\n\n# dist training settings\ndist_params:\n  backend: nccl\n  port: 29500\n"
  },
  {
    "path": "realesrgan/__init__.py",
    "content": "# flake8: noqa\nfrom .archs import *\nfrom .data import *\nfrom .models import *\nfrom .utils import *\nfrom .version import *\n"
  },
  {
    "path": "realesrgan/archs/__init__.py",
    "content": "import importlib\nfrom basicsr.utils import scandir\nfrom os import path as osp\n\n# automatically scan and import arch modules for registry\n# scan all the files that end with '_arch.py' under the archs folder\narch_folder = osp.dirname(osp.abspath(__file__))\narch_filenames = [osp.splitext(osp.basename(v))[0] for v in scandir(arch_folder) if v.endswith('_arch.py')]\n# import all the arch modules\n_arch_modules = [importlib.import_module(f'realesrgan.archs.{file_name}') for file_name in arch_filenames]\n"
  },
  {
    "path": "realesrgan/archs/discriminator_arch.py",
    "content": "from basicsr.utils.registry import ARCH_REGISTRY\nfrom torch import nn as nn\nfrom torch.nn import functional as F\nfrom torch.nn.utils import spectral_norm\n\n\n@ARCH_REGISTRY.register()\nclass UNetDiscriminatorSN(nn.Module):\n    \"\"\"Defines a U-Net discriminator with spectral normalization (SN)\n\n    It is used in Real-ESRGAN: Training Real-World Blind Super-Resolution with Pure Synthetic Data.\n\n    Arg:\n        num_in_ch (int): Channel number of inputs. Default: 3.\n        num_feat (int): Channel number of base intermediate features. Default: 64.\n        skip_connection (bool): Whether to use skip connections between U-Net. Default: True.\n    \"\"\"\n\n    def __init__(self, num_in_ch, num_feat=64, skip_connection=True):\n        super(UNetDiscriminatorSN, self).__init__()\n        self.skip_connection = skip_connection\n        norm = spectral_norm\n        # the first convolution\n        self.conv0 = nn.Conv2d(num_in_ch, num_feat, kernel_size=3, stride=1, padding=1)\n        # downsample\n        self.conv1 = norm(nn.Conv2d(num_feat, num_feat * 2, 4, 2, 1, bias=False))\n        self.conv2 = norm(nn.Conv2d(num_feat * 2, num_feat * 4, 4, 2, 1, bias=False))\n        self.conv3 = norm(nn.Conv2d(num_feat * 4, num_feat * 8, 4, 2, 1, bias=False))\n        # upsample\n        self.conv4 = norm(nn.Conv2d(num_feat * 8, num_feat * 4, 3, 1, 1, bias=False))\n        self.conv5 = norm(nn.Conv2d(num_feat * 4, num_feat * 2, 3, 1, 1, bias=False))\n        self.conv6 = norm(nn.Conv2d(num_feat * 2, num_feat, 3, 1, 1, bias=False))\n        # extra convolutions\n        self.conv7 = norm(nn.Conv2d(num_feat, num_feat, 3, 1, 1, bias=False))\n        self.conv8 = norm(nn.Conv2d(num_feat, num_feat, 3, 1, 1, bias=False))\n        self.conv9 = nn.Conv2d(num_feat, 1, 3, 1, 1)\n\n    def forward(self, x):\n        # downsample\n        x0 = F.leaky_relu(self.conv0(x), negative_slope=0.2, inplace=True)\n        x1 = F.leaky_relu(self.conv1(x0), negative_slope=0.2, inplace=True)\n        x2 = F.leaky_relu(self.conv2(x1), negative_slope=0.2, inplace=True)\n        x3 = F.leaky_relu(self.conv3(x2), negative_slope=0.2, inplace=True)\n\n        # upsample\n        x3 = F.interpolate(x3, scale_factor=2, mode='bilinear', align_corners=False)\n        x4 = F.leaky_relu(self.conv4(x3), negative_slope=0.2, inplace=True)\n\n        if self.skip_connection:\n            x4 = x4 + x2\n        x4 = F.interpolate(x4, scale_factor=2, mode='bilinear', align_corners=False)\n        x5 = F.leaky_relu(self.conv5(x4), negative_slope=0.2, inplace=True)\n\n        if self.skip_connection:\n            x5 = x5 + x1\n        x5 = F.interpolate(x5, scale_factor=2, mode='bilinear', align_corners=False)\n        x6 = F.leaky_relu(self.conv6(x5), negative_slope=0.2, inplace=True)\n\n        if self.skip_connection:\n            x6 = x6 + x0\n\n        # extra convolutions\n        out = F.leaky_relu(self.conv7(x6), negative_slope=0.2, inplace=True)\n        out = F.leaky_relu(self.conv8(out), negative_slope=0.2, inplace=True)\n        out = self.conv9(out)\n\n        return out\n"
  },
  {
    "path": "realesrgan/archs/srvgg_arch.py",
    "content": "from basicsr.utils.registry import ARCH_REGISTRY\nfrom torch import nn as nn\nfrom torch.nn import functional as F\n\n\n@ARCH_REGISTRY.register()\nclass SRVGGNetCompact(nn.Module):\n    \"\"\"A compact VGG-style network structure for super-resolution.\n\n    It is a compact network structure, which performs upsampling in the last layer and no convolution is\n    conducted on the HR feature space.\n\n    Args:\n        num_in_ch (int): Channel number of inputs. Default: 3.\n        num_out_ch (int): Channel number of outputs. Default: 3.\n        num_feat (int): Channel number of intermediate features. Default: 64.\n        num_conv (int): Number of convolution layers in the body network. Default: 16.\n        upscale (int): Upsampling factor. Default: 4.\n        act_type (str): Activation type, options: 'relu', 'prelu', 'leakyrelu'. Default: prelu.\n    \"\"\"\n\n    def __init__(self, num_in_ch=3, num_out_ch=3, num_feat=64, num_conv=16, upscale=4, act_type='prelu'):\n        super(SRVGGNetCompact, self).__init__()\n        self.num_in_ch = num_in_ch\n        self.num_out_ch = num_out_ch\n        self.num_feat = num_feat\n        self.num_conv = num_conv\n        self.upscale = upscale\n        self.act_type = act_type\n\n        self.body = nn.ModuleList()\n        # the first conv\n        self.body.append(nn.Conv2d(num_in_ch, num_feat, 3, 1, 1))\n        # the first activation\n        if act_type == 'relu':\n            activation = nn.ReLU(inplace=True)\n        elif act_type == 'prelu':\n            activation = nn.PReLU(num_parameters=num_feat)\n        elif act_type == 'leakyrelu':\n            activation = nn.LeakyReLU(negative_slope=0.1, inplace=True)\n        self.body.append(activation)\n\n        # the body structure\n        for _ in range(num_conv):\n            self.body.append(nn.Conv2d(num_feat, num_feat, 3, 1, 1))\n            # activation\n            if act_type == 'relu':\n                activation = nn.ReLU(inplace=True)\n            elif act_type == 'prelu':\n                activation = nn.PReLU(num_parameters=num_feat)\n            elif act_type == 'leakyrelu':\n                activation = nn.LeakyReLU(negative_slope=0.1, inplace=True)\n            self.body.append(activation)\n\n        # the last conv\n        self.body.append(nn.Conv2d(num_feat, num_out_ch * upscale * upscale, 3, 1, 1))\n        # upsample\n        self.upsampler = nn.PixelShuffle(upscale)\n\n    def forward(self, x):\n        out = x\n        for i in range(0, len(self.body)):\n            out = self.body[i](out)\n\n        out = self.upsampler(out)\n        # add the nearest upsampled image, so that the network learns the residual\n        base = F.interpolate(x, scale_factor=self.upscale, mode='nearest')\n        out += base\n        return out\n"
  },
  {
    "path": "realesrgan/data/__init__.py",
    "content": "import importlib\nfrom basicsr.utils import scandir\nfrom os import path as osp\n\n# automatically scan and import dataset modules for registry\n# scan all the files that end with '_dataset.py' under the data folder\ndata_folder = osp.dirname(osp.abspath(__file__))\ndataset_filenames = [osp.splitext(osp.basename(v))[0] for v in scandir(data_folder) if v.endswith('_dataset.py')]\n# import all the dataset modules\n_dataset_modules = [importlib.import_module(f'realesrgan.data.{file_name}') for file_name in dataset_filenames]\n"
  },
  {
    "path": "realesrgan/data/realesrgan_dataset.py",
    "content": "import cv2\nimport math\nimport numpy as np\nimport os\nimport os.path as osp\nimport random\nimport time\nimport torch\nfrom basicsr.data.degradations import circular_lowpass_kernel, random_mixed_kernels\nfrom basicsr.data.transforms import augment\nfrom basicsr.utils import FileClient, get_root_logger, imfrombytes, img2tensor\nfrom basicsr.utils.registry import DATASET_REGISTRY\nfrom torch.utils import data as data\n\n\n@DATASET_REGISTRY.register()\nclass RealESRGANDataset(data.Dataset):\n    \"\"\"Dataset used for Real-ESRGAN model:\n    Real-ESRGAN: Training Real-World Blind Super-Resolution with Pure Synthetic Data.\n\n    It loads gt (Ground-Truth) images, and augments them.\n    It also generates blur kernels and sinc kernels for generating low-quality images.\n    Note that the low-quality images are processed in tensors on GPUS for faster processing.\n\n    Args:\n        opt (dict): Config for train datasets. It contains the following keys:\n            dataroot_gt (str): Data root path for gt.\n            meta_info (str): Path for meta information file.\n            io_backend (dict): IO backend type and other kwarg.\n            use_hflip (bool): Use horizontal flips.\n            use_rot (bool): Use rotation (use vertical flip and transposing h and w for implementation).\n            Please see more options in the codes.\n    \"\"\"\n\n    def __init__(self, opt):\n        super(RealESRGANDataset, self).__init__()\n        self.opt = opt\n        self.file_client = None\n        self.io_backend_opt = opt['io_backend']\n        self.gt_folder = opt['dataroot_gt']\n\n        # file client (lmdb io backend)\n        if self.io_backend_opt['type'] == 'lmdb':\n            self.io_backend_opt['db_paths'] = [self.gt_folder]\n            self.io_backend_opt['client_keys'] = ['gt']\n            if not self.gt_folder.endswith('.lmdb'):\n                raise ValueError(f\"'dataroot_gt' should end with '.lmdb', but received {self.gt_folder}\")\n            with open(osp.join(self.gt_folder, 'meta_info.txt')) as fin:\n                self.paths = [line.split('.')[0] for line in fin]\n        else:\n            # disk backend with meta_info\n            # Each line in the meta_info describes the relative path to an image\n            with open(self.opt['meta_info']) as fin:\n                paths = [line.strip().split(' ')[0] for line in fin]\n                self.paths = [os.path.join(self.gt_folder, v) for v in paths]\n\n        # blur settings for the first degradation\n        self.blur_kernel_size = opt['blur_kernel_size']\n        self.kernel_list = opt['kernel_list']\n        self.kernel_prob = opt['kernel_prob']  # a list for each kernel probability\n        self.blur_sigma = opt['blur_sigma']\n        self.betag_range = opt['betag_range']  # betag used in generalized Gaussian blur kernels\n        self.betap_range = opt['betap_range']  # betap used in plateau blur kernels\n        self.sinc_prob = opt['sinc_prob']  # the probability for sinc filters\n\n        # blur settings for the second degradation\n        self.blur_kernel_size2 = opt['blur_kernel_size2']\n        self.kernel_list2 = opt['kernel_list2']\n        self.kernel_prob2 = opt['kernel_prob2']\n        self.blur_sigma2 = opt['blur_sigma2']\n        self.betag_range2 = opt['betag_range2']\n        self.betap_range2 = opt['betap_range2']\n        self.sinc_prob2 = opt['sinc_prob2']\n\n        # a final sinc filter\n        self.final_sinc_prob = opt['final_sinc_prob']\n\n        self.kernel_range = [2 * v + 1 for v in range(3, 11)]  # kernel size ranges from 7 to 21\n        # TODO: kernel range is now hard-coded, should be in the configure file\n        self.pulse_tensor = torch.zeros(21, 21).float()  # convolving with pulse tensor brings no blurry effect\n        self.pulse_tensor[10, 10] = 1\n\n    def __getitem__(self, index):\n        if self.file_client is None:\n            self.file_client = FileClient(self.io_backend_opt.pop('type'), **self.io_backend_opt)\n\n        # -------------------------------- Load gt images -------------------------------- #\n        # Shape: (h, w, c); channel order: BGR; image range: [0, 1], float32.\n        gt_path = self.paths[index]\n        # avoid errors caused by high latency in reading files\n        retry = 3\n        while retry > 0:\n            try:\n                img_bytes = self.file_client.get(gt_path, 'gt')\n            except (IOError, OSError) as e:\n                logger = get_root_logger()\n                logger.warn(f'File client error: {e}, remaining retry times: {retry - 1}')\n                # change another file to read\n                index = random.randint(0, self.__len__())\n                gt_path = self.paths[index]\n                time.sleep(1)  # sleep 1s for occasional server congestion\n            else:\n                break\n            finally:\n                retry -= 1\n        img_gt = imfrombytes(img_bytes, float32=True)\n\n        # -------------------- Do augmentation for training: flip, rotation -------------------- #\n        img_gt = augment(img_gt, self.opt['use_hflip'], self.opt['use_rot'])\n\n        # crop or pad to 400\n        # TODO: 400 is hard-coded. You may change it accordingly\n        h, w = img_gt.shape[0:2]\n        crop_pad_size = 400\n        # pad\n        if h < crop_pad_size or w < crop_pad_size:\n            pad_h = max(0, crop_pad_size - h)\n            pad_w = max(0, crop_pad_size - w)\n            img_gt = cv2.copyMakeBorder(img_gt, 0, pad_h, 0, pad_w, cv2.BORDER_REFLECT_101)\n        # crop\n        if img_gt.shape[0] > crop_pad_size or img_gt.shape[1] > crop_pad_size:\n            h, w = img_gt.shape[0:2]\n            # randomly choose top and left coordinates\n            top = random.randint(0, h - crop_pad_size)\n            left = random.randint(0, w - crop_pad_size)\n            img_gt = img_gt[top:top + crop_pad_size, left:left + crop_pad_size, ...]\n\n        # ------------------------ Generate kernels (used in the first degradation) ------------------------ #\n        kernel_size = random.choice(self.kernel_range)\n        if np.random.uniform() < self.opt['sinc_prob']:\n            # this sinc filter setting is for kernels ranging from [7, 21]\n            if kernel_size < 13:\n                omega_c = np.random.uniform(np.pi / 3, np.pi)\n            else:\n                omega_c = np.random.uniform(np.pi / 5, np.pi)\n            kernel = circular_lowpass_kernel(omega_c, kernel_size, pad_to=False)\n        else:\n            kernel = random_mixed_kernels(\n                self.kernel_list,\n                self.kernel_prob,\n                kernel_size,\n                self.blur_sigma,\n                self.blur_sigma, [-math.pi, math.pi],\n                self.betag_range,\n                self.betap_range,\n                noise_range=None)\n        # pad kernel\n        pad_size = (21 - kernel_size) // 2\n        kernel = np.pad(kernel, ((pad_size, pad_size), (pad_size, pad_size)))\n\n        # ------------------------ Generate kernels (used in the second degradation) ------------------------ #\n        kernel_size = random.choice(self.kernel_range)\n        if np.random.uniform() < self.opt['sinc_prob2']:\n            if kernel_size < 13:\n                omega_c = np.random.uniform(np.pi / 3, np.pi)\n            else:\n                omega_c = np.random.uniform(np.pi / 5, np.pi)\n            kernel2 = circular_lowpass_kernel(omega_c, kernel_size, pad_to=False)\n        else:\n            kernel2 = random_mixed_kernels(\n                self.kernel_list2,\n                self.kernel_prob2,\n                kernel_size,\n                self.blur_sigma2,\n                self.blur_sigma2, [-math.pi, math.pi],\n                self.betag_range2,\n                self.betap_range2,\n                noise_range=None)\n\n        # pad kernel\n        pad_size = (21 - kernel_size) // 2\n        kernel2 = np.pad(kernel2, ((pad_size, pad_size), (pad_size, pad_size)))\n\n        # ------------------------------------- the final sinc kernel ------------------------------------- #\n        if np.random.uniform() < self.opt['final_sinc_prob']:\n            kernel_size = random.choice(self.kernel_range)\n            omega_c = np.random.uniform(np.pi / 3, np.pi)\n            sinc_kernel = circular_lowpass_kernel(omega_c, kernel_size, pad_to=21)\n            sinc_kernel = torch.FloatTensor(sinc_kernel)\n        else:\n            sinc_kernel = self.pulse_tensor\n\n        # BGR to RGB, HWC to CHW, numpy to tensor\n        img_gt = img2tensor([img_gt], bgr2rgb=True, float32=True)[0]\n        kernel = torch.FloatTensor(kernel)\n        kernel2 = torch.FloatTensor(kernel2)\n\n        return_d = {'gt': img_gt, 'kernel1': kernel, 'kernel2': kernel2, 'sinc_kernel': sinc_kernel, 'gt_path': gt_path}\n        return return_d\n\n    def __len__(self):\n        return len(self.paths)\n"
  },
  {
    "path": "realesrgan/data/realesrgan_paired_dataset.py",
    "content": "import os\nfrom basicsr.data.data_util import paired_paths_from_folder, paired_paths_from_lmdb\nfrom basicsr.data.transforms import augment, paired_random_crop\nfrom basicsr.utils import FileClient, imfrombytes, img2tensor\nfrom basicsr.utils.registry import DATASET_REGISTRY\nfrom torch.utils import data as data\nfrom torchvision.transforms.functional import normalize\n\n\n@DATASET_REGISTRY.register()\nclass RealESRGANPairedDataset(data.Dataset):\n    \"\"\"Paired image dataset for image restoration.\n\n    Read LQ (Low Quality, e.g. LR (Low Resolution), blurry, noisy, etc) and GT image pairs.\n\n    There are three modes:\n    1. 'lmdb': Use lmdb files.\n        If opt['io_backend'] == lmdb.\n    2. 'meta_info': Use meta information file to generate paths.\n        If opt['io_backend'] != lmdb and opt['meta_info'] is not None.\n    3. 'folder': Scan folders to generate paths.\n        The rest.\n\n    Args:\n        opt (dict): Config for train datasets. It contains the following keys:\n            dataroot_gt (str): Data root path for gt.\n            dataroot_lq (str): Data root path for lq.\n            meta_info (str): Path for meta information file.\n            io_backend (dict): IO backend type and other kwarg.\n            filename_tmpl (str): Template for each filename. Note that the template excludes the file extension.\n                Default: '{}'.\n            gt_size (int): Cropped patched size for gt patches.\n            use_hflip (bool): Use horizontal flips.\n            use_rot (bool): Use rotation (use vertical flip and transposing h\n                and w for implementation).\n\n            scale (bool): Scale, which will be added automatically.\n            phase (str): 'train' or 'val'.\n    \"\"\"\n\n    def __init__(self, opt):\n        super(RealESRGANPairedDataset, self).__init__()\n        self.opt = opt\n        self.file_client = None\n        self.io_backend_opt = opt['io_backend']\n        # mean and std for normalizing the input images\n        self.mean = opt['mean'] if 'mean' in opt else None\n        self.std = opt['std'] if 'std' in opt else None\n\n        self.gt_folder, self.lq_folder = opt['dataroot_gt'], opt['dataroot_lq']\n        self.filename_tmpl = opt['filename_tmpl'] if 'filename_tmpl' in opt else '{}'\n\n        # file client (lmdb io backend)\n        if self.io_backend_opt['type'] == 'lmdb':\n            self.io_backend_opt['db_paths'] = [self.lq_folder, self.gt_folder]\n            self.io_backend_opt['client_keys'] = ['lq', 'gt']\n            self.paths = paired_paths_from_lmdb([self.lq_folder, self.gt_folder], ['lq', 'gt'])\n        elif 'meta_info' in self.opt and self.opt['meta_info'] is not None:\n            # disk backend with meta_info\n            # Each line in the meta_info describes the relative path to an image\n            with open(self.opt['meta_info']) as fin:\n                paths = [line.strip() for line in fin]\n            self.paths = []\n            for path in paths:\n                gt_path, lq_path = path.split(', ')\n                gt_path = os.path.join(self.gt_folder, gt_path)\n                lq_path = os.path.join(self.lq_folder, lq_path)\n                self.paths.append(dict([('gt_path', gt_path), ('lq_path', lq_path)]))\n        else:\n            # disk backend\n            # it will scan the whole folder to get meta info\n            # it will be time-consuming for folders with too many files. It is recommended using an extra meta txt file\n            self.paths = paired_paths_from_folder([self.lq_folder, self.gt_folder], ['lq', 'gt'], self.filename_tmpl)\n\n    def __getitem__(self, index):\n        if self.file_client is None:\n            self.file_client = FileClient(self.io_backend_opt.pop('type'), **self.io_backend_opt)\n\n        scale = self.opt['scale']\n\n        # Load gt and lq images. Dimension order: HWC; channel order: BGR;\n        # image range: [0, 1], float32.\n        gt_path = self.paths[index]['gt_path']\n        img_bytes = self.file_client.get(gt_path, 'gt')\n        img_gt = imfrombytes(img_bytes, float32=True)\n        lq_path = self.paths[index]['lq_path']\n        img_bytes = self.file_client.get(lq_path, 'lq')\n        img_lq = imfrombytes(img_bytes, float32=True)\n\n        # augmentation for training\n        if self.opt['phase'] == 'train':\n            gt_size = self.opt['gt_size']\n            # random crop\n            img_gt, img_lq = paired_random_crop(img_gt, img_lq, gt_size, scale, gt_path)\n            # flip, rotation\n            img_gt, img_lq = augment([img_gt, img_lq], self.opt['use_hflip'], self.opt['use_rot'])\n\n        # BGR to RGB, HWC to CHW, numpy to tensor\n        img_gt, img_lq = img2tensor([img_gt, img_lq], bgr2rgb=True, float32=True)\n        # normalize\n        if self.mean is not None or self.std is not None:\n            normalize(img_lq, self.mean, self.std, inplace=True)\n            normalize(img_gt, self.mean, self.std, inplace=True)\n\n        return {'lq': img_lq, 'gt': img_gt, 'lq_path': lq_path, 'gt_path': gt_path}\n\n    def __len__(self):\n        return len(self.paths)\n"
  },
  {
    "path": "realesrgan/models/__init__.py",
    "content": "import importlib\nfrom basicsr.utils import scandir\nfrom os import path as osp\n\n# automatically scan and import model modules for registry\n# scan all the files that end with '_model.py' under the model folder\nmodel_folder = osp.dirname(osp.abspath(__file__))\nmodel_filenames = [osp.splitext(osp.basename(v))[0] for v in scandir(model_folder) if v.endswith('_model.py')]\n# import all the model modules\n_model_modules = [importlib.import_module(f'realesrgan.models.{file_name}') for file_name in model_filenames]\n"
  },
  {
    "path": "realesrgan/models/realesrgan_model.py",
    "content": "import numpy as np\nimport random\nimport torch\nfrom basicsr.data.degradations import random_add_gaussian_noise_pt, random_add_poisson_noise_pt\nfrom basicsr.data.transforms import paired_random_crop\nfrom basicsr.models.srgan_model import SRGANModel\nfrom basicsr.utils import DiffJPEG, USMSharp\nfrom basicsr.utils.img_process_util import filter2D\nfrom basicsr.utils.registry import MODEL_REGISTRY\nfrom collections import OrderedDict\nfrom torch.nn import functional as F\n\n\n@MODEL_REGISTRY.register()\nclass RealESRGANModel(SRGANModel):\n    \"\"\"RealESRGAN Model for Real-ESRGAN: Training Real-World Blind Super-Resolution with Pure Synthetic Data.\n\n    It mainly performs:\n    1. randomly synthesize LQ images in GPU tensors\n    2. optimize the networks with GAN training.\n    \"\"\"\n\n    def __init__(self, opt):\n        super(RealESRGANModel, self).__init__(opt)\n        self.jpeger = DiffJPEG(differentiable=False).cuda()  # simulate JPEG compression artifacts\n        self.usm_sharpener = USMSharp().cuda()  # do usm sharpening\n        self.queue_size = opt.get('queue_size', 180)\n\n    @torch.no_grad()\n    def _dequeue_and_enqueue(self):\n        \"\"\"It is the training pair pool for increasing the diversity in a batch.\n\n        Batch processing limits the diversity of synthetic degradations in a batch. For example, samples in a\n        batch could not have different resize scaling factors. Therefore, we employ this training pair pool\n        to increase the degradation diversity in a batch.\n        \"\"\"\n        # initialize\n        b, c, h, w = self.lq.size()\n        if not hasattr(self, 'queue_lr'):\n            assert self.queue_size % b == 0, f'queue size {self.queue_size} should be divisible by batch size {b}'\n            self.queue_lr = torch.zeros(self.queue_size, c, h, w).cuda()\n            _, c, h, w = self.gt.size()\n            self.queue_gt = torch.zeros(self.queue_size, c, h, w).cuda()\n            self.queue_ptr = 0\n        if self.queue_ptr == self.queue_size:  # the pool is full\n            # do dequeue and enqueue\n            # shuffle\n            idx = torch.randperm(self.queue_size)\n            self.queue_lr = self.queue_lr[idx]\n            self.queue_gt = self.queue_gt[idx]\n            # get first b samples\n            lq_dequeue = self.queue_lr[0:b, :, :, :].clone()\n            gt_dequeue = self.queue_gt[0:b, :, :, :].clone()\n            # update the queue\n            self.queue_lr[0:b, :, :, :] = self.lq.clone()\n            self.queue_gt[0:b, :, :, :] = self.gt.clone()\n\n            self.lq = lq_dequeue\n            self.gt = gt_dequeue\n        else:\n            # only do enqueue\n            self.queue_lr[self.queue_ptr:self.queue_ptr + b, :, :, :] = self.lq.clone()\n            self.queue_gt[self.queue_ptr:self.queue_ptr + b, :, :, :] = self.gt.clone()\n            self.queue_ptr = self.queue_ptr + b\n\n    @torch.no_grad()\n    def feed_data(self, data):\n        \"\"\"Accept data from dataloader, and then add two-order degradations to obtain LQ images.\n        \"\"\"\n        if self.is_train and self.opt.get('high_order_degradation', True):\n            # training data synthesis\n            self.gt = data['gt'].to(self.device)\n            self.gt_usm = self.usm_sharpener(self.gt)\n\n            self.kernel1 = data['kernel1'].to(self.device)\n            self.kernel2 = data['kernel2'].to(self.device)\n            self.sinc_kernel = data['sinc_kernel'].to(self.device)\n\n            ori_h, ori_w = self.gt.size()[2:4]\n\n            # ----------------------- The first degradation process ----------------------- #\n            # blur\n            out = filter2D(self.gt_usm, self.kernel1)\n            # random resize\n            updown_type = random.choices(['up', 'down', 'keep'], self.opt['resize_prob'])[0]\n            if updown_type == 'up':\n                scale = np.random.uniform(1, self.opt['resize_range'][1])\n            elif updown_type == 'down':\n                scale = np.random.uniform(self.opt['resize_range'][0], 1)\n            else:\n                scale = 1\n            mode = random.choice(['area', 'bilinear', 'bicubic'])\n            out = F.interpolate(out, scale_factor=scale, mode=mode)\n            # add noise\n            gray_noise_prob = self.opt['gray_noise_prob']\n            if np.random.uniform() < self.opt['gaussian_noise_prob']:\n                out = random_add_gaussian_noise_pt(\n                    out, sigma_range=self.opt['noise_range'], clip=True, rounds=False, gray_prob=gray_noise_prob)\n            else:\n                out = random_add_poisson_noise_pt(\n                    out,\n                    scale_range=self.opt['poisson_scale_range'],\n                    gray_prob=gray_noise_prob,\n                    clip=True,\n                    rounds=False)\n            # JPEG compression\n            jpeg_p = out.new_zeros(out.size(0)).uniform_(*self.opt['jpeg_range'])\n            out = torch.clamp(out, 0, 1)  # clamp to [0, 1], otherwise JPEGer will result in unpleasant artifacts\n            out = self.jpeger(out, quality=jpeg_p)\n\n            # ----------------------- The second degradation process ----------------------- #\n            # blur\n            if np.random.uniform() < self.opt['second_blur_prob']:\n                out = filter2D(out, self.kernel2)\n            # random resize\n            updown_type = random.choices(['up', 'down', 'keep'], self.opt['resize_prob2'])[0]\n            if updown_type == 'up':\n                scale = np.random.uniform(1, self.opt['resize_range2'][1])\n            elif updown_type == 'down':\n                scale = np.random.uniform(self.opt['resize_range2'][0], 1)\n            else:\n                scale = 1\n            mode = random.choice(['area', 'bilinear', 'bicubic'])\n            out = F.interpolate(\n                out, size=(int(ori_h / self.opt['scale'] * scale), int(ori_w / self.opt['scale'] * scale)), mode=mode)\n            # add noise\n            gray_noise_prob = self.opt['gray_noise_prob2']\n            if np.random.uniform() < self.opt['gaussian_noise_prob2']:\n                out = random_add_gaussian_noise_pt(\n                    out, sigma_range=self.opt['noise_range2'], clip=True, rounds=False, gray_prob=gray_noise_prob)\n            else:\n                out = random_add_poisson_noise_pt(\n                    out,\n                    scale_range=self.opt['poisson_scale_range2'],\n                    gray_prob=gray_noise_prob,\n                    clip=True,\n                    rounds=False)\n\n            # JPEG compression + the final sinc filter\n            # We also need to resize images to desired sizes. We group [resize back + sinc filter] together\n            # as one operation.\n            # We consider two orders:\n            #   1. [resize back + sinc filter] + JPEG compression\n            #   2. JPEG compression + [resize back + sinc filter]\n            # Empirically, we find other combinations (sinc + JPEG + Resize) will introduce twisted lines.\n            if np.random.uniform() < 0.5:\n                # resize back + the final sinc filter\n                mode = random.choice(['area', 'bilinear', 'bicubic'])\n                out = F.interpolate(out, size=(ori_h // self.opt['scale'], ori_w // self.opt['scale']), mode=mode)\n                out = filter2D(out, self.sinc_kernel)\n                # JPEG compression\n                jpeg_p = out.new_zeros(out.size(0)).uniform_(*self.opt['jpeg_range2'])\n                out = torch.clamp(out, 0, 1)\n                out = self.jpeger(out, quality=jpeg_p)\n            else:\n                # JPEG compression\n                jpeg_p = out.new_zeros(out.size(0)).uniform_(*self.opt['jpeg_range2'])\n                out = torch.clamp(out, 0, 1)\n                out = self.jpeger(out, quality=jpeg_p)\n                # resize back + the final sinc filter\n                mode = random.choice(['area', 'bilinear', 'bicubic'])\n                out = F.interpolate(out, size=(ori_h // self.opt['scale'], ori_w // self.opt['scale']), mode=mode)\n                out = filter2D(out, self.sinc_kernel)\n\n            # clamp and round\n            self.lq = torch.clamp((out * 255.0).round(), 0, 255) / 255.\n\n            # random crop\n            gt_size = self.opt['gt_size']\n            (self.gt, self.gt_usm), self.lq = paired_random_crop([self.gt, self.gt_usm], self.lq, gt_size,\n                                                                 self.opt['scale'])\n\n            # training pair pool\n            self._dequeue_and_enqueue()\n            # sharpen self.gt again, as we have changed the self.gt with self._dequeue_and_enqueue\n            self.gt_usm = self.usm_sharpener(self.gt)\n            self.lq = self.lq.contiguous()  # for the warning: grad and param do not obey the gradient layout contract\n        else:\n            # for paired training or validation\n            self.lq = data['lq'].to(self.device)\n            if 'gt' in data:\n                self.gt = data['gt'].to(self.device)\n                self.gt_usm = self.usm_sharpener(self.gt)\n\n    def nondist_validation(self, dataloader, current_iter, tb_logger, save_img):\n        # do not use the synthetic process during validation\n        self.is_train = False\n        super(RealESRGANModel, self).nondist_validation(dataloader, current_iter, tb_logger, save_img)\n        self.is_train = True\n\n    def optimize_parameters(self, current_iter):\n        # usm sharpening\n        l1_gt = self.gt_usm\n        percep_gt = self.gt_usm\n        gan_gt = self.gt_usm\n        if self.opt['l1_gt_usm'] is False:\n            l1_gt = self.gt\n        if self.opt['percep_gt_usm'] is False:\n            percep_gt = self.gt\n        if self.opt['gan_gt_usm'] is False:\n            gan_gt = self.gt\n\n        # optimize net_g\n        for p in self.net_d.parameters():\n            p.requires_grad = False\n\n        self.optimizer_g.zero_grad()\n        self.output = self.net_g(self.lq)\n\n        l_g_total = 0\n        loss_dict = OrderedDict()\n        if (current_iter % self.net_d_iters == 0 and current_iter > self.net_d_init_iters):\n            # pixel loss\n            if self.cri_pix:\n                l_g_pix = self.cri_pix(self.output, l1_gt)\n                l_g_total += l_g_pix\n                loss_dict['l_g_pix'] = l_g_pix\n            # perceptual loss\n            if self.cri_perceptual:\n                l_g_percep, l_g_style = self.cri_perceptual(self.output, percep_gt)\n                if l_g_percep is not None:\n                    l_g_total += l_g_percep\n                    loss_dict['l_g_percep'] = l_g_percep\n                if l_g_style is not None:\n                    l_g_total += l_g_style\n                    loss_dict['l_g_style'] = l_g_style\n            # gan loss\n            fake_g_pred = self.net_d(self.output)\n            l_g_gan = self.cri_gan(fake_g_pred, True, is_disc=False)\n            l_g_total += l_g_gan\n            loss_dict['l_g_gan'] = l_g_gan\n\n            l_g_total.backward()\n            self.optimizer_g.step()\n\n        # optimize net_d\n        for p in self.net_d.parameters():\n            p.requires_grad = True\n\n        self.optimizer_d.zero_grad()\n        # real\n        real_d_pred = self.net_d(gan_gt)\n        l_d_real = self.cri_gan(real_d_pred, True, is_disc=True)\n        loss_dict['l_d_real'] = l_d_real\n        loss_dict['out_d_real'] = torch.mean(real_d_pred.detach())\n        l_d_real.backward()\n        # fake\n        fake_d_pred = self.net_d(self.output.detach().clone())  # clone for pt1.9\n        l_d_fake = self.cri_gan(fake_d_pred, False, is_disc=True)\n        loss_dict['l_d_fake'] = l_d_fake\n        loss_dict['out_d_fake'] = torch.mean(fake_d_pred.detach())\n        l_d_fake.backward()\n        self.optimizer_d.step()\n\n        if self.ema_decay > 0:\n            self.model_ema(decay=self.ema_decay)\n\n        self.log_dict = self.reduce_loss_dict(loss_dict)\n"
  },
  {
    "path": "realesrgan/models/realesrnet_model.py",
    "content": "import numpy as np\nimport random\nimport torch\nfrom basicsr.data.degradations import random_add_gaussian_noise_pt, random_add_poisson_noise_pt\nfrom basicsr.data.transforms import paired_random_crop\nfrom basicsr.models.sr_model import SRModel\nfrom basicsr.utils import DiffJPEG, USMSharp\nfrom basicsr.utils.img_process_util import filter2D\nfrom basicsr.utils.registry import MODEL_REGISTRY\nfrom torch.nn import functional as F\n\n\n@MODEL_REGISTRY.register()\nclass RealESRNetModel(SRModel):\n    \"\"\"RealESRNet Model for Real-ESRGAN: Training Real-World Blind Super-Resolution with Pure Synthetic Data.\n\n    It is trained without GAN losses.\n    It mainly performs:\n    1. randomly synthesize LQ images in GPU tensors\n    2. optimize the networks with GAN training.\n    \"\"\"\n\n    def __init__(self, opt):\n        super(RealESRNetModel, self).__init__(opt)\n        self.jpeger = DiffJPEG(differentiable=False).cuda()  # simulate JPEG compression artifacts\n        self.usm_sharpener = USMSharp().cuda()  # do usm sharpening\n        self.queue_size = opt.get('queue_size', 180)\n\n    @torch.no_grad()\n    def _dequeue_and_enqueue(self):\n        \"\"\"It is the training pair pool for increasing the diversity in a batch.\n\n        Batch processing limits the diversity of synthetic degradations in a batch. For example, samples in a\n        batch could not have different resize scaling factors. Therefore, we employ this training pair pool\n        to increase the degradation diversity in a batch.\n        \"\"\"\n        # initialize\n        b, c, h, w = self.lq.size()\n        if not hasattr(self, 'queue_lr'):\n            assert self.queue_size % b == 0, f'queue size {self.queue_size} should be divisible by batch size {b}'\n            self.queue_lr = torch.zeros(self.queue_size, c, h, w).cuda()\n            _, c, h, w = self.gt.size()\n            self.queue_gt = torch.zeros(self.queue_size, c, h, w).cuda()\n            self.queue_ptr = 0\n        if self.queue_ptr == self.queue_size:  # the pool is full\n            # do dequeue and enqueue\n            # shuffle\n            idx = torch.randperm(self.queue_size)\n            self.queue_lr = self.queue_lr[idx]\n            self.queue_gt = self.queue_gt[idx]\n            # get first b samples\n            lq_dequeue = self.queue_lr[0:b, :, :, :].clone()\n            gt_dequeue = self.queue_gt[0:b, :, :, :].clone()\n            # update the queue\n            self.queue_lr[0:b, :, :, :] = self.lq.clone()\n            self.queue_gt[0:b, :, :, :] = self.gt.clone()\n\n            self.lq = lq_dequeue\n            self.gt = gt_dequeue\n        else:\n            # only do enqueue\n            self.queue_lr[self.queue_ptr:self.queue_ptr + b, :, :, :] = self.lq.clone()\n            self.queue_gt[self.queue_ptr:self.queue_ptr + b, :, :, :] = self.gt.clone()\n            self.queue_ptr = self.queue_ptr + b\n\n    @torch.no_grad()\n    def feed_data(self, data):\n        \"\"\"Accept data from dataloader, and then add two-order degradations to obtain LQ images.\n        \"\"\"\n        if self.is_train and self.opt.get('high_order_degradation', True):\n            # training data synthesis\n            self.gt = data['gt'].to(self.device)\n            # USM sharpen the GT images\n            if self.opt['gt_usm'] is True:\n                self.gt = self.usm_sharpener(self.gt)\n\n            self.kernel1 = data['kernel1'].to(self.device)\n            self.kernel2 = data['kernel2'].to(self.device)\n            self.sinc_kernel = data['sinc_kernel'].to(self.device)\n\n            ori_h, ori_w = self.gt.size()[2:4]\n\n            # ----------------------- The first degradation process ----------------------- #\n            # blur\n            out = filter2D(self.gt, self.kernel1)\n            # random resize\n            updown_type = random.choices(['up', 'down', 'keep'], self.opt['resize_prob'])[0]\n            if updown_type == 'up':\n                scale = np.random.uniform(1, self.opt['resize_range'][1])\n            elif updown_type == 'down':\n                scale = np.random.uniform(self.opt['resize_range'][0], 1)\n            else:\n                scale = 1\n            mode = random.choice(['area', 'bilinear', 'bicubic'])\n            out = F.interpolate(out, scale_factor=scale, mode=mode)\n            # add noise\n            gray_noise_prob = self.opt['gray_noise_prob']\n            if np.random.uniform() < self.opt['gaussian_noise_prob']:\n                out = random_add_gaussian_noise_pt(\n                    out, sigma_range=self.opt['noise_range'], clip=True, rounds=False, gray_prob=gray_noise_prob)\n            else:\n                out = random_add_poisson_noise_pt(\n                    out,\n                    scale_range=self.opt['poisson_scale_range'],\n                    gray_prob=gray_noise_prob,\n                    clip=True,\n                    rounds=False)\n            # JPEG compression\n            jpeg_p = out.new_zeros(out.size(0)).uniform_(*self.opt['jpeg_range'])\n            out = torch.clamp(out, 0, 1)  # clamp to [0, 1], otherwise JPEGer will result in unpleasant artifacts\n            out = self.jpeger(out, quality=jpeg_p)\n\n            # ----------------------- The second degradation process ----------------------- #\n            # blur\n            if np.random.uniform() < self.opt['second_blur_prob']:\n                out = filter2D(out, self.kernel2)\n            # random resize\n            updown_type = random.choices(['up', 'down', 'keep'], self.opt['resize_prob2'])[0]\n            if updown_type == 'up':\n                scale = np.random.uniform(1, self.opt['resize_range2'][1])\n            elif updown_type == 'down':\n                scale = np.random.uniform(self.opt['resize_range2'][0], 1)\n            else:\n                scale = 1\n            mode = random.choice(['area', 'bilinear', 'bicubic'])\n            out = F.interpolate(\n                out, size=(int(ori_h / self.opt['scale'] * scale), int(ori_w / self.opt['scale'] * scale)), mode=mode)\n            # add noise\n            gray_noise_prob = self.opt['gray_noise_prob2']\n            if np.random.uniform() < self.opt['gaussian_noise_prob2']:\n                out = random_add_gaussian_noise_pt(\n                    out, sigma_range=self.opt['noise_range2'], clip=True, rounds=False, gray_prob=gray_noise_prob)\n            else:\n                out = random_add_poisson_noise_pt(\n                    out,\n                    scale_range=self.opt['poisson_scale_range2'],\n                    gray_prob=gray_noise_prob,\n                    clip=True,\n                    rounds=False)\n\n            # JPEG compression + the final sinc filter\n            # We also need to resize images to desired sizes. We group [resize back + sinc filter] together\n            # as one operation.\n            # We consider two orders:\n            #   1. [resize back + sinc filter] + JPEG compression\n            #   2. JPEG compression + [resize back + sinc filter]\n            # Empirically, we find other combinations (sinc + JPEG + Resize) will introduce twisted lines.\n            if np.random.uniform() < 0.5:\n                # resize back + the final sinc filter\n                mode = random.choice(['area', 'bilinear', 'bicubic'])\n                out = F.interpolate(out, size=(ori_h // self.opt['scale'], ori_w // self.opt['scale']), mode=mode)\n                out = filter2D(out, self.sinc_kernel)\n                # JPEG compression\n                jpeg_p = out.new_zeros(out.size(0)).uniform_(*self.opt['jpeg_range2'])\n                out = torch.clamp(out, 0, 1)\n                out = self.jpeger(out, quality=jpeg_p)\n            else:\n                # JPEG compression\n                jpeg_p = out.new_zeros(out.size(0)).uniform_(*self.opt['jpeg_range2'])\n                out = torch.clamp(out, 0, 1)\n                out = self.jpeger(out, quality=jpeg_p)\n                # resize back + the final sinc filter\n                mode = random.choice(['area', 'bilinear', 'bicubic'])\n                out = F.interpolate(out, size=(ori_h // self.opt['scale'], ori_w // self.opt['scale']), mode=mode)\n                out = filter2D(out, self.sinc_kernel)\n\n            # clamp and round\n            self.lq = torch.clamp((out * 255.0).round(), 0, 255) / 255.\n\n            # random crop\n            gt_size = self.opt['gt_size']\n            self.gt, self.lq = paired_random_crop(self.gt, self.lq, gt_size, self.opt['scale'])\n\n            # training pair pool\n            self._dequeue_and_enqueue()\n            self.lq = self.lq.contiguous()  # for the warning: grad and param do not obey the gradient layout contract\n        else:\n            # for paired training or validation\n            self.lq = data['lq'].to(self.device)\n            if 'gt' in data:\n                self.gt = data['gt'].to(self.device)\n                self.gt_usm = self.usm_sharpener(self.gt)\n\n    def nondist_validation(self, dataloader, current_iter, tb_logger, save_img):\n        # do not use the synthetic process during validation\n        self.is_train = False\n        super(RealESRNetModel, self).nondist_validation(dataloader, current_iter, tb_logger, save_img)\n        self.is_train = True\n"
  },
  {
    "path": "realesrgan/train.py",
    "content": "# flake8: noqa\nimport os.path as osp\nfrom basicsr.train import train_pipeline\n\nimport realesrgan.archs\nimport realesrgan.data\nimport realesrgan.models\n\nif __name__ == '__main__':\n    root_path = osp.abspath(osp.join(__file__, osp.pardir, osp.pardir))\n    train_pipeline(root_path)\n"
  },
  {
    "path": "realesrgan/utils.py",
    "content": "import cv2\nimport math\nimport numpy as np\nimport os\nimport queue\nimport threading\nimport torch\nfrom basicsr.utils.download_util import load_file_from_url\nfrom torch.nn import functional as F\n\nROOT_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))\n\n\nclass RealESRGANer():\n    \"\"\"A helper class for upsampling images with RealESRGAN.\n\n    Args:\n        scale (int): Upsampling scale factor used in the networks. It is usually 2 or 4.\n        model_path (str): The path to the pretrained model. It can be urls (will first download it automatically).\n        model (nn.Module): The defined network. Default: None.\n        tile (int): As too large images result in the out of GPU memory issue, so this tile option will first crop\n            input images into tiles, and then process each of them. Finally, they will be merged into one image.\n            0 denotes for do not use tile. Default: 0.\n        tile_pad (int): The pad size for each tile, to remove border artifacts. Default: 10.\n        pre_pad (int): Pad the input images to avoid border artifacts. Default: 10.\n        half (float): Whether to use half precision during inference. Default: False.\n    \"\"\"\n\n    def __init__(self,\n                 scale,\n                 model_path,\n                 dni_weight=None,\n                 model=None,\n                 tile=0,\n                 tile_pad=10,\n                 pre_pad=10,\n                 half=False,\n                 device=None,\n                 gpu_id=None):\n        self.scale = scale\n        self.tile_size = tile\n        self.tile_pad = tile_pad\n        self.pre_pad = pre_pad\n        self.mod_scale = None\n        self.half = half\n\n        # initialize model\n        if gpu_id:\n            self.device = torch.device(\n                f'cuda:{gpu_id}' if torch.cuda.is_available() else 'cpu') if device is None else device\n        else:\n            self.device = torch.device('cuda' if torch.cuda.is_available() else 'cpu') if device is None else device\n\n        if isinstance(model_path, list):\n            # dni\n            assert len(model_path) == len(dni_weight), 'model_path and dni_weight should have the save length.'\n            loadnet = self.dni(model_path[0], model_path[1], dni_weight)\n        else:\n            # if the model_path starts with https, it will first download models to the folder: weights\n            if model_path.startswith('https://'):\n                model_path = load_file_from_url(\n                    url=model_path, model_dir=os.path.join(ROOT_DIR, 'weights'), progress=True, file_name=None)\n            loadnet = torch.load(model_path, map_location=torch.device('cpu'))\n\n        # prefer to use params_ema\n        if 'params_ema' in loadnet:\n            keyname = 'params_ema'\n        else:\n            keyname = 'params'\n        model.load_state_dict(loadnet[keyname], strict=True)\n\n        model.eval()\n        self.model = model.to(self.device)\n        if self.half:\n            self.model = self.model.half()\n\n    def dni(self, net_a, net_b, dni_weight, key='params', loc='cpu'):\n        \"\"\"Deep network interpolation.\n\n        ``Paper: Deep Network Interpolation for Continuous Imagery Effect Transition``\n        \"\"\"\n        net_a = torch.load(net_a, map_location=torch.device(loc))\n        net_b = torch.load(net_b, map_location=torch.device(loc))\n        for k, v_a in net_a[key].items():\n            net_a[key][k] = dni_weight[0] * v_a + dni_weight[1] * net_b[key][k]\n        return net_a\n\n    def pre_process(self, img):\n        \"\"\"Pre-process, such as pre-pad and mod pad, so that the images can be divisible\n        \"\"\"\n        img = torch.from_numpy(np.transpose(img, (2, 0, 1))).float()\n        self.img = img.unsqueeze(0).to(self.device)\n        if self.half:\n            self.img = self.img.half()\n\n        # pre_pad\n        if self.pre_pad != 0:\n            self.img = F.pad(self.img, (0, self.pre_pad, 0, self.pre_pad), 'reflect')\n        # mod pad for divisible borders\n        if self.scale == 2:\n            self.mod_scale = 2\n        elif self.scale == 1:\n            self.mod_scale = 4\n        if self.mod_scale is not None:\n            self.mod_pad_h, self.mod_pad_w = 0, 0\n            _, _, h, w = self.img.size()\n            if (h % self.mod_scale != 0):\n                self.mod_pad_h = (self.mod_scale - h % self.mod_scale)\n            if (w % self.mod_scale != 0):\n                self.mod_pad_w = (self.mod_scale - w % self.mod_scale)\n            self.img = F.pad(self.img, (0, self.mod_pad_w, 0, self.mod_pad_h), 'reflect')\n\n    def process(self):\n        # model inference\n        self.output = self.model(self.img)\n\n    def tile_process(self):\n        \"\"\"It will first crop input images to tiles, and then process each tile.\n        Finally, all the processed tiles are merged into one images.\n\n        Modified from: https://github.com/ata4/esrgan-launcher\n        \"\"\"\n        batch, channel, height, width = self.img.shape\n        output_height = height * self.scale\n        output_width = width * self.scale\n        output_shape = (batch, channel, output_height, output_width)\n\n        # start with black image\n        self.output = self.img.new_zeros(output_shape)\n        tiles_x = math.ceil(width / self.tile_size)\n        tiles_y = math.ceil(height / self.tile_size)\n\n        # loop over all tiles\n        for y in range(tiles_y):\n            for x in range(tiles_x):\n                # extract tile from input image\n                ofs_x = x * self.tile_size\n                ofs_y = y * self.tile_size\n                # input tile area on total image\n                input_start_x = ofs_x\n                input_end_x = min(ofs_x + self.tile_size, width)\n                input_start_y = ofs_y\n                input_end_y = min(ofs_y + self.tile_size, height)\n\n                # input tile area on total image with padding\n                input_start_x_pad = max(input_start_x - self.tile_pad, 0)\n                input_end_x_pad = min(input_end_x + self.tile_pad, width)\n                input_start_y_pad = max(input_start_y - self.tile_pad, 0)\n                input_end_y_pad = min(input_end_y + self.tile_pad, height)\n\n                # input tile dimensions\n                input_tile_width = input_end_x - input_start_x\n                input_tile_height = input_end_y - input_start_y\n                tile_idx = y * tiles_x + x + 1\n                input_tile = self.img[:, :, input_start_y_pad:input_end_y_pad, input_start_x_pad:input_end_x_pad]\n\n                # upscale tile\n                try:\n                    with torch.no_grad():\n                        output_tile = self.model(input_tile)\n                except RuntimeError as error:\n                    print('Error', error)\n                print(f'\\tTile {tile_idx}/{tiles_x * tiles_y}')\n\n                # output tile area on total image\n                output_start_x = input_start_x * self.scale\n                output_end_x = input_end_x * self.scale\n                output_start_y = input_start_y * self.scale\n                output_end_y = input_end_y * self.scale\n\n                # output tile area without padding\n                output_start_x_tile = (input_start_x - input_start_x_pad) * self.scale\n                output_end_x_tile = output_start_x_tile + input_tile_width * self.scale\n                output_start_y_tile = (input_start_y - input_start_y_pad) * self.scale\n                output_end_y_tile = output_start_y_tile + input_tile_height * self.scale\n\n                # put tile into output image\n                self.output[:, :, output_start_y:output_end_y,\n                            output_start_x:output_end_x] = output_tile[:, :, output_start_y_tile:output_end_y_tile,\n                                                                       output_start_x_tile:output_end_x_tile]\n\n    def post_process(self):\n        # remove extra pad\n        if self.mod_scale is not None:\n            _, _, h, w = self.output.size()\n            self.output = self.output[:, :, 0:h - self.mod_pad_h * self.scale, 0:w - self.mod_pad_w * self.scale]\n        # remove prepad\n        if self.pre_pad != 0:\n            _, _, h, w = self.output.size()\n            self.output = self.output[:, :, 0:h - self.pre_pad * self.scale, 0:w - self.pre_pad * self.scale]\n        return self.output\n\n    @torch.no_grad()\n    def enhance(self, img, outscale=None, alpha_upsampler='realesrgan'):\n        h_input, w_input = img.shape[0:2]\n        # img: numpy\n        img = img.astype(np.float32)\n        if np.max(img) > 256:  # 16-bit image\n            max_range = 65535\n            print('\\tInput is a 16-bit image')\n        else:\n            max_range = 255\n        img = img / max_range\n        if len(img.shape) == 2:  # gray image\n            img_mode = 'L'\n            img = cv2.cvtColor(img, cv2.COLOR_GRAY2RGB)\n        elif img.shape[2] == 4:  # RGBA image with alpha channel\n            img_mode = 'RGBA'\n            alpha = img[:, :, 3]\n            img = img[:, :, 0:3]\n            img = cv2.cvtColor(img, cv2.COLOR_BGR2RGB)\n            if alpha_upsampler == 'realesrgan':\n                alpha = cv2.cvtColor(alpha, cv2.COLOR_GRAY2RGB)\n        else:\n            img_mode = 'RGB'\n            img = cv2.cvtColor(img, cv2.COLOR_BGR2RGB)\n\n        # ------------------- process image (without the alpha channel) ------------------- #\n        self.pre_process(img)\n        if self.tile_size > 0:\n            self.tile_process()\n        else:\n            self.process()\n        output_img = self.post_process()\n        output_img = output_img.data.squeeze().float().cpu().clamp_(0, 1).numpy()\n        output_img = np.transpose(output_img[[2, 1, 0], :, :], (1, 2, 0))\n        if img_mode == 'L':\n            output_img = cv2.cvtColor(output_img, cv2.COLOR_BGR2GRAY)\n\n        # ------------------- process the alpha channel if necessary ------------------- #\n        if img_mode == 'RGBA':\n            if alpha_upsampler == 'realesrgan':\n                self.pre_process(alpha)\n                if self.tile_size > 0:\n                    self.tile_process()\n                else:\n                    self.process()\n                output_alpha = self.post_process()\n                output_alpha = output_alpha.data.squeeze().float().cpu().clamp_(0, 1).numpy()\n                output_alpha = np.transpose(output_alpha[[2, 1, 0], :, :], (1, 2, 0))\n                output_alpha = cv2.cvtColor(output_alpha, cv2.COLOR_BGR2GRAY)\n            else:  # use the cv2 resize for alpha channel\n                h, w = alpha.shape[0:2]\n                output_alpha = cv2.resize(alpha, (w * self.scale, h * self.scale), interpolation=cv2.INTER_LINEAR)\n\n            # merge the alpha channel\n            output_img = cv2.cvtColor(output_img, cv2.COLOR_BGR2BGRA)\n            output_img[:, :, 3] = output_alpha\n\n        # ------------------------------ return ------------------------------ #\n        if max_range == 65535:  # 16-bit image\n            output = (output_img * 65535.0).round().astype(np.uint16)\n        else:\n            output = (output_img * 255.0).round().astype(np.uint8)\n\n        if outscale is not None and outscale != float(self.scale):\n            output = cv2.resize(\n                output, (\n                    int(w_input * outscale),\n                    int(h_input * outscale),\n                ), interpolation=cv2.INTER_LANCZOS4)\n\n        return output, img_mode\n\n\nclass PrefetchReader(threading.Thread):\n    \"\"\"Prefetch images.\n\n    Args:\n        img_list (list[str]): A image list of image paths to be read.\n        num_prefetch_queue (int): Number of prefetch queue.\n    \"\"\"\n\n    def __init__(self, img_list, num_prefetch_queue):\n        super().__init__()\n        self.que = queue.Queue(num_prefetch_queue)\n        self.img_list = img_list\n\n    def run(self):\n        for img_path in self.img_list:\n            img = cv2.imread(img_path, cv2.IMREAD_UNCHANGED)\n            self.que.put(img)\n\n        self.que.put(None)\n\n    def __next__(self):\n        next_item = self.que.get()\n        if next_item is None:\n            raise StopIteration\n        return next_item\n\n    def __iter__(self):\n        return self\n\n\nclass IOConsumer(threading.Thread):\n\n    def __init__(self, opt, que, qid):\n        super().__init__()\n        self._queue = que\n        self.qid = qid\n        self.opt = opt\n\n    def run(self):\n        while True:\n            msg = self._queue.get()\n            if isinstance(msg, str) and msg == 'quit':\n                break\n\n            output = msg['output']\n            save_path = msg['save_path']\n            cv2.imwrite(save_path, output)\n        print(f'IO worker {self.qid} is done.')\n"
  },
  {
    "path": "requirements.txt",
    "content": "basicsr>=1.4.2\nfacexlib>=0.2.5\ngfpgan>=1.3.5\nnumpy\nopencv-python\nPillow\ntorch>=1.7\ntorchvision\ntqdm\n"
  },
  {
    "path": "scripts/extract_subimages.py",
    "content": "import argparse\nimport cv2\nimport numpy as np\nimport os\nimport sys\nfrom basicsr.utils import scandir\nfrom multiprocessing import Pool\nfrom os import path as osp\nfrom tqdm import tqdm\n\n\ndef main(args):\n    \"\"\"A multi-thread tool to crop large images to sub-images for faster IO.\n\n    opt (dict): Configuration dict. It contains:\n        n_thread (int): Thread number.\n        compression_level (int):  CV_IMWRITE_PNG_COMPRESSION from 0 to 9. A higher value means a smaller size\n            and longer compression time. Use 0 for faster CPU decompression. Default: 3, same in cv2.\n        input_folder (str): Path to the input folder.\n        save_folder (str): Path to save folder.\n        crop_size (int): Crop size.\n        step (int): Step for overlapped sliding window.\n        thresh_size (int): Threshold size. Patches whose size is lower than thresh_size will be dropped.\n\n    Usage:\n        For each folder, run this script.\n        Typically, there are GT folder and LQ folder to be processed for DIV2K dataset.\n        After process, each sub_folder should have the same number of subimages.\n        Remember to modify opt configurations according to your settings.\n    \"\"\"\n\n    opt = {}\n    opt['n_thread'] = args.n_thread\n    opt['compression_level'] = args.compression_level\n    opt['input_folder'] = args.input\n    opt['save_folder'] = args.output\n    opt['crop_size'] = args.crop_size\n    opt['step'] = args.step\n    opt['thresh_size'] = args.thresh_size\n    extract_subimages(opt)\n\n\ndef extract_subimages(opt):\n    \"\"\"Crop images to subimages.\n\n    Args:\n        opt (dict): Configuration dict. It contains:\n            input_folder (str): Path to the input folder.\n            save_folder (str): Path to save folder.\n            n_thread (int): Thread number.\n    \"\"\"\n    input_folder = opt['input_folder']\n    save_folder = opt['save_folder']\n    if not osp.exists(save_folder):\n        os.makedirs(save_folder)\n        print(f'mkdir {save_folder} ...')\n    else:\n        print(f'Folder {save_folder} already exists. Exit.')\n        sys.exit(1)\n\n    # scan all images\n    img_list = list(scandir(input_folder, full_path=True))\n\n    pbar = tqdm(total=len(img_list), unit='image', desc='Extract')\n    pool = Pool(opt['n_thread'])\n    for path in img_list:\n        pool.apply_async(worker, args=(path, opt), callback=lambda arg: pbar.update(1))\n    pool.close()\n    pool.join()\n    pbar.close()\n    print('All processes done.')\n\n\ndef worker(path, opt):\n    \"\"\"Worker for each process.\n\n    Args:\n        path (str): Image path.\n        opt (dict): Configuration dict. It contains:\n            crop_size (int): Crop size.\n            step (int): Step for overlapped sliding window.\n            thresh_size (int): Threshold size. Patches whose size is lower than thresh_size will be dropped.\n            save_folder (str): Path to save folder.\n            compression_level (int): for cv2.IMWRITE_PNG_COMPRESSION.\n\n    Returns:\n        process_info (str): Process information displayed in progress bar.\n    \"\"\"\n    crop_size = opt['crop_size']\n    step = opt['step']\n    thresh_size = opt['thresh_size']\n    img_name, extension = osp.splitext(osp.basename(path))\n\n    # remove the x2, x3, x4 and x8 in the filename for DIV2K\n    img_name = img_name.replace('x2', '').replace('x3', '').replace('x4', '').replace('x8', '')\n\n    img = cv2.imread(path, cv2.IMREAD_UNCHANGED)\n\n    h, w = img.shape[0:2]\n    h_space = np.arange(0, h - crop_size + 1, step)\n    if h - (h_space[-1] + crop_size) > thresh_size:\n        h_space = np.append(h_space, h - crop_size)\n    w_space = np.arange(0, w - crop_size + 1, step)\n    if w - (w_space[-1] + crop_size) > thresh_size:\n        w_space = np.append(w_space, w - crop_size)\n\n    index = 0\n    for x in h_space:\n        for y in w_space:\n            index += 1\n            cropped_img = img[x:x + crop_size, y:y + crop_size, ...]\n            cropped_img = np.ascontiguousarray(cropped_img)\n            cv2.imwrite(\n                osp.join(opt['save_folder'], f'{img_name}_s{index:03d}{extension}'), cropped_img,\n                [cv2.IMWRITE_PNG_COMPRESSION, opt['compression_level']])\n    process_info = f'Processing {img_name} ...'\n    return process_info\n\n\nif __name__ == '__main__':\n    parser = argparse.ArgumentParser()\n    parser.add_argument('--input', type=str, default='datasets/DF2K/DF2K_HR', help='Input folder')\n    parser.add_argument('--output', type=str, default='datasets/DF2K/DF2K_HR_sub', help='Output folder')\n    parser.add_argument('--crop_size', type=int, default=480, help='Crop size')\n    parser.add_argument('--step', type=int, default=240, help='Step for overlapped sliding window')\n    parser.add_argument(\n        '--thresh_size',\n        type=int,\n        default=0,\n        help='Threshold size. Patches whose size is lower than thresh_size will be dropped.')\n    parser.add_argument('--n_thread', type=int, default=20, help='Thread number.')\n    parser.add_argument('--compression_level', type=int, default=3, help='Compression level')\n    args = parser.parse_args()\n\n    main(args)\n"
  },
  {
    "path": "scripts/generate_meta_info.py",
    "content": "import argparse\nimport cv2\nimport glob\nimport os\n\n\ndef main(args):\n    txt_file = open(args.meta_info, 'w')\n    for folder, root in zip(args.input, args.root):\n        img_paths = sorted(glob.glob(os.path.join(folder, '*')))\n        for img_path in img_paths:\n            status = True\n            if args.check:\n                # read the image once for check, as some images may have errors\n                try:\n                    img = cv2.imread(img_path)\n                except (IOError, OSError) as error:\n                    print(f'Read {img_path} error: {error}')\n                    status = False\n                if img is None:\n                    status = False\n                    print(f'Img is None: {img_path}')\n            if status:\n                # get the relative path\n                img_name = os.path.relpath(img_path, root)\n                print(img_name)\n                txt_file.write(f'{img_name}\\n')\n\n\nif __name__ == '__main__':\n    \"\"\"Generate meta info (txt file) for only Ground-Truth images.\n\n    It can also generate meta info from several folders into one txt file.\n    \"\"\"\n    parser = argparse.ArgumentParser()\n    parser.add_argument(\n        '--input',\n        nargs='+',\n        default=['datasets/DF2K/DF2K_HR', 'datasets/DF2K/DF2K_multiscale'],\n        help='Input folder, can be a list')\n    parser.add_argument(\n        '--root',\n        nargs='+',\n        default=['datasets/DF2K', 'datasets/DF2K'],\n        help='Folder root, should have the length as input folders')\n    parser.add_argument(\n        '--meta_info',\n        type=str,\n        default='datasets/DF2K/meta_info/meta_info_DF2Kmultiscale.txt',\n        help='txt path for meta info')\n    parser.add_argument('--check', action='store_true', help='Read image to check whether it is ok')\n    args = parser.parse_args()\n\n    assert len(args.input) == len(args.root), ('Input folder and folder root should have the same length, but got '\n                                               f'{len(args.input)} and {len(args.root)}.')\n    os.makedirs(os.path.dirname(args.meta_info), exist_ok=True)\n\n    main(args)\n"
  },
  {
    "path": "scripts/generate_meta_info_pairdata.py",
    "content": "import argparse\nimport glob\nimport os\n\n\ndef main(args):\n    txt_file = open(args.meta_info, 'w')\n    # sca images\n    img_paths_gt = sorted(glob.glob(os.path.join(args.input[0], '*')))\n    img_paths_lq = sorted(glob.glob(os.path.join(args.input[1], '*')))\n\n    assert len(img_paths_gt) == len(img_paths_lq), ('GT folder and LQ folder should have the same length, but got '\n                                                    f'{len(img_paths_gt)} and {len(img_paths_lq)}.')\n\n    for img_path_gt, img_path_lq in zip(img_paths_gt, img_paths_lq):\n        # get the relative paths\n        img_name_gt = os.path.relpath(img_path_gt, args.root[0])\n        img_name_lq = os.path.relpath(img_path_lq, args.root[1])\n        print(f'{img_name_gt}, {img_name_lq}')\n        txt_file.write(f'{img_name_gt}, {img_name_lq}\\n')\n\n\nif __name__ == '__main__':\n    \"\"\"This script is used to generate meta info (txt file) for paired images.\n    \"\"\"\n    parser = argparse.ArgumentParser()\n    parser.add_argument(\n        '--input',\n        nargs='+',\n        default=['datasets/DF2K/DIV2K_train_HR_sub', 'datasets/DF2K/DIV2K_train_LR_bicubic_X4_sub'],\n        help='Input folder, should be [gt_folder, lq_folder]')\n    parser.add_argument('--root', nargs='+', default=[None, None], help='Folder root, will use the ')\n    parser.add_argument(\n        '--meta_info',\n        type=str,\n        default='datasets/DF2K/meta_info/meta_info_DIV2K_sub_pair.txt',\n        help='txt path for meta info')\n    args = parser.parse_args()\n\n    assert len(args.input) == 2, 'Input folder should have two elements: gt folder and lq folder'\n    assert len(args.root) == 2, 'Root path should have two elements: root for gt folder and lq folder'\n    os.makedirs(os.path.dirname(args.meta_info), exist_ok=True)\n    for i in range(2):\n        if args.input[i].endswith('/'):\n            args.input[i] = args.input[i][:-1]\n        if args.root[i] is None:\n            args.root[i] = os.path.dirname(args.input[i])\n\n    main(args)\n"
  },
  {
    "path": "scripts/generate_multiscale_DF2K.py",
    "content": "import argparse\nimport glob\nimport os\nfrom PIL import Image\n\n\ndef main(args):\n    # For DF2K, we consider the following three scales,\n    # and the smallest image whose shortest edge is 400\n    scale_list = [0.75, 0.5, 1 / 3]\n    shortest_edge = 400\n\n    path_list = sorted(glob.glob(os.path.join(args.input, '*')))\n    for path in path_list:\n        print(path)\n        basename = os.path.splitext(os.path.basename(path))[0]\n\n        img = Image.open(path)\n        width, height = img.size\n        for idx, scale in enumerate(scale_list):\n            print(f'\\t{scale:.2f}')\n            rlt = img.resize((int(width * scale), int(height * scale)), resample=Image.LANCZOS)\n            rlt.save(os.path.join(args.output, f'{basename}T{idx}.png'))\n\n        # save the smallest image which the shortest edge is 400\n        if width < height:\n            ratio = height / width\n            width = shortest_edge\n            height = int(width * ratio)\n        else:\n            ratio = width / height\n            height = shortest_edge\n            width = int(height * ratio)\n        rlt = img.resize((int(width), int(height)), resample=Image.LANCZOS)\n        rlt.save(os.path.join(args.output, f'{basename}T{idx+1}.png'))\n\n\nif __name__ == '__main__':\n    \"\"\"Generate multi-scale versions for GT images with LANCZOS resampling.\n    It is now used for DF2K dataset (DIV2K + Flickr 2K)\n    \"\"\"\n    parser = argparse.ArgumentParser()\n    parser.add_argument('--input', type=str, default='datasets/DF2K/DF2K_HR', help='Input folder')\n    parser.add_argument('--output', type=str, default='datasets/DF2K/DF2K_multiscale', help='Output folder')\n    args = parser.parse_args()\n\n    os.makedirs(args.output, exist_ok=True)\n    main(args)\n"
  },
  {
    "path": "scripts/pytorch2onnx.py",
    "content": "import argparse\nimport torch\nimport torch.onnx\nfrom basicsr.archs.rrdbnet_arch import RRDBNet\n\n\ndef main(args):\n    # An instance of the model\n    model = RRDBNet(num_in_ch=3, num_out_ch=3, num_feat=64, num_block=23, num_grow_ch=32, scale=4)\n    if args.params:\n        keyname = 'params'\n    else:\n        keyname = 'params_ema'\n    model.load_state_dict(torch.load(args.input)[keyname])\n    # set the train mode to false since we will only run the forward pass.\n    model.train(False)\n    model.cpu().eval()\n\n    # An example input\n    x = torch.rand(1, 3, 64, 64)\n    # Export the model\n    with torch.no_grad():\n        torch_out = torch.onnx._export(model, x, args.output, opset_version=11, export_params=True)\n    print(torch_out.shape)\n\n\nif __name__ == '__main__':\n    \"\"\"Convert pytorch model to onnx models\"\"\"\n    parser = argparse.ArgumentParser()\n    parser.add_argument(\n        '--input', type=str, default='experiments/pretrained_models/RealESRGAN_x4plus.pth', help='Input model path')\n    parser.add_argument('--output', type=str, default='realesrgan-x4.onnx', help='Output onnx path')\n    parser.add_argument('--params', action='store_false', help='Use params instead of params_ema')\n    args = parser.parse_args()\n\n    main(args)\n"
  },
  {
    "path": "setup.cfg",
    "content": "[flake8]\nignore =\n    # line break before binary operator (W503)\n    W503,\n    # line break after binary operator (W504)\n    W504,\nmax-line-length=120\n\n[yapf]\nbased_on_style = pep8\ncolumn_limit = 120\nblank_line_before_nested_class_or_def = true\nsplit_before_expression_after_opening_paren = true\n\n[isort]\nline_length = 120\nmulti_line_output = 0\nknown_standard_library = pkg_resources,setuptools\nknown_first_party = realesrgan\nknown_third_party = PIL,basicsr,cv2,numpy,pytest,torch,torchvision,tqdm,yaml\nno_lines_before = STDLIB,LOCALFOLDER\ndefault_section = THIRDPARTY\n\n[codespell]\nskip = .git,./docs/build\ncount =\nquiet-level = 3\n\n[aliases]\ntest=pytest\n\n[tool:pytest]\naddopts=tests/\n"
  },
  {
    "path": "setup.py",
    "content": "#!/usr/bin/env python\n\nfrom setuptools import find_packages, setup\n\nimport os\nimport subprocess\nimport time\n\nversion_file = 'realesrgan/version.py'\n\n\ndef readme():\n    with open('README.md', encoding='utf-8') as f:\n        content = f.read()\n    return content\n\n\ndef get_git_hash():\n\n    def _minimal_ext_cmd(cmd):\n        # construct minimal environment\n        env = {}\n        for k in ['SYSTEMROOT', 'PATH', 'HOME']:\n            v = os.environ.get(k)\n            if v is not None:\n                env[k] = v\n        # LANGUAGE is used on win32\n        env['LANGUAGE'] = 'C'\n        env['LANG'] = 'C'\n        env['LC_ALL'] = 'C'\n        out = subprocess.Popen(cmd, stdout=subprocess.PIPE, env=env).communicate()[0]\n        return out\n\n    try:\n        out = _minimal_ext_cmd(['git', 'rev-parse', 'HEAD'])\n        sha = out.strip().decode('ascii')\n    except OSError:\n        sha = 'unknown'\n\n    return sha\n\n\ndef get_hash():\n    if os.path.exists('.git'):\n        sha = get_git_hash()[:7]\n    else:\n        sha = 'unknown'\n\n    return sha\n\n\ndef write_version_py():\n    content = \"\"\"# GENERATED VERSION FILE\n# TIME: {}\n__version__ = '{}'\n__gitsha__ = '{}'\nversion_info = ({})\n\"\"\"\n    sha = get_hash()\n    with open('VERSION', 'r') as f:\n        SHORT_VERSION = f.read().strip()\n    VERSION_INFO = ', '.join([x if x.isdigit() else f'\"{x}\"' for x in SHORT_VERSION.split('.')])\n\n    version_file_str = content.format(time.asctime(), SHORT_VERSION, sha, VERSION_INFO)\n    with open(version_file, 'w') as f:\n        f.write(version_file_str)\n\n\ndef get_version():\n    with open(version_file, 'r') as f:\n        exec(compile(f.read(), version_file, 'exec'))\n    return locals()['__version__']\n\n\ndef get_requirements(filename='requirements.txt'):\n    here = os.path.dirname(os.path.realpath(__file__))\n    with open(os.path.join(here, filename), 'r') as f:\n        requires = [line.replace('\\n', '') for line in f.readlines()]\n    return requires\n\n\nif __name__ == '__main__':\n    write_version_py()\n    setup(\n        name='realesrgan',\n        version=get_version(),\n        description='Real-ESRGAN aims at developing Practical Algorithms for General Image Restoration',\n        long_description=readme(),\n        long_description_content_type='text/markdown',\n        author='Xintao Wang',\n        author_email='xintao.wang@outlook.com',\n        keywords='computer vision, pytorch, image restoration, super-resolution, esrgan, real-esrgan',\n        url='https://github.com/xinntao/Real-ESRGAN',\n        include_package_data=True,\n        packages=find_packages(exclude=('options', 'datasets', 'experiments', 'results', 'tb_logger', 'wandb')),\n        classifiers=[\n            'Development Status :: 4 - Beta',\n            'License :: OSI Approved :: Apache Software License',\n            'Operating System :: OS Independent',\n            'Programming Language :: Python :: 3',\n            'Programming Language :: Python :: 3.7',\n            'Programming Language :: Python :: 3.8',\n        ],\n        license='BSD-3-Clause License',\n        setup_requires=['cython', 'numpy'],\n        install_requires=get_requirements(),\n        zip_safe=False)\n"
  },
  {
    "path": "tests/data/gt.lmdb/meta_info.txt",
    "content": "baboon.png (480,500,3) 1\ncomic.png (360,240,3) 1\n"
  },
  {
    "path": "tests/data/lq.lmdb/meta_info.txt",
    "content": "baboon.png (120,125,3) 1\ncomic.png (80,60,3) 1\n"
  },
  {
    "path": "tests/data/meta_info_gt.txt",
    "content": "baboon.png\ncomic.png\n"
  },
  {
    "path": "tests/data/meta_info_pair.txt",
    "content": "gt/baboon.png, lq/baboon.png\ngt/comic.png, lq/comic.png\n"
  },
  {
    "path": "tests/data/test_realesrgan_dataset.yml",
    "content": "name: Demo\ntype: RealESRGANDataset\ndataroot_gt: tests/data/gt\nmeta_info: tests/data/meta_info_gt.txt\nio_backend:\n  type: disk\n\nblur_kernel_size: 21\nkernel_list: ['iso', 'aniso', 'generalized_iso', 'generalized_aniso', 'plateau_iso', 'plateau_aniso']\nkernel_prob: [0.45, 0.25, 0.12, 0.03, 0.12, 0.03]\nsinc_prob: 1\nblur_sigma: [0.2, 3]\nbetag_range: [0.5, 4]\nbetap_range: [1, 2]\n\nblur_kernel_size2: 21\nkernel_list2: ['iso', 'aniso', 'generalized_iso', 'generalized_aniso', 'plateau_iso', 'plateau_aniso']\nkernel_prob2: [0.45, 0.25, 0.12, 0.03, 0.12, 0.03]\nsinc_prob2: 1\nblur_sigma2: [0.2, 1.5]\nbetag_range2: [0.5, 4]\nbetap_range2: [1, 2]\n\nfinal_sinc_prob: 1\n\ngt_size: 128\nuse_hflip: True\nuse_rot: False\n"
  },
  {
    "path": "tests/data/test_realesrgan_model.yml",
    "content": "scale: 4\nnum_gpu: 1\nmanual_seed: 0\nis_train: True\ndist: False\n\n# ----------------- options for synthesizing training data ----------------- #\n# USM the ground-truth\nl1_gt_usm: True\npercep_gt_usm: True\ngan_gt_usm: False\n\n# the first degradation process\nresize_prob: [0.2, 0.7, 0.1]  # up, down, keep\nresize_range: [0.15, 1.5]\ngaussian_noise_prob: 1\nnoise_range: [1, 30]\npoisson_scale_range: [0.05, 3]\ngray_noise_prob: 1\njpeg_range: [30, 95]\n\n# the second degradation process\nsecond_blur_prob: 1\nresize_prob2: [0.3, 0.4, 0.3]  # up, down, keep\nresize_range2: [0.3, 1.2]\ngaussian_noise_prob2: 1\nnoise_range2: [1, 25]\npoisson_scale_range2: [0.05, 2.5]\ngray_noise_prob2: 1\njpeg_range2: [30, 95]\n\ngt_size: 32\nqueue_size: 1\n\n# network structures\nnetwork_g:\n  type: RRDBNet\n  num_in_ch: 3\n  num_out_ch: 3\n  num_feat: 4\n  num_block: 1\n  num_grow_ch: 2\n\nnetwork_d:\n  type: UNetDiscriminatorSN\n  num_in_ch: 3\n  num_feat: 2\n  skip_connection: True\n\n# path\npath:\n  pretrain_network_g: ~\n  param_key_g: params_ema\n  strict_load_g: true\n  resume_state: ~\n\n# training settings\ntrain:\n  ema_decay: 0.999\n  optim_g:\n    type: Adam\n    lr: !!float 1e-4\n    weight_decay: 0\n    betas: [0.9, 0.99]\n  optim_d:\n    type: Adam\n    lr: !!float 1e-4\n    weight_decay: 0\n    betas: [0.9, 0.99]\n\n  scheduler:\n    type: MultiStepLR\n    milestones: [400000]\n    gamma: 0.5\n\n  total_iter: 400000\n  warmup_iter: -1  # no warm up\n\n  # losses\n  pixel_opt:\n    type: L1Loss\n    loss_weight: 1.0\n    reduction: mean\n  # perceptual loss (content and style losses)\n  perceptual_opt:\n    type: PerceptualLoss\n    layer_weights:\n      # before relu\n      'conv1_2': 0.1\n      'conv2_2': 0.1\n      'conv3_4': 1\n      'conv4_4': 1\n      'conv5_4': 1\n    vgg_type: vgg19\n    use_input_norm: true\n    perceptual_weight: !!float 1.0\n    style_weight: 0\n    range_norm: false\n    criterion: l1\n  # gan loss\n  gan_opt:\n    type: GANLoss\n    gan_type: vanilla\n    real_label_val: 1.0\n    fake_label_val: 0.0\n    loss_weight: !!float 1e-1\n\n  net_d_iters: 1\n  net_d_init_iters: 0\n\n\n# validation settings\nval:\n  val_freq: !!float 5e3\n  save_img: False\n"
  },
  {
    "path": "tests/data/test_realesrgan_paired_dataset.yml",
    "content": "name: Demo\ntype: RealESRGANPairedDataset\nscale: 4\ndataroot_gt: tests/data\ndataroot_lq: tests/data\nmeta_info: tests/data/meta_info_pair.txt\nio_backend:\n  type: disk\n\nphase: train\ngt_size: 128\nuse_hflip: True\nuse_rot: False\n"
  },
  {
    "path": "tests/data/test_realesrnet_model.yml",
    "content": "scale: 4\nnum_gpu: 1\nmanual_seed: 0\nis_train: True\ndist: False\n\n# ----------------- options for synthesizing training data ----------------- #\ngt_usm: True  # USM the ground-truth\n\n# the first degradation process\nresize_prob: [0.2, 0.7, 0.1]  # up, down, keep\nresize_range: [0.15, 1.5]\ngaussian_noise_prob: 1\nnoise_range: [1, 30]\npoisson_scale_range: [0.05, 3]\ngray_noise_prob: 1\njpeg_range: [30, 95]\n\n# the second degradation process\nsecond_blur_prob: 1\nresize_prob2: [0.3, 0.4, 0.3]  # up, down, keep\nresize_range2: [0.3, 1.2]\ngaussian_noise_prob2: 1\nnoise_range2: [1, 25]\npoisson_scale_range2: [0.05, 2.5]\ngray_noise_prob2: 1\njpeg_range2: [30, 95]\n\ngt_size: 32\nqueue_size: 1\n\n# network structures\nnetwork_g:\n  type: RRDBNet\n  num_in_ch: 3\n  num_out_ch: 3\n  num_feat: 4\n  num_block: 1\n  num_grow_ch: 2\n\n# path\npath:\n  pretrain_network_g: ~\n  param_key_g: params_ema\n  strict_load_g: true\n  resume_state: ~\n\n# training settings\ntrain:\n  ema_decay: 0.999\n  optim_g:\n    type: Adam\n    lr: !!float 2e-4\n    weight_decay: 0\n    betas: [0.9, 0.99]\n\n  scheduler:\n    type: MultiStepLR\n    milestones: [1000000]\n    gamma: 0.5\n\n  total_iter: 1000000\n  warmup_iter: -1  # no warm up\n\n  # losses\n  pixel_opt:\n    type: L1Loss\n    loss_weight: 1.0\n    reduction: mean\n\n\n# validation settings\nval:\n  val_freq: !!float 5e3\n  save_img: False\n"
  },
  {
    "path": "tests/test_dataset.py",
    "content": "import pytest\nimport yaml\n\nfrom realesrgan.data.realesrgan_dataset import RealESRGANDataset\nfrom realesrgan.data.realesrgan_paired_dataset import RealESRGANPairedDataset\n\n\ndef test_realesrgan_dataset():\n\n    with open('tests/data/test_realesrgan_dataset.yml', mode='r') as f:\n        opt = yaml.load(f, Loader=yaml.FullLoader)\n\n    dataset = RealESRGANDataset(opt)\n    assert dataset.io_backend_opt['type'] == 'disk'  # io backend\n    assert len(dataset) == 2  # whether to read correct meta info\n    assert dataset.kernel_list == [\n        'iso', 'aniso', 'generalized_iso', 'generalized_aniso', 'plateau_iso', 'plateau_aniso'\n    ]  # correct initialization the degradation configurations\n    assert dataset.betag_range2 == [0.5, 4]\n\n    # test __getitem__\n    result = dataset.__getitem__(0)\n    # check returned keys\n    expected_keys = ['gt', 'kernel1', 'kernel2', 'sinc_kernel', 'gt_path']\n    assert set(expected_keys).issubset(set(result.keys()))\n    # check shape and contents\n    assert result['gt'].shape == (3, 400, 400)\n    assert result['kernel1'].shape == (21, 21)\n    assert result['kernel2'].shape == (21, 21)\n    assert result['sinc_kernel'].shape == (21, 21)\n    assert result['gt_path'] == 'tests/data/gt/baboon.png'\n\n    # ------------------ test lmdb backend -------------------- #\n    opt['dataroot_gt'] = 'tests/data/gt.lmdb'\n    opt['io_backend']['type'] = 'lmdb'\n\n    dataset = RealESRGANDataset(opt)\n    assert dataset.io_backend_opt['type'] == 'lmdb'  # io backend\n    assert len(dataset.paths) == 2  # whether to read correct meta info\n    assert dataset.kernel_list == [\n        'iso', 'aniso', 'generalized_iso', 'generalized_aniso', 'plateau_iso', 'plateau_aniso'\n    ]  # correct initialization the degradation configurations\n    assert dataset.betag_range2 == [0.5, 4]\n\n    # test __getitem__\n    result = dataset.__getitem__(1)\n    # check returned keys\n    expected_keys = ['gt', 'kernel1', 'kernel2', 'sinc_kernel', 'gt_path']\n    assert set(expected_keys).issubset(set(result.keys()))\n    # check shape and contents\n    assert result['gt'].shape == (3, 400, 400)\n    assert result['kernel1'].shape == (21, 21)\n    assert result['kernel2'].shape == (21, 21)\n    assert result['sinc_kernel'].shape == (21, 21)\n    assert result['gt_path'] == 'comic'\n\n    # ------------------ test with sinc_prob = 0 -------------------- #\n    opt['dataroot_gt'] = 'tests/data/gt.lmdb'\n    opt['io_backend']['type'] = 'lmdb'\n    opt['sinc_prob'] = 0\n    opt['sinc_prob2'] = 0\n    opt['final_sinc_prob'] = 0\n    dataset = RealESRGANDataset(opt)\n    result = dataset.__getitem__(0)\n    # check returned keys\n    expected_keys = ['gt', 'kernel1', 'kernel2', 'sinc_kernel', 'gt_path']\n    assert set(expected_keys).issubset(set(result.keys()))\n    # check shape and contents\n    assert result['gt'].shape == (3, 400, 400)\n    assert result['kernel1'].shape == (21, 21)\n    assert result['kernel2'].shape == (21, 21)\n    assert result['sinc_kernel'].shape == (21, 21)\n    assert result['gt_path'] == 'baboon'\n\n    # ------------------ lmdb backend should have paths ends with lmdb -------------------- #\n    with pytest.raises(ValueError):\n        opt['dataroot_gt'] = 'tests/data/gt'\n        opt['io_backend']['type'] = 'lmdb'\n        dataset = RealESRGANDataset(opt)\n\n\ndef test_realesrgan_paired_dataset():\n\n    with open('tests/data/test_realesrgan_paired_dataset.yml', mode='r') as f:\n        opt = yaml.load(f, Loader=yaml.FullLoader)\n\n    dataset = RealESRGANPairedDataset(opt)\n    assert dataset.io_backend_opt['type'] == 'disk'  # io backend\n    assert len(dataset) == 2  # whether to read correct meta info\n\n    # test __getitem__\n    result = dataset.__getitem__(0)\n    # check returned keys\n    expected_keys = ['gt', 'lq', 'gt_path', 'lq_path']\n    assert set(expected_keys).issubset(set(result.keys()))\n    # check shape and contents\n    assert result['gt'].shape == (3, 128, 128)\n    assert result['lq'].shape == (3, 32, 32)\n    assert result['gt_path'] == 'tests/data/gt/baboon.png'\n    assert result['lq_path'] == 'tests/data/lq/baboon.png'\n\n    # ------------------ test lmdb backend -------------------- #\n    opt['dataroot_gt'] = 'tests/data/gt.lmdb'\n    opt['dataroot_lq'] = 'tests/data/lq.lmdb'\n    opt['io_backend']['type'] = 'lmdb'\n\n    dataset = RealESRGANPairedDataset(opt)\n    assert dataset.io_backend_opt['type'] == 'lmdb'  # io backend\n    assert len(dataset) == 2  # whether to read correct meta info\n\n    # test __getitem__\n    result = dataset.__getitem__(1)\n    # check returned keys\n    expected_keys = ['gt', 'lq', 'gt_path', 'lq_path']\n    assert set(expected_keys).issubset(set(result.keys()))\n    # check shape and contents\n    assert result['gt'].shape == (3, 128, 128)\n    assert result['lq'].shape == (3, 32, 32)\n    assert result['gt_path'] == 'comic'\n    assert result['lq_path'] == 'comic'\n\n    # ------------------ test paired_paths_from_folder -------------------- #\n    opt['dataroot_gt'] = 'tests/data/gt'\n    opt['dataroot_lq'] = 'tests/data/lq'\n    opt['io_backend'] = dict(type='disk')\n    opt['meta_info'] = None\n\n    dataset = RealESRGANPairedDataset(opt)\n    assert dataset.io_backend_opt['type'] == 'disk'  # io backend\n    assert len(dataset) == 2  # whether to read correct meta info\n\n    # test __getitem__\n    result = dataset.__getitem__(0)\n    # check returned keys\n    expected_keys = ['gt', 'lq', 'gt_path', 'lq_path']\n    assert set(expected_keys).issubset(set(result.keys()))\n    # check shape and contents\n    assert result['gt'].shape == (3, 128, 128)\n    assert result['lq'].shape == (3, 32, 32)\n\n    # ------------------ test normalization -------------------- #\n    dataset.mean = [0.5, 0.5, 0.5]\n    dataset.std = [0.5, 0.5, 0.5]\n    # test __getitem__\n    result = dataset.__getitem__(0)\n    # check returned keys\n    expected_keys = ['gt', 'lq', 'gt_path', 'lq_path']\n    assert set(expected_keys).issubset(set(result.keys()))\n    # check shape and contents\n    assert result['gt'].shape == (3, 128, 128)\n    assert result['lq'].shape == (3, 32, 32)\n"
  },
  {
    "path": "tests/test_discriminator_arch.py",
    "content": "import torch\n\nfrom realesrgan.archs.discriminator_arch import UNetDiscriminatorSN\n\n\ndef test_unetdiscriminatorsn():\n    \"\"\"Test arch: UNetDiscriminatorSN.\"\"\"\n\n    # model init and forward (cpu)\n    net = UNetDiscriminatorSN(num_in_ch=3, num_feat=4, skip_connection=True)\n    img = torch.rand((1, 3, 32, 32), dtype=torch.float32)\n    output = net(img)\n    assert output.shape == (1, 1, 32, 32)\n\n    # model init and forward (gpu)\n    if torch.cuda.is_available():\n        net.cuda()\n        output = net(img.cuda())\n        assert output.shape == (1, 1, 32, 32)\n"
  },
  {
    "path": "tests/test_model.py",
    "content": "import torch\nimport yaml\nfrom basicsr.archs.rrdbnet_arch import RRDBNet\nfrom basicsr.data.paired_image_dataset import PairedImageDataset\nfrom basicsr.losses.losses import GANLoss, L1Loss, PerceptualLoss\n\nfrom realesrgan.archs.discriminator_arch import UNetDiscriminatorSN\nfrom realesrgan.models.realesrgan_model import RealESRGANModel\nfrom realesrgan.models.realesrnet_model import RealESRNetModel\n\n\ndef test_realesrnet_model():\n    with open('tests/data/test_realesrnet_model.yml', mode='r') as f:\n        opt = yaml.load(f, Loader=yaml.FullLoader)\n\n    # build model\n    model = RealESRNetModel(opt)\n    # test attributes\n    assert model.__class__.__name__ == 'RealESRNetModel'\n    assert isinstance(model.net_g, RRDBNet)\n    assert isinstance(model.cri_pix, L1Loss)\n    assert isinstance(model.optimizers[0], torch.optim.Adam)\n\n    # prepare data\n    gt = torch.rand((1, 3, 32, 32), dtype=torch.float32)\n    kernel1 = torch.rand((1, 5, 5), dtype=torch.float32)\n    kernel2 = torch.rand((1, 5, 5), dtype=torch.float32)\n    sinc_kernel = torch.rand((1, 5, 5), dtype=torch.float32)\n    data = dict(gt=gt, kernel1=kernel1, kernel2=kernel2, sinc_kernel=sinc_kernel)\n    model.feed_data(data)\n    # check dequeue\n    model.feed_data(data)\n    # check data shape\n    assert model.lq.shape == (1, 3, 8, 8)\n    assert model.gt.shape == (1, 3, 32, 32)\n\n    # change probability to test if-else\n    model.opt['gaussian_noise_prob'] = 0\n    model.opt['gray_noise_prob'] = 0\n    model.opt['second_blur_prob'] = 0\n    model.opt['gaussian_noise_prob2'] = 0\n    model.opt['gray_noise_prob2'] = 0\n    model.feed_data(data)\n    # check data shape\n    assert model.lq.shape == (1, 3, 8, 8)\n    assert model.gt.shape == (1, 3, 32, 32)\n\n    # ----------------- test nondist_validation -------------------- #\n    # construct dataloader\n    dataset_opt = dict(\n        name='Demo',\n        dataroot_gt='tests/data/gt',\n        dataroot_lq='tests/data/lq',\n        io_backend=dict(type='disk'),\n        scale=4,\n        phase='val')\n    dataset = PairedImageDataset(dataset_opt)\n    dataloader = torch.utils.data.DataLoader(dataset=dataset, batch_size=1, shuffle=False, num_workers=0)\n    assert model.is_train is True\n    model.nondist_validation(dataloader, 1, None, False)\n    assert model.is_train is True\n\n\ndef test_realesrgan_model():\n    with open('tests/data/test_realesrgan_model.yml', mode='r') as f:\n        opt = yaml.load(f, Loader=yaml.FullLoader)\n\n    # build model\n    model = RealESRGANModel(opt)\n    # test attributes\n    assert model.__class__.__name__ == 'RealESRGANModel'\n    assert isinstance(model.net_g, RRDBNet)  # generator\n    assert isinstance(model.net_d, UNetDiscriminatorSN)  # discriminator\n    assert isinstance(model.cri_pix, L1Loss)\n    assert isinstance(model.cri_perceptual, PerceptualLoss)\n    assert isinstance(model.cri_gan, GANLoss)\n    assert isinstance(model.optimizers[0], torch.optim.Adam)\n    assert isinstance(model.optimizers[1], torch.optim.Adam)\n\n    # prepare data\n    gt = torch.rand((1, 3, 32, 32), dtype=torch.float32)\n    kernel1 = torch.rand((1, 5, 5), dtype=torch.float32)\n    kernel2 = torch.rand((1, 5, 5), dtype=torch.float32)\n    sinc_kernel = torch.rand((1, 5, 5), dtype=torch.float32)\n    data = dict(gt=gt, kernel1=kernel1, kernel2=kernel2, sinc_kernel=sinc_kernel)\n    model.feed_data(data)\n    # check dequeue\n    model.feed_data(data)\n    # check data shape\n    assert model.lq.shape == (1, 3, 8, 8)\n    assert model.gt.shape == (1, 3, 32, 32)\n\n    # change probability to test if-else\n    model.opt['gaussian_noise_prob'] = 0\n    model.opt['gray_noise_prob'] = 0\n    model.opt['second_blur_prob'] = 0\n    model.opt['gaussian_noise_prob2'] = 0\n    model.opt['gray_noise_prob2'] = 0\n    model.feed_data(data)\n    # check data shape\n    assert model.lq.shape == (1, 3, 8, 8)\n    assert model.gt.shape == (1, 3, 32, 32)\n\n    # ----------------- test nondist_validation -------------------- #\n    # construct dataloader\n    dataset_opt = dict(\n        name='Demo',\n        dataroot_gt='tests/data/gt',\n        dataroot_lq='tests/data/lq',\n        io_backend=dict(type='disk'),\n        scale=4,\n        phase='val')\n    dataset = PairedImageDataset(dataset_opt)\n    dataloader = torch.utils.data.DataLoader(dataset=dataset, batch_size=1, shuffle=False, num_workers=0)\n    assert model.is_train is True\n    model.nondist_validation(dataloader, 1, None, False)\n    assert model.is_train is True\n\n    # ----------------- test optimize_parameters -------------------- #\n    model.feed_data(data)\n    model.optimize_parameters(1)\n    assert model.output.shape == (1, 3, 32, 32)\n    assert isinstance(model.log_dict, dict)\n    # check returned keys\n    expected_keys = ['l_g_pix', 'l_g_percep', 'l_g_gan', 'l_d_real', 'out_d_real', 'l_d_fake', 'out_d_fake']\n    assert set(expected_keys).issubset(set(model.log_dict.keys()))\n"
  },
  {
    "path": "tests/test_utils.py",
    "content": "import numpy as np\nfrom basicsr.archs.rrdbnet_arch import RRDBNet\n\nfrom realesrgan.utils import RealESRGANer\n\n\ndef test_realesrganer():\n    # initialize with default model\n    restorer = RealESRGANer(\n        scale=4,\n        model_path='experiments/pretrained_models/RealESRGAN_x4plus.pth',\n        model=None,\n        tile=10,\n        tile_pad=10,\n        pre_pad=2,\n        half=False)\n    assert isinstance(restorer.model, RRDBNet)\n    assert restorer.half is False\n    # initialize with user-defined model\n    model = RRDBNet(num_in_ch=3, num_out_ch=3, num_feat=64, num_block=6, num_grow_ch=32, scale=4)\n    restorer = RealESRGANer(\n        scale=4,\n        model_path='experiments/pretrained_models/RealESRGAN_x4plus_anime_6B.pth',\n        model=model,\n        tile=10,\n        tile_pad=10,\n        pre_pad=2,\n        half=True)\n    # test attribute\n    assert isinstance(restorer.model, RRDBNet)\n    assert restorer.half is True\n\n    # ------------------ test pre_process ---------------- #\n    img = np.random.random((12, 12, 3)).astype(np.float32)\n    restorer.pre_process(img)\n    assert restorer.img.shape == (1, 3, 14, 14)\n    # with modcrop\n    restorer.scale = 1\n    restorer.pre_process(img)\n    assert restorer.img.shape == (1, 3, 16, 16)\n\n    # ------------------ test process ---------------- #\n    restorer.process()\n    assert restorer.output.shape == (1, 3, 64, 64)\n\n    # ------------------ test post_process ---------------- #\n    restorer.mod_scale = 4\n    output = restorer.post_process()\n    assert output.shape == (1, 3, 60, 60)\n\n    # ------------------ test tile_process ---------------- #\n    restorer.scale = 4\n    img = np.random.random((12, 12, 3)).astype(np.float32)\n    restorer.pre_process(img)\n    restorer.tile_process()\n    assert restorer.output.shape == (1, 3, 64, 64)\n\n    # ------------------ test enhance ---------------- #\n    img = np.random.random((12, 12, 3)).astype(np.float32)\n    result = restorer.enhance(img, outscale=2)\n    assert result[0].shape == (24, 24, 3)\n    assert result[1] == 'RGB'\n\n    # ------------------ test enhance with 16-bit image---------------- #\n    img = np.random.random((4, 4, 3)).astype(np.uint16) + 512\n    result = restorer.enhance(img, outscale=2)\n    assert result[0].shape == (8, 8, 3)\n    assert result[1] == 'RGB'\n\n    # ------------------ test enhance with gray image---------------- #\n    img = np.random.random((4, 4)).astype(np.float32)\n    result = restorer.enhance(img, outscale=2)\n    assert result[0].shape == (8, 8)\n    assert result[1] == 'L'\n\n    # ------------------ test enhance with RGBA---------------- #\n    img = np.random.random((4, 4, 4)).astype(np.float32)\n    result = restorer.enhance(img, outscale=2)\n    assert result[0].shape == (8, 8, 4)\n    assert result[1] == 'RGBA'\n\n    # ------------------ test enhance with RGBA, alpha_upsampler---------------- #\n    restorer.tile_size = 0\n    img = np.random.random((4, 4, 4)).astype(np.float32)\n    result = restorer.enhance(img, outscale=2, alpha_upsampler=None)\n    assert result[0].shape == (8, 8, 4)\n    assert result[1] == 'RGBA'\n"
  }
]