diff --git a/.gitattributes b/.gitattributes index a6344aac8c09253b3b630fb776ae94478aa0275b..3e15efd719e55ebabe8454de9919507fc0c87be9 100644 --- a/.gitattributes +++ b/.gitattributes @@ -25,11 +25,12 @@ *.safetensors filter=lfs diff=lfs merge=lfs -text saved_model/**/* filter=lfs diff=lfs merge=lfs -text *.tar.* filter=lfs diff=lfs merge=lfs -text -*.tar filter=lfs diff=lfs merge=lfs -text *.tflite filter=lfs diff=lfs merge=lfs -text *.tgz filter=lfs diff=lfs merge=lfs -text *.wasm filter=lfs diff=lfs merge=lfs -text *.xz filter=lfs diff=lfs merge=lfs -text -*.zip filter=lfs diff=lfs merge=lfs -text *.zst filter=lfs diff=lfs merge=lfs -text *tfevents* filter=lfs diff=lfs merge=lfs -text +*zip filter=lfs diff=lfs merge=lfs -text +SuperResolutionAnimeDiffusion.zip filter=lfs diff=lfs merge=lfs -text +random_examples.zip filter=lfs diff=lfs merge=lfs -text diff --git a/.gitignore b/.gitignore new file mode 100644 index 0000000000000000000000000000000000000000..98c2d2047b6d29e3897102709df995a10b1bea8b --- /dev/null +++ b/.gitignore @@ -0,0 +1,161 @@ +# dev files +*.cache +*.dev.py +*.mv +state_dict/ +integrated_datasets/ +*.results +*.tokenizer +*.model +*.state_dict +*.config +*.args +*.gz +*.bin +*.result.txt +*.DS_Store +*.tmp +*.args.txt +*.summary.txt +*.dat +*.graph +# Byte-compiled / optimized / DLL files +__pycache__/ +*.py[cod] +*$py.class +*.pyc +experiments/ +tests/ +*.result.json +.idea/ +imgs/ + +# Embedding +glove.840B.300d.txt +glove.42B.300d.txt +glove.twitter.27B.txt + +# project main files +release_note.json + +# C extensions +*.so + +# Distribution / packaging +.Python +build/ +develop-eggs/ +dist/ +downloads/ +eggs/ +.eggs/ +lib64/ +parts/ +sdist/ +var/ +wheels/ +pip-wheel-metadata/ +share/python-wheels/ +*.egg-info/ +.installed.cfg +*.egg +MANIFEST + +# PyInstaller +# Usually these files are written by a python script from a template +# before PyInstaller builds the exe, so as to inject date/other infos into it. +*.manifest +*.spec + +# Installer training_logs +pip-log.txt +pip-delete-this-directory.txt + +# Unit test / coverage reports +htmlcov/ +.tox/ +.nox/ +.coverage +.coverage.* +.cache +nosetests.xml +coverage.xml +*.cover +*.py,cover +.hypothesis/ +.pytest_cache/ + +# Translations +*.mo +*.pot + +# Django stuff: +*.log +local_settings.py +db.sqlite3 +db.sqlite3-journal + +# Flask stuff: +instance/ +.webassets-cache + +# Scrapy stuff: +.scrapy + +# Sphinx documentation +docs/_build/ + +# PyBuilder +target/ + +# Jupyter Notebook +.ipynb_checkpoints + +# IPython +profile_default/ +ipython_config.py + +# pyenv +.python-version + +# pipenv +# According to pypa/pipenv#598, it is recommended to include Pipfile.lock in version control. +# However, in case of collaboration, if having platform-specific dependencies or dependencies +# having no cross-platform support, pipenv may install dependencies that don't work, or not +# install all needed dependencies. +#Pipfile.lock + +# celery beat schedule file +celerybeat-schedule + +# SageMath parsed files +*.sage.py + +# Environments +.env +.venv +env/ +venv/ +ENV/ +env.bak/ +venv.bak/ + +# Spyder project settings +.spyderproject +.spyproject + +# Rope project settings +.ropeproject + +# mkdocs documentation +/site + +# mypy +.mypy_cache/ +.dmypy.json +dmypy.json + +# Pyre type checker +.pyre/ +.DS_Store +examples/.DS_Store diff --git a/README.md b/README.md index beba3fc4986cd0059b4d6a37297907ed41dff53c..a8c0364b05ee13759f0ef3d3e4b911de523d5414 100644 --- a/README.md +++ b/README.md @@ -9,4 +9,126 @@ app_file: app.py pinned: false --- -Check out the configuration reference at https://huggingface.co/docs/hub/spaces-config-reference +# If you have a GPU, try the [Stable Diffusion WebUI](https://github.com/yangheng95/stable-diffusion-webui) + + +# [Online Web Demo](https://huggingface.co/spaces/yangheng/Super-Resolution-Anime-Diffusion) + +This is demo forked from https://huggingface.co/Linaqruf/anything-v3.0. + +## Super Resolution Anime Diffusion +At this moment, many diffusion models can only generate <1024 width and length pictures. +I integrated the Super Resolution with [Anything diffusion model](https://huggingface.co/Linaqruf/anything-v3.0) to produce high resolution pictures. +Thanks to the open-source project: https://github.com/yu45020/Waifu2x + + +## Modifications +1. Disable the safety checker to save time and memory. You need to abide the original rules of the model. +2. Add the Super Resolution function to the model. +3. Add batch generation function to the model (see inference.py). + +## Install +1. Install [Anaconda](https://www.anaconda.com/products/distribution) or [Miniconda](https://docs.conda.io/en/latest/miniconda.html) +2. create a conda environment: +```bash +conda create -n diffusion python=3.9 +conda activate diffusion +``` +3. install requirements: +```ash +conda install pytorch pytorch-cuda=11.7 -c pytorch -c nvidia +pip install -r requirements.txt +``` +4. Run web demo: +``` +python app.py +``` +5. or run batch anime-generation +``` +python inference.py +``` +see the source code for details, you can set scale factor to magnify pictures + +## Random Examples (512*768) x4 scale factor +![Anime Girl](./random_examples/1.png) +![Anime Girl](./random_examples/2.png) +# Origin README +--- +language: +- en +license: creativeml-openrail-m +tags: +- stable-diffusion +- stable-diffusion-diffusers +- text-to-image +- diffusers +inference: true +--- + +# Anything V3 + +Welcome to Anything V3 - a latent diffusion model for weebs. This model is intended to produce high-quality, highly detailed anime style with just a few prompts. Like other anime-style Stable Diffusion models, it also supports danbooru tags to generate images. + +e.g. **_1girl, white hair, golden eyes, beautiful eyes, detail, flower meadow, cumulonimbus clouds, lighting, detailed sky, garden_** + +## Gradio + +We support a [Gradio](https://github.com/gradio-app/gradio) Web UI to run Anything-V3.0: + +[Open in Spaces](https://huggingface.co/spaces/akhaliq/anything-v3.0) + + + +## 🧨 Diffusers + +This model can be used just like any other Stable Diffusion model. For more information, +please have a look at the [Stable Diffusion](https://huggingface.co/docs/diffusers/api/pipelines/stable_diffusion). + +You can also export the model to [ONNX](https://huggingface.co/docs/diffusers/optimization/onnx), [MPS](https://huggingface.co/docs/diffusers/optimization/mps) and/or [FLAX/JAX](). + +```python +from diffusers import StableDiffusionPipeline +import torch + +model_id = "Linaqruf/anything-v3.0" +pipe = StableDiffusionPipeline.from_pretrained(model_id, torch_dtype=torch.float16) +pipe = pipe.to("cuda") + +prompt = "pikachu" +image = pipe(prompt).images[0] + +image.save("./pikachu.png") +``` + +## Examples + +Below are some examples of images generated using this model: + +**Anime Girl:** +![Anime Girl](https://huggingface.co/Linaqruf/anything-v3.0/resolve/main/1girl.png) +``` +1girl, brown hair, green eyes, colorful, autumn, cumulonimbus clouds, lighting, blue sky, falling leaves, garden +Steps: 50, Sampler: DDIM, CFG scale: 12 +``` +**Anime Boy:** +![Anime Boy](https://huggingface.co/Linaqruf/anything-v3.0/resolve/main/1boy.png) +``` +1boy, medium hair, blonde hair, blue eyes, bishounen, colorful, autumn, cumulonimbus clouds, lighting, blue sky, falling leaves, garden +Steps: 50, Sampler: DDIM, CFG scale: 12 +``` +**Scenery:** +![Scenery](https://huggingface.co/Linaqruf/anything-v3.0/resolve/main/scenery.png) +``` +scenery, shibuya tokyo, post-apocalypse, ruins, rust, sky, skyscraper, abandoned, blue sky, broken window, building, cloud, crane machine, outdoors, overgrown, pillar, sunset +Steps: 50, Sampler: DDIM, CFG scale: 12 +``` + +## License + +This model is open access and available to all, with a CreativeML OpenRAIL-M license further specifying rights and usage. +The CreativeML OpenRAIL License specifies: + +1. You can't use the model to deliberately produce nor share illegal or harmful outputs or content +2. The authors claims no rights on the outputs you generate, you are free to use them and are accountable for their use which must not go against the provisions set in the license +3. You may re-distribute the weights and use the model commercially and/or as a service. If you do, please be aware you have to include the same use restrictions as the ones in the license and share a copy of the CreativeML OpenRAIL-M to all your users (please read the license entirely and carefully) +[Please read the full license here](https://huggingface.co/spaces/CompVis/stable-diffusion-license) diff --git a/README_HG.md b/README_HG.md new file mode 100644 index 0000000000000000000000000000000000000000..99a0776d1a4669fa8387cc77e162c60084100a92 --- /dev/null +++ b/README_HG.md @@ -0,0 +1,12 @@ +--- +title: Anything V3.0 +emoji: 🏃 +colorFrom: gray +colorTo: yellow +sdk: gradio +sdk_version: 3.10.1 +app_file: app.py +pinned: false +--- + +Check out the configuration reference at https://huggingface.co/docs/hub/spaces-config-reference diff --git a/RealESRGANv030/.github/workflows/no-response.yml b/RealESRGANv030/.github/workflows/no-response.yml new file mode 100644 index 0000000000000000000000000000000000000000..fa702eeacff13fe8475b0e102a8b8c37602f3963 --- /dev/null +++ b/RealESRGANv030/.github/workflows/no-response.yml @@ -0,0 +1,33 @@ +name: No Response + +# TODO: it seems not to work +# Modified from: https://raw.githubusercontent.com/github/docs/main/.github/workflows/no-response.yaml + +# **What it does**: Closes issues that don't have enough information to be actionable. +# **Why we have it**: To remove the need for maintainers to remember to check back on issues periodically +# to see if contributors have responded. +# **Who does it impact**: Everyone that works on docs or docs-internal. + +on: + issue_comment: + types: [created] + + schedule: + # Schedule for five minutes after the hour every hour + - cron: '5 * * * *' + +jobs: + noResponse: + runs-on: ubuntu-latest + steps: + - uses: lee-dohm/no-response@v0.5.0 + with: + token: ${{ github.token }} + closeComment: > + This issue has been automatically closed because there has been no response + to our request for more information from the original author. With only the + information that is currently in the issue, we don't have enough information + to take action. Please reach out if you have or find the answers we need so + that we can investigate further. + If you still have questions, please improve your description and re-open it. + Thanks :-) diff --git a/RealESRGANv030/.github/workflows/publish-pip.yml b/RealESRGANv030/.github/workflows/publish-pip.yml new file mode 100644 index 0000000000000000000000000000000000000000..f3c8e574fd59fa9a4f3925eee9ee590dbdca965a --- /dev/null +++ b/RealESRGANv030/.github/workflows/publish-pip.yml @@ -0,0 +1,33 @@ +name: PyPI Publish + +on: push + +jobs: + build-n-publish: + runs-on: ubuntu-latest + if: startsWith(github.event.ref, 'refs/tags') + + steps: + - uses: actions/checkout@v2 + - name: Set up Python 3.8 + uses: actions/setup-python@v1 + with: + python-version: 3.8 + - name: Upgrade pip + run: pip install pip --upgrade + - name: Install PyTorch (cpu) + run: pip install torch==1.7.0+cpu torchvision==0.8.1+cpu -f https://download.pytorch.org/whl/torch_stable.html + - name: Install dependencies + run: | + pip install basicsr + pip install facexlib + pip install gfpgan + pip install -r requirements.txt + - name: Build and install + run: rm -rf .eggs && pip install -e . + - name: Build for distribution + run: python setup.py sdist bdist_wheel + - name: Publish distribution to PyPI + uses: pypa/gh-action-pypi-publish@master + with: + password: ${{ secrets.PYPI_API_TOKEN }} diff --git a/RealESRGANv030/.github/workflows/pylint.yml b/RealESRGANv030/.github/workflows/pylint.yml new file mode 100644 index 0000000000000000000000000000000000000000..2084d1aa236b948d8734b6762d3e01054580001a --- /dev/null +++ b/RealESRGANv030/.github/workflows/pylint.yml @@ -0,0 +1,31 @@ +name: PyLint + +on: [push, pull_request] + +jobs: + build: + + runs-on: ubuntu-latest + strategy: + matrix: + python-version: [3.8] + + steps: + - uses: actions/checkout@v2 + - name: Set up Python ${{ matrix.python-version }} + uses: actions/setup-python@v2 + with: + python-version: ${{ matrix.python-version }} + + - name: Install dependencies + run: | + python -m pip install --upgrade pip + pip install codespell flake8 isort yapf + + # modify the folders accordingly + - name: Lint + run: | + codespell + flake8 . + isort --check-only --diff realesrgan/ scripts/ inference_realesrgan.py setup.py + yapf -r -d realesrgan/ scripts/ inference_realesrgan.py setup.py diff --git a/RealESRGANv030/.github/workflows/release.yml b/RealESRGANv030/.github/workflows/release.yml new file mode 100644 index 0000000000000000000000000000000000000000..18be9e5c31768ab3be3e1075500a35bcb5783434 --- /dev/null +++ b/RealESRGANv030/.github/workflows/release.yml @@ -0,0 +1,41 @@ +name: release +on: + push: + tags: + - '*' + +jobs: + build: + permissions: write-all + name: Create Release + runs-on: ubuntu-latest + steps: + - name: Checkout code + uses: actions/checkout@v2 + - name: Create Release + id: create_release + uses: actions/create-release@v1 + env: + GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }} + with: + tag_name: ${{ github.ref }} + release_name: Real-ESRGAN ${{ github.ref }} Release Note + body: | + 🚀 See you again 😸 + 🚀Have a nice day 😸 and happy everyday 😃 + 🚀 Long time no see ☄️ + + ✨ **Highlights** + ✅ [Features] Support ... + + 🐛 **Bug Fixes** + + 🌴 **Improvements** + + 📢📢📢 + +

+ +

+ draft: true + prerelease: false diff --git a/RealESRGANv030/.gitignore b/RealESRGANv030/.gitignore new file mode 100644 index 0000000000000000000000000000000000000000..bb86ed0fd8a71305c7d8cc794bfa4591a5ccbc99 --- /dev/null +++ b/RealESRGANv030/.gitignore @@ -0,0 +1,140 @@ +# ignored folders +datasets/* +experiments/* +results/* +tb_logger/* +wandb/* +tmp/* +weights/* + +version.py + +# Byte-compiled / optimized / DLL files +__pycache__/ +*.py[cod] +*$py.class + +# C extensions +*.so + +# Distribution / packaging +.Python +build/ +develop-eggs/ +dist/ +downloads/ +eggs/ +.eggs/ +lib/ +lib64/ +parts/ +sdist/ +var/ +wheels/ +pip-wheel-metadata/ +share/python-wheels/ +*.egg-info/ +.installed.cfg +*.egg +MANIFEST + +# PyInstaller +# Usually these files are written by a python script from a template +# before PyInstaller builds the exe, so as to inject date/other infos into it. +*.manifest +*.spec + +# Installer logs +pip-log.txt +pip-delete-this-directory.txt + +# Unit test / coverage reports +htmlcov/ +.tox/ +.nox/ +.coverage +.coverage.* +.cache +nosetests.xml +coverage.xml +*.cover +*.py,cover +.hypothesis/ +.pytest_cache/ + +# Translations +*.mo +*.pot + +# Django stuff: +*.log +local_settings.py +db.sqlite3 +db.sqlite3-journal + +# Flask stuff: +instance/ +.webassets-cache + +# Scrapy stuff: +.scrapy + +# Sphinx documentation +docs/_build/ + +# PyBuilder +target/ + +# Jupyter Notebook +.ipynb_checkpoints + +# IPython +profile_default/ +ipython_config.py + +# pyenv +.python-version + +# pipenv +# According to pypa/pipenv#598, it is recommended to include Pipfile.lock in version control. +# However, in case of collaboration, if having platform-specific dependencies or dependencies +# having no cross-platform support, pipenv may install dependencies that don't work, or not +# install all needed dependencies. +#Pipfile.lock + +# PEP 582; used by e.g. github.com/David-OConnor/pyflow +__pypackages__/ + +# Celery stuff +celerybeat-schedule +celerybeat.pid + +# SageMath parsed files +*.sage.py + +# Environments +.env +.venv +env/ +venv/ +ENV/ +env.bak/ +venv.bak/ + +# Spyder project settings +.spyderproject +.spyproject + +# Rope project settings +.ropeproject + +# mkdocs documentation +/site + +# mypy +.mypy_cache/ +.dmypy.json +dmypy.json + +# Pyre type checker +.pyre/ diff --git a/RealESRGANv030/.pre-commit-config.yaml b/RealESRGANv030/.pre-commit-config.yaml new file mode 100644 index 0000000000000000000000000000000000000000..d221d29fbaac74bef1c0cd910ce8d8b6526181b8 --- /dev/null +++ b/RealESRGANv030/.pre-commit-config.yaml @@ -0,0 +1,46 @@ +repos: + # flake8 + - repo: https://github.com/PyCQA/flake8 + rev: 3.8.3 + hooks: + - id: flake8 + args: ["--config=setup.cfg", "--ignore=W504, W503"] + + # modify known_third_party + - repo: https://github.com/asottile/seed-isort-config + rev: v2.2.0 + hooks: + - id: seed-isort-config + + # isort + - repo: https://github.com/timothycrosley/isort + rev: 5.2.2 + hooks: + - id: isort + + # yapf + - repo: https://github.com/pre-commit/mirrors-yapf + rev: v0.30.0 + hooks: + - id: yapf + + # codespell + - repo: https://github.com/codespell-project/codespell + rev: v2.1.0 + hooks: + - id: codespell + + # pre-commit-hooks + - repo: https://github.com/pre-commit/pre-commit-hooks + rev: v3.2.0 + hooks: + - id: trailing-whitespace # Trim trailing whitespace + - id: check-yaml # Attempt to load all yaml files to verify syntax + - id: check-merge-conflict # Check for files that contain merge conflict strings + - id: double-quote-string-fixer # Replace double quoted strings with single quoted strings + - id: end-of-file-fixer # Make sure files end in a newline and only a newline + - id: requirements-txt-fixer # Sort entries in requirements.txt and remove incorrect entry for pkg-resources==0.0.0 + - id: fix-encoding-pragma # Remove the coding pragma: # -*- coding: utf-8 -*- + args: ["--remove"] + - id: mixed-line-ending # Replace or check mixed line ending + args: ["--fix=lf"] diff --git a/RealESRGANv030/.vscode/settings.json b/RealESRGANv030/.vscode/settings.json new file mode 100644 index 0000000000000000000000000000000000000000..b12635534688a8a8c69033d81fad96ef734ea6bb --- /dev/null +++ b/RealESRGANv030/.vscode/settings.json @@ -0,0 +1,19 @@ +{ + "files.trimTrailingWhitespace": true, + "editor.wordWrap": "on", + "editor.rulers": [ + 80, + 120 + ], + "editor.renderWhitespace": "all", + "editor.renderControlCharacters": true, + "python.formatting.provider": "yapf", + "python.formatting.yapfArgs": [ + "--style", + "{BASED_ON_STYLE = pep8, BLANK_LINE_BEFORE_NESTED_CLASS_OR_DEF = true, SPLIT_BEFORE_EXPRESSION_AFTER_OPENING_PAREN = true, COLUMN_LIMIT = 120}" + ], + "python.linting.flake8Enabled": true, + "python.linting.flake8Args": [ + "max-line-length=120" + ], +} diff --git a/RealESRGANv030/CODE_OF_CONDUCT.md b/RealESRGANv030/CODE_OF_CONDUCT.md new file mode 100644 index 0000000000000000000000000000000000000000..e8cc4daa4345590464314889b187d6a2d7a8e20f --- /dev/null +++ b/RealESRGANv030/CODE_OF_CONDUCT.md @@ -0,0 +1,128 @@ +# Contributor Covenant Code of Conduct + +## Our Pledge + +We as members, contributors, and leaders pledge to make participation in our +community a harassment-free experience for everyone, regardless of age, body +size, visible or invisible disability, ethnicity, sex characteristics, gender +identity and expression, level of experience, education, socio-economic status, +nationality, personal appearance, race, religion, or sexual identity +and orientation. + +We pledge to act and interact in ways that contribute to an open, welcoming, +diverse, inclusive, and healthy community. + +## Our Standards + +Examples of behavior that contributes to a positive environment for our +community include: + +* Demonstrating empathy and kindness toward other people +* Being respectful of differing opinions, viewpoints, and experiences +* Giving and gracefully accepting constructive feedback +* Accepting responsibility and apologizing to those affected by our mistakes, + and learning from the experience +* Focusing on what is best not just for us as individuals, but for the + overall community + +Examples of unacceptable behavior include: + +* The use of sexualized language or imagery, and sexual attention or + advances of any kind +* Trolling, insulting or derogatory comments, and personal or political attacks +* Public or private harassment +* Publishing others' private information, such as a physical or email + address, without their explicit permission +* Other conduct which could reasonably be considered inappropriate in a + professional setting + +## Enforcement Responsibilities + +Community leaders are responsible for clarifying and enforcing our standards of +acceptable behavior and will take appropriate and fair corrective action in +response to any behavior that they deem inappropriate, threatening, offensive, +or harmful. + +Community leaders have the right and responsibility to remove, edit, or reject +comments, commits, code, wiki edits, issues, and other contributions that are +not aligned to this Code of Conduct, and will communicate reasons for moderation +decisions when appropriate. + +## Scope + +This Code of Conduct applies within all community spaces, and also applies when +an individual is officially representing the community in public spaces. +Examples of representing our community include using an official e-mail address, +posting via an official social media account, or acting as an appointed +representative at an online or offline event. + +## Enforcement + +Instances of abusive, harassing, or otherwise unacceptable behavior may be +reported to the community leaders responsible for enforcement at +xintao.wang@outlook.com or xintaowang@tencent.com. +All complaints will be reviewed and investigated promptly and fairly. + +All community leaders are obligated to respect the privacy and security of the +reporter of any incident. + +## Enforcement Guidelines + +Community leaders will follow these Community Impact Guidelines in determining +the consequences for any action they deem in violation of this Code of Conduct: + +### 1. Correction + +**Community Impact**: Use of inappropriate language or other behavior deemed +unprofessional or unwelcome in the community. + +**Consequence**: A private, written warning from community leaders, providing +clarity around the nature of the violation and an explanation of why the +behavior was inappropriate. A public apology may be requested. + +### 2. Warning + +**Community Impact**: A violation through a single incident or series +of actions. + +**Consequence**: A warning with consequences for continued behavior. No +interaction with the people involved, including unsolicited interaction with +those enforcing the Code of Conduct, for a specified period of time. This +includes avoiding interactions in community spaces as well as external channels +like social media. Violating these terms may lead to a temporary or +permanent ban. + +### 3. Temporary Ban + +**Community Impact**: A serious violation of community standards, including +sustained inappropriate behavior. + +**Consequence**: A temporary ban from any sort of interaction or public +communication with the community for a specified period of time. No public or +private interaction with the people involved, including unsolicited interaction +with those enforcing the Code of Conduct, is allowed during this period. +Violating these terms may lead to a permanent ban. + +### 4. Permanent Ban + +**Community Impact**: Demonstrating a pattern of violation of community +standards, including sustained inappropriate behavior, harassment of an +individual, or aggression toward or disparagement of classes of individuals. + +**Consequence**: A permanent ban from any sort of public interaction within +the community. + +## Attribution + +This Code of Conduct is adapted from the [Contributor Covenant][homepage], +version 2.0, available at +https://www.contributor-covenant.org/version/2/0/code_of_conduct.html. + +Community Impact Guidelines were inspired by [Mozilla's code of conduct +enforcement ladder](https://github.com/mozilla/diversity). + +[homepage]: https://www.contributor-covenant.org + +For answers to common questions about this code of conduct, see the FAQ at +https://www.contributor-covenant.org/faq. Translations are available at +https://www.contributor-covenant.org/translations. diff --git a/RealESRGANv030/LICENSE b/RealESRGANv030/LICENSE new file mode 100644 index 0000000000000000000000000000000000000000..552a1eeaf01f4e7077013ed3496600c608f35202 --- /dev/null +++ b/RealESRGANv030/LICENSE @@ -0,0 +1,29 @@ +BSD 3-Clause License + +Copyright (c) 2021, Xintao Wang +All rights reserved. + +Redistribution and use in source and binary forms, with or without +modification, are permitted provided that the following conditions are met: + +1. Redistributions of source code must retain the above copyright notice, this + list of conditions and the following disclaimer. + +2. Redistributions in binary form must reproduce the above copyright notice, + this list of conditions and the following disclaimer in the documentation + and/or other materials provided with the distribution. + +3. Neither the name of the copyright holder nor the names of its + contributors may be used to endorse or promote products derived from + this software without specific prior written permission. + +THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" +AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE +IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE +DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE +FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL +DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR +SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER +CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, +OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE +OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. diff --git a/RealESRGANv030/MANIFEST.in b/RealESRGANv030/MANIFEST.in new file mode 100644 index 0000000000000000000000000000000000000000..b87c827c894c82b5530c1267ea1d57e86c5f515b --- /dev/null +++ b/RealESRGANv030/MANIFEST.in @@ -0,0 +1,8 @@ +include assets/* +include inputs/* +include scripts/*.py +include inference_realesrgan.py +include VERSION +include LICENSE +include requirements.txt +include weights/README.md diff --git a/RealESRGANv030/README.md b/RealESRGANv030/README.md new file mode 100644 index 0000000000000000000000000000000000000000..118e930c12bffd9e6da1df03180f5c9a8dcaabc3 --- /dev/null +++ b/RealESRGANv030/README.md @@ -0,0 +1,272 @@ +

+ +

+ +##
English | 简体中文
+ +
+ +👀[**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) + +[![download](https://img.shields.io/github/downloads/xinntao/Real-ESRGAN/total.svg)](https://github.com/xinntao/Real-ESRGAN/releases) +[![PyPI](https://img.shields.io/pypi/v/realesrgan)](https://pypi.org/project/realesrgan/) +[![Open issue](https://img.shields.io/github/issues/xinntao/Real-ESRGAN)](https://github.com/xinntao/Real-ESRGAN/issues) +[![Closed issue](https://img.shields.io/github/issues-closed/xinntao/Real-ESRGAN)](https://github.com/xinntao/Real-ESRGAN/issues) +[![LICENSE](https://img.shields.io/github/license/xinntao/Real-ESRGAN.svg)](https://github.com/xinntao/Real-ESRGAN/blob/master/LICENSE) +[![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) +[![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) + +
+ +🔥 **AnimeVideo-v3 model (动漫视频小模型)**. Please see [[*anime video models*](docs/anime_video_model.md)] and [[*comparisons*](docs/anime_comparisons.md)]
+🔥 **RealESRGAN_x4plus_anime_6B** for anime images **(动漫插图模型)**. Please see [[*anime_model*](docs/anime_model.md)] + + +1. :boom: **Update** online Replicate demo: [![Replicate](https://img.shields.io/static/v1?label=Demo&message=Replicate&color=blue)](https://replicate.com/xinntao/realesrgan) +1. 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) +1. 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) + + +Real-ESRGAN aims at developing **Practical Algorithms for General Image/Video Restoration**.
+We extend the powerful ESRGAN to a practical restoration application (namely, Real-ESRGAN), which is trained with pure synthetic data. + +🌌 Thanks for your valuable feedbacks/suggestions. All the feedbacks are updated in [feedback.md](docs/feedback.md). + +--- + +If Real-ESRGAN is helpful, please help to ⭐ this repo or recommend it to your friends 😊
+Other recommended projects:
+▶️ [GFPGAN](https://github.com/TencentARC/GFPGAN): A practical algorithm for real-world face restoration
+▶️ [BasicSR](https://github.com/xinntao/BasicSR): An open-source image and video restoration toolbox
+▶️ [facexlib](https://github.com/xinntao/facexlib): A collection that provides useful face-relation functions.
+▶️ [HandyView](https://github.com/xinntao/HandyView): A PyQt5-based image viewer that is handy for view and comparison
+▶️ [HandyFigure](https://github.com/xinntao/HandyFigure): Open source of paper figures
+ +--- + +### 📖 Real-ESRGAN: Training Real-World Blind Super-Resolution with Pure Synthetic Data + +> [[Paper](https://arxiv.org/abs/2107.10833)]   [[YouTube Video](https://www.youtube.com/watch?v=fxHWoDSSvSc)]   [[B站讲解](https://www.bilibili.com/video/BV1H34y1m7sS/)]   [[Poster](https://xinntao.github.io/projects/RealESRGAN_src/RealESRGAN_poster.pdf)]   [[PPT slides](https://docs.google.com/presentation/d/1QtW6Iy8rm8rGLsJ0Ldti6kP-7Qyzy6XL/edit?usp=sharing&ouid=109799856763657548160&rtpof=true&sd=true)]
+> [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)
+> [Tencent ARC Lab](https://arc.tencent.com/en/ai-demos/imgRestore); Shenzhen Institutes of Advanced Technology, Chinese Academy of Sciences + +

+ +

+ +--- + + +## 🚩 Updates + +- ✅ 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. +- ✅ 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. +- ✅ Add small models for anime videos. More details are in [anime video models](docs/anime_video_model.md). +- ✅ Add the ncnn implementation [Real-ESRGAN-ncnn-vulkan](https://github.com/xinntao/Real-ESRGAN-ncnn-vulkan). +- ✅ 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) +- ✅ 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) +- ✅ Integrate [GFPGAN](https://github.com/TencentARC/GFPGAN) to support **face enhancement**. +- ✅ 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) +- ✅ Support arbitrary scale with `--outscale` (It actually further resizes outputs with `LANCZOS4`). Add *RealESRGAN_x2plus.pth* model. +- ✅ [The inference code](inference_realesrgan.py) supports: 1) **tile** options; 2) images with **alpha channel**; 3) **gray** images; 4) **16-bit** images. +- ✅ The training codes have been released. A detailed guide can be found in [Training.md](docs/Training.md). + +--- + + +## 👀 Demos Videos + +#### Bilibili + +- [大闹天宫片段](https://www.bilibili.com/video/BV1ja41117zb) +- [Anime dance cut 动漫魔性舞蹈](https://www.bilibili.com/video/BV1wY4y1L7hT/) +- [海贼王片段](https://www.bilibili.com/video/BV1i3411L7Gy/) + +#### YouTube + +## 🔧 Dependencies and Installation + +- Python >= 3.7 (Recommend to use [Anaconda](https://www.anaconda.com/download/#linux) or [Miniconda](https://docs.conda.io/en/latest/miniconda.html)) +- [PyTorch >= 1.7](https://pytorch.org/) + +### Installation + +1. Clone repo + + ```bash + git clone https://github.com/xinntao/Real-ESRGAN.git + cd Real-ESRGAN + ``` + +1. Install dependent packages + + ```bash + # Install basicsr - https://github.com/xinntao/BasicSR + # We use BasicSR for both training and inference + pip install basicsr + # facexlib and gfpgan are for face enhancement + pip install facexlib + pip install gfpgan + pip install -r requirements.txt + python setup.py develop + ``` + +--- + +## ⚡ Quick Inference + +There are usually three ways to inference Real-ESRGAN. + +1. [Online inference](#online-inference) +1. [Portable executable files (NCNN)](#portable-executable-files-ncnn) +1. [Python script](#python-script) + +### Online inference + +1. You can try in our website: [ARC Demo](https://arc.tencent.com/en/ai-demos/imgRestore) (now only support RealESRGAN_x4plus_anime_6B) +1. [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**). + +### Portable executable files (NCNN) + +You 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**. + +This executable file is **portable** and includes all the binaries and models required. No CUDA or PyTorch environment is needed.
+ +You can simply run the following command (the Windows example, more information is in the README.md of each executable files): + +```bash +./realesrgan-ncnn-vulkan.exe -i input.jpg -o output.png -n model_name +``` + +We have provided five models: + +1. realesrgan-x4plus (default) +2. realesrnet-x4plus +3. realesrgan-x4plus-anime (optimized for anime images, small model size) +4. realesr-animevideov3 (animation video) + +You can use the `-n` argument for other models, for example, `./realesrgan-ncnn-vulkan.exe -i input.jpg -o output.png -n realesrnet-x4plus` + +#### Usage of portable executable files + +1. Please refer to [Real-ESRGAN-ncnn-vulkan](https://github.com/xinntao/Real-ESRGAN-ncnn-vulkan#computer-usages) for more details. +1. Note that it does not support all the functions (such as `outscale`) as the python script `inference_realesrgan.py`. + +```console +Usage: realesrgan-ncnn-vulkan.exe -i infile -o outfile [options]... + + -h show this help + -i input-path input image path (jpg/png/webp) or directory + -o output-path output image path (jpg/png/webp) or directory + -s scale upscale ratio (can be 2, 3, 4. default=4) + -t tile-size tile size (>=32/0=auto, default=0) can be 0,0,0 for multi-gpu + -m model-path folder path to the pre-trained models. default=models + -n model-name model name (default=realesr-animevideov3, can be realesr-animevideov3 | realesrgan-x4plus | realesrgan-x4plus-anime | realesrnet-x4plus) + -g gpu-id gpu device to use (default=auto) can be 0,1,2 for multi-gpu + -j load:proc:save thread count for load/proc/save (default=1:2:2) can be 1:2,2,2:2 for multi-gpu + -x enable tta mode" + -f format output image format (jpg/png/webp, default=ext/png) + -v verbose output +``` + +Note 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. + +### Python script + +#### Usage of python script + +1. 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. + +```console +Usage: python inference_realesrgan.py -n RealESRGAN_x4plus -i infile -o outfile [options]... + +A common command: python inference_realesrgan.py -n RealESRGAN_x4plus -i infile --outscale 3.5 --face_enhance + + -h show this help + -i --input Input image or folder. Default: inputs + -o --output Output folder. Default: results + -n --model_name Model name. Default: RealESRGAN_x4plus + -s, --outscale The final upsampling scale of the image. Default: 4 + --suffix Suffix of the restored image. Default: out + -t, --tile Tile size, 0 for no tile during testing. Default: 0 + --face_enhance Whether to use GFPGAN to enhance face. Default: False + --fp32 Use fp32 precision during inference. Default: fp16 (half precision). + --ext Image extension. Options: auto | jpg | png, auto means using the same extension as inputs. Default: auto +``` + +#### Inference general images + +Download pre-trained models: [RealESRGAN_x4plus.pth](https://github.com/xinntao/Real-ESRGAN/releases/download/v0.1.0/RealESRGAN_x4plus.pth) + +```bash +wget https://github.com/xinntao/Real-ESRGAN/releases/download/v0.1.0/RealESRGAN_x4plus.pth -P weights +``` + +Inference! + +```bash +python inference_realesrgan.py -n RealESRGAN_x4plus -i inputs --face_enhance +``` + +Results are in the `results` folder + +#### Inference anime images + +

+ +

+ +Pre-trained models: [RealESRGAN_x4plus_anime_6B](https://github.com/xinntao/Real-ESRGAN/releases/download/v0.2.2.4/RealESRGAN_x4plus_anime_6B.pth)
+ More details and comparisons with [waifu2x](https://github.com/nihui/waifu2x-ncnn-vulkan) are in [**anime_model.md**](docs/anime_model.md) + +```bash +# download model +wget https://github.com/xinntao/Real-ESRGAN/releases/download/v0.2.2.4/RealESRGAN_x4plus_anime_6B.pth -P weights +# inference +python inference_realesrgan.py -n RealESRGAN_x4plus_anime_6B -i inputs +``` + +Results are in the `results` folder + +--- + +## BibTeX + + @InProceedings{wang2021realesrgan, + author = {Xintao Wang and Liangbin Xie and Chao Dong and Ying Shan}, + title = {Real-ESRGAN: Training Real-World Blind Super-Resolution with Pure Synthetic Data}, + booktitle = {International Conference on Computer Vision Workshops (ICCVW)}, + date = {2021} + } + +## 📧 Contact + +If you have any question, please email `xintao.wang@outlook.com` or `xintaowang@tencent.com`. + + +## 🧩 Projects that use Real-ESRGAN + +If you develop/use Real-ESRGAN in your projects, welcome to let me know. + +- NCNN-Android: [RealSR-NCNN-Android](https://github.com/tumuyan/RealSR-NCNN-Android) by [tumuyan](https://github.com/tumuyan) +- VapourSynth: [vs-realesrgan](https://github.com/HolyWu/vs-realesrgan) by [HolyWu](https://github.com/HolyWu) +- NCNN: [Real-ESRGAN-ncnn-vulkan](https://github.com/xinntao/Real-ESRGAN-ncnn-vulkan) + +    **GUI** + +- [Waifu2x-Extension-GUI](https://github.com/AaronFeng753/Waifu2x-Extension-GUI) by [AaronFeng753](https://github.com/AaronFeng753) +- [Squirrel-RIFE](https://github.com/Justin62628/Squirrel-RIFE) by [Justin62628](https://github.com/Justin62628) +- [Real-GUI](https://github.com/scifx/Real-GUI) by [scifx](https://github.com/scifx) +- [Real-ESRGAN_GUI](https://github.com/net2cn/Real-ESRGAN_GUI) by [net2cn](https://github.com/net2cn) +- [Real-ESRGAN-EGUI](https://github.com/WGzeyu/Real-ESRGAN-EGUI) by [WGzeyu](https://github.com/WGzeyu) +- [anime_upscaler](https://github.com/shangar21/anime_upscaler) by [shangar21](https://github.com/shangar21) +- [Upscayl](https://github.com/upscayl/upscayl) by [Nayam Amarshe](https://github.com/NayamAmarshe) and [TGS963](https://github.com/TGS963) + +## 🤗 Acknowledgement + +Thanks for all the contributors. + +- [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). +- [Asiimoviet](https://github.com/Asiimoviet): Translate the README.md to Chinese (中文). +- [2ji3150](https://github.com/2ji3150): Thanks for the [detailed and valuable feedbacks/suggestions](https://github.com/xinntao/Real-ESRGAN/issues/131). +- [Jared-02](https://github.com/Jared-02): Translate the Training.md to Chinese (中文). diff --git a/RealESRGANv030/README_CN.md b/RealESRGANv030/README_CN.md new file mode 100644 index 0000000000000000000000000000000000000000..fda1217bec600c5dcea72624c13533be6b71453e --- /dev/null +++ b/RealESRGANv030/README_CN.md @@ -0,0 +1,276 @@ +

+ +

+ +##
English | 简体中文
+ +[![download](https://img.shields.io/github/downloads/xinntao/Real-ESRGAN/total.svg)](https://github.com/xinntao/Real-ESRGAN/releases) +[![PyPI](https://img.shields.io/pypi/v/realesrgan)](https://pypi.org/project/realesrgan/) +[![Open issue](https://img.shields.io/github/issues/xinntao/Real-ESRGAN)](https://github.com/xinntao/Real-ESRGAN/issues) +[![Closed issue](https://img.shields.io/github/issues-closed/xinntao/Real-ESRGAN)](https://github.com/xinntao/Real-ESRGAN/issues) +[![LICENSE](https://img.shields.io/github/license/xinntao/Real-ESRGAN.svg)](https://github.com/xinntao/Real-ESRGAN/blob/master/LICENSE) +[![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) +[![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) + +:fire: 更新动漫视频的小模型 **RealESRGAN AnimeVideo-v3**. 更多信息在 [[动漫视频模型介绍](docs/anime_video_model.md)] 和 [[比较](docs/anime_comparisons_CN.md)] 中. + +1. 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) +2. **支持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)。 + +Real-ESRGAN 的目标是开发出**实用的图像/视频修复算法**。
+我们在 ESRGAN 的基础上使用纯合成的数据来进行训练,以使其能被应用于实际的图片修复的场景(顾名思义:Real-ESRGAN)。 + +:art: Real-ESRGAN 需要,也很欢迎你的贡献,如新功能、模型、bug修复、建议、维护等等。详情可以查看[CONTRIBUTING.md](docs/CONTRIBUTING.md),所有的贡献者都会被列在[此处](README_CN.md#hugs-感谢)。 + +:milky_way: 感谢大家提供了很好的反馈。这些反馈会逐步更新在 [这个文档](docs/feedback.md)。 + +:question: 常见的问题可以在[FAQ.md](docs/FAQ.md)中找到答案。(好吧,现在还是空白的=-=||) + +--- + +如果 Real-ESRGAN 对你有帮助,可以给本项目一个 Star :star: ,或者推荐给你的朋友们,谢谢!:blush:
+其他推荐的项目:
+:arrow_forward: [GFPGAN](https://github.com/TencentARC/GFPGAN): 实用的人脸复原算法
+:arrow_forward: [BasicSR](https://github.com/xinntao/BasicSR): 开源的图像和视频工具箱
+:arrow_forward: [facexlib](https://github.com/xinntao/facexlib): 提供与人脸相关的工具箱
+:arrow_forward: [HandyView](https://github.com/xinntao/HandyView): 基于PyQt5的图片查看器,方便查看以及比较
+ +--- + + +
+🚩更新 + +- ✅ 更新动漫视频的小模型 **RealESRGAN AnimeVideo-v3**. 更多信息在 [anime video models](docs/anime_video_model.md) 和 [comparisons](docs/anime_comparisons.md)中. +- ✅ 添加了针对动漫视频的小模型, 更多信息在 [anime video models](docs/anime_video_model.md) 中. +- ✅ 添加了ncnn 实现:[Real-ESRGAN-ncnn-vulkan](https://github.com/xinntao/Real-ESRGAN-ncnn-vulkan). +- ✅ 添加了 [*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) +- ✅支持用户在自己的数据上进行微调 (finetune):[详情](docs/Training.md#Finetune-Real-ESRGAN-on-your-own-dataset) +- ✅ 支持使用[GFPGAN](https://github.com/TencentARC/GFPGAN)**增强人脸** +- ✅ 通过[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) +- ✅ 支持任意比例的缩放:`--outscale`(实际上使用`LANCZOS4`来更进一步调整输出图像的尺寸)。添加了*RealESRGAN_x2plus.pth*模型 +- ✅ [推断脚本](inference_realesrgan.py)支持: 1) 分块处理**tile**; 2) 带**alpha通道**的图像; 3) **灰色**图像; 4) **16-bit**图像. +- ✅ 训练代码已经发布,具体做法可查看:[Training.md](docs/Training.md)。 + +
+ + +
+🧩使用Real-ESRGAN的项目 + +    👋 如果你开发/使用/集成了Real-ESRGAN, 欢迎联系我添加 + +- NCNN-Android: [RealSR-NCNN-Android](https://github.com/tumuyan/RealSR-NCNN-Android) by [tumuyan](https://github.com/tumuyan) +- VapourSynth: [vs-realesrgan](https://github.com/HolyWu/vs-realesrgan) by [HolyWu](https://github.com/HolyWu) +- NCNN: [Real-ESRGAN-ncnn-vulkan](https://github.com/xinntao/Real-ESRGAN-ncnn-vulkan) + +    **易用的图形界面** + +- [Waifu2x-Extension-GUI](https://github.com/AaronFeng753/Waifu2x-Extension-GUI) by [AaronFeng753](https://github.com/AaronFeng753) +- [Squirrel-RIFE](https://github.com/Justin62628/Squirrel-RIFE) by [Justin62628](https://github.com/Justin62628) +- [Real-GUI](https://github.com/scifx/Real-GUI) by [scifx](https://github.com/scifx) +- [Real-ESRGAN_GUI](https://github.com/net2cn/Real-ESRGAN_GUI) by [net2cn](https://github.com/net2cn) +- [Real-ESRGAN-EGUI](https://github.com/WGzeyu/Real-ESRGAN-EGUI) by [WGzeyu](https://github.com/WGzeyu) +- [anime_upscaler](https://github.com/shangar21/anime_upscaler) by [shangar21](https://github.com/shangar21) +- [RealESRGAN-GUI](https://github.com/Baiyuetribe/paper2gui/blob/main/Video%20Super%20Resolution/RealESRGAN-GUI.md) by [Baiyuetribe](https://github.com/Baiyuetribe) + +
+ +
+👀Demo视频(B站) + +- [大闹天宫片段](https://www.bilibili.com/video/BV1ja41117zb) + +
+ +### :book: Real-ESRGAN: Training Real-World Blind Super-Resolution with Pure Synthetic Data + +> [[论文](https://arxiv.org/abs/2107.10833)]   [项目主页]   [[YouTube 视频](https://www.youtube.com/watch?v=fxHWoDSSvSc)]   [[B站视频](https://www.bilibili.com/video/BV1H34y1m7sS/)]   [[Poster](https://xinntao.github.io/projects/RealESRGAN_src/RealESRGAN_poster.pdf)]   [[PPT](https://docs.google.com/presentation/d/1QtW6Iy8rm8rGLsJ0Ldti6kP-7Qyzy6XL/edit?usp=sharing&ouid=109799856763657548160&rtpof=true&sd=true)]
+> [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)
+> Tencent ARC Lab; Shenzhen Institutes of Advanced Technology, Chinese Academy of Sciences + +

+ +

+ +--- + +我们提供了一套训练好的模型(*RealESRGAN_x4plus.pth*),可以进行4倍的超分辨率。
+**现在的 Real-ESRGAN 还是有几率失败的,因为现实生活的降质过程比较复杂。**
+而且,本项目对**人脸以及文字之类**的效果还不是太好,但是我们会持续进行优化的。
+ +Real-ESRGAN 将会被长期支持,我会在空闲的时间中持续维护更新。 + +这些是未来计划的几个新功能: + +- [ ] 优化人脸 +- [ ] 优化文字 +- [x] 优化动画图像 +- [ ] 支持更多的超分辨率比例 +- [ ] 可调节的复原 + +如果你有好主意或需求,欢迎在 issue 或 discussion 中提出。
+如果你有一些 Real-ESRGAN 中有问题的照片,你也可以在 issue 或者 discussion 中发出来。我会留意(但是不一定能解决:stuck_out_tongue:)。如果有必要的话,我还会专门开一页来记录那些有待解决的图像。 + +--- + +### 便携版(绿色版)可执行文件 + +你可以下载**支持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)。 + +绿色版指的是这些exe你可以直接运行(放U盘里拷走都没问题),因为里面已经有所需的文件和模型了。它不需要 CUDA 或者 PyTorch运行环境。
+ +你可以通过下面这个命令来运行(Windows版本的例子,更多信息请查看对应版本的README.md): + +```bash +./realesrgan-ncnn-vulkan.exe -i 输入图像.jpg -o 输出图像.png -n 模型名字 +``` + +我们提供了五种模型: + +1. realesrgan-x4plus(默认) +2. reaesrnet-x4plus +3. realesrgan-x4plus-anime(针对动漫插画图像优化,有更小的体积) +4. realesr-animevideov3 (针对动漫视频) + +你可以通过`-n`参数来使用其他模型,例如`./realesrgan-ncnn-vulkan.exe -i 二次元图片.jpg -o 二刺螈图片.png -n realesrgan-x4plus-anime` + +### 可执行文件的用法 + +1. 更多细节可以参考 [Real-ESRGAN-ncnn-vulkan](https://github.com/xinntao/Real-ESRGAN-ncnn-vulkan#computer-usages). +2. 注意:可执行文件并没有支持 python 脚本 `inference_realesrgan.py` 中所有的功能,比如 `outscale` 选项) . + +```console +Usage: realesrgan-ncnn-vulkan.exe -i infile -o outfile [options]... + + -h show this help + -i input-path input image path (jpg/png/webp) or directory + -o output-path output image path (jpg/png/webp) or directory + -s scale upscale ratio (can be 2, 3, 4. default=4) + -t tile-size tile size (>=32/0=auto, default=0) can be 0,0,0 for multi-gpu + -m model-path folder path to the pre-trained models. default=models + -n model-name model name (default=realesr-animevideov3, can be realesr-animevideov3 | realesrgan-x4plus | realesrgan-x4plus-anime | realesrnet-x4plus) + -g gpu-id gpu device to use (default=auto) can be 0,1,2 for multi-gpu + -j load:proc:save thread count for load/proc/save (default=1:2:2) can be 1:2,2,2:2 for multi-gpu + -x enable tta mode" + -f format output image format (jpg/png/webp, default=ext/png) + -v verbose output +``` + +由于这些exe文件会把图像分成几个板块,然后来分别进行处理,再合成导出,输出的图像可能会有一点割裂感(而且可能跟PyTorch的输出不太一样) + +--- + +## :wrench: 依赖以及安装 + +- Python >= 3.7 (推荐使用[Anaconda](https://www.anaconda.com/download/#linux)或[Miniconda](https://docs.conda.io/en/latest/miniconda.html)) +- [PyTorch >= 1.7](https://pytorch.org/) + +#### 安装 + +1. 把项目克隆到本地 + + ```bash + git clone https://github.com/xinntao/Real-ESRGAN.git + cd Real-ESRGAN + ``` + +2. 安装各种依赖 + + ```bash + # 安装 basicsr - https://github.com/xinntao/BasicSR + # 我们使用BasicSR来训练以及推断 + pip install basicsr + # facexlib和gfpgan是用来增强人脸的 + pip install facexlib + pip install gfpgan + pip install -r requirements.txt + python setup.py develop + ``` + +## :zap: 快速上手 + +### 普通图片 + +下载我们训练好的模型: [RealESRGAN_x4plus.pth](https://github.com/xinntao/Real-ESRGAN/releases/download/v0.1.0/RealESRGAN_x4plus.pth) + +```bash +wget https://github.com/xinntao/Real-ESRGAN/releases/download/v0.1.0/RealESRGAN_x4plus.pth -P weights +``` + +推断! + +```bash +python inference_realesrgan.py -n RealESRGAN_x4plus -i inputs --face_enhance +``` + +结果在`results`文件夹 + +### 动画图片 + +

+ +

+ +训练好的模型: [RealESRGAN_x4plus_anime_6B](https://github.com/xinntao/Real-ESRGAN/releases/download/v0.2.2.4/RealESRGAN_x4plus_anime_6B.pth)
+有关[waifu2x](https://github.com/nihui/waifu2x-ncnn-vulkan)的更多信息和对比在[**anime_model.md**](docs/anime_model.md)中。 + +```bash +# 下载模型 +wget https://github.com/xinntao/Real-ESRGAN/releases/download/v0.2.2.4/RealESRGAN_x4plus_anime_6B.pth -P weights +# 推断 +python inference_realesrgan.py -n RealESRGAN_x4plus_anime_6B -i inputs +``` + +结果在`results`文件夹 + +### Python 脚本的用法 + +1. 虽然你使用了 X4 模型,但是你可以 **输出任意尺寸比例的图片**,只要实用了 `outscale` 参数. 程序会进一步对模型的输出图像进行缩放。 + +```console +Usage: python inference_realesrgan.py -n RealESRGAN_x4plus -i infile -o outfile [options]... + +A common command: python inference_realesrgan.py -n RealESRGAN_x4plus -i infile --outscale 3.5 --face_enhance + + -h show this help + -i --input Input image or folder. Default: inputs + -o --output Output folder. Default: results + -n --model_name Model name. Default: RealESRGAN_x4plus + -s, --outscale The final upsampling scale of the image. Default: 4 + --suffix Suffix of the restored image. Default: out + -t, --tile Tile size, 0 for no tile during testing. Default: 0 + --face_enhance Whether to use GFPGAN to enhance face. Default: False + --fp32 Whether to use half precision during inference. Default: False + --ext Image extension. Options: auto | jpg | png, auto means using the same extension as inputs. Default: auto +``` + +## :european_castle: 模型库 + +请参见 [docs/model_zoo.md](docs/model_zoo.md) + +## :computer: 训练,在你的数据上微调(Fine-tune) + +这里有一份详细的指南:[Training.md](docs/Training.md). + +## BibTeX 引用 + + @Article{wang2021realesrgan, + title={Real-ESRGAN: Training Real-World Blind Super-Resolution with Pure Synthetic Data}, + author={Xintao Wang and Liangbin Xie and Chao Dong and Ying Shan}, + journal={arXiv:2107.10833}, + year={2021} + } + +## :e-mail: 联系我们 + +如果你有任何问题,请通过 `xintao.wang@outlook.com` 或 `xintaowang@tencent.com` 联系我们。 + +## :hugs: 感谢 + +感谢所有的贡献者大大们~ + +- [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)。 +- [Asiimoviet](https://github.com/Asiimoviet): 把 README.md 文档 翻译成了中文。 +- [2ji3150](https://github.com/2ji3150): 感谢详尽并且富有价值的[反馈、建议](https://github.com/xinntao/Real-ESRGAN/issues/131). +- [Jared-02](https://github.com/Jared-02): 把 Training.md 文档 翻译成了中文。 diff --git a/RealESRGANv030/VERSION b/RealESRGANv030/VERSION new file mode 100644 index 0000000000000000000000000000000000000000..0d91a54c7d439e84e3dd17d3594f1b2b6737f430 --- /dev/null +++ b/RealESRGANv030/VERSION @@ -0,0 +1 @@ +0.3.0 diff --git a/RealESRGANv030/__init__.py b/RealESRGANv030/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..e69de29bb2d1d6434b8b29ae775ad8c2e48c5391 diff --git a/RealESRGANv030/assets/realesrgan_logo.png b/RealESRGANv030/assets/realesrgan_logo.png new file mode 100644 index 0000000000000000000000000000000000000000..88cd1ad6170794c2becb95006edffa0655d9372a Binary files /dev/null and b/RealESRGANv030/assets/realesrgan_logo.png differ diff --git a/RealESRGANv030/assets/realesrgan_logo_ai.png b/RealESRGANv030/assets/realesrgan_logo_ai.png new file mode 100644 index 0000000000000000000000000000000000000000..b0f595cf2535de7e69393384d8d056300f1cdddc Binary files /dev/null and b/RealESRGANv030/assets/realesrgan_logo_ai.png differ diff --git a/RealESRGANv030/assets/realesrgan_logo_av.png b/RealESRGANv030/assets/realesrgan_logo_av.png new file mode 100644 index 0000000000000000000000000000000000000000..501ac8e81292d9369122a69ec2dd56a3ae8beca6 Binary files /dev/null and b/RealESRGANv030/assets/realesrgan_logo_av.png differ diff --git a/RealESRGANv030/assets/realesrgan_logo_gi.png b/RealESRGANv030/assets/realesrgan_logo_gi.png new file mode 100644 index 0000000000000000000000000000000000000000..cdb0a1a74e0b54a1c684141324c6635acf2f60f8 Binary files /dev/null and b/RealESRGANv030/assets/realesrgan_logo_gi.png differ diff --git a/RealESRGANv030/assets/realesrgan_logo_gv.png b/RealESRGANv030/assets/realesrgan_logo_gv.png new file mode 100644 index 0000000000000000000000000000000000000000..21dfba05f3855f1d9740e6d2cbe2a8ac736f4508 Binary files /dev/null and b/RealESRGANv030/assets/realesrgan_logo_gv.png differ diff --git a/RealESRGANv030/assets/teaser-text.png b/RealESRGANv030/assets/teaser-text.png new file mode 100644 index 0000000000000000000000000000000000000000..af9b424e390bf454838d962f049db9bb5ef1064d Binary files /dev/null and b/RealESRGANv030/assets/teaser-text.png differ diff --git a/RealESRGANv030/assets/teaser.jpg b/RealESRGANv030/assets/teaser.jpg new file mode 100644 index 0000000000000000000000000000000000000000..dc9b7ccdf78e3c816b0b6ca567433b53253b2e1e Binary files /dev/null and b/RealESRGANv030/assets/teaser.jpg differ diff --git a/RealESRGANv030/cog.yaml b/RealESRGANv030/cog.yaml new file mode 100644 index 0000000000000000000000000000000000000000..daa6983934b6e186ecd0cf1d4e038acdb9910cbc --- /dev/null +++ b/RealESRGANv030/cog.yaml @@ -0,0 +1,22 @@ +# This file is used for constructing replicate env +image: "r8.im/tencentarc/realesrgan" + +build: + gpu: true + python_version: "3.8" + system_packages: + - "libgl1-mesa-glx" + - "libglib2.0-0" + python_packages: + - "torch==1.7.1" + - "torchvision==0.8.2" + - "numpy==1.21.1" + - "lmdb==1.2.1" + - "opencv-python==4.5.3.56" + - "PyYAML==5.4.1" + - "tqdm==4.62.2" + - "yapf==0.31.0" + - "basicsr==1.4.2" + - "facexlib==0.2.5" + +predict: "cog_predict.py:Predictor" diff --git a/RealESRGANv030/cog_predict.py b/RealESRGANv030/cog_predict.py new file mode 100644 index 0000000000000000000000000000000000000000..f314611be45d716664670fd39f90a1cfc18606e1 --- /dev/null +++ b/RealESRGANv030/cog_predict.py @@ -0,0 +1,219 @@ +# flake8: noqa +# This file is used for deploying replicate models +# running: cog predict -i img=@inputs/00017_gray.png -i version='General - v3' -i scale=2 -i face_enhance=True -i tile=0 +# push: cog push r8.im/xinntao/realesrgan + +import os + +os.system("pip install gfpgan") +os.system("python setup.py develop") + +import cv2 +import shutil +import tempfile +import torch +from basicsr.archs.rrdbnet_arch import RRDBNet +from basicsr.archs.srvgg_arch import SRVGGNetCompact + +from realesrgan.utils import RealESRGANer + +try: + from cog import BasePredictor, Input, Path + from gfpgan import GFPGANer +except Exception: + print("please install cog and realesrgan package") + + +class Predictor(BasePredictor): + def setup(self): + os.makedirs("output", exist_ok=True) + # download weights + if not os.path.exists("weights/realesr-general-x4v3.pth"): + os.system( + "wget https://github.com/xinntao/Real-ESRGAN/releases/download/v0.2.5.0/realesr-general-x4v3.pth -P ./weights" + ) + if not os.path.exists("weights/GFPGANv1.4.pth"): + os.system( + "wget https://github.com/TencentARC/GFPGAN/releases/download/v1.3.0/GFPGANv1.4.pth -P ./weights" + ) + if not os.path.exists("weights/RealESRGAN_x4plus.pth"): + os.system( + "wget https://github.com/xinntao/Real-ESRGAN/releases/download/v0.1.0/RealESRGAN_x4plus.pth -P ./weights" + ) + if not os.path.exists("weights/RealESRGAN_x4plus_anime_6B.pth"): + os.system( + "wget https://github.com/xinntao/Real-ESRGAN/releases/download/v0.2.2.4/RealESRGAN_x4plus_anime_6B.pth -P ./weights" + ) + if not os.path.exists("weights/realesr-animevideov3.pth"): + os.system( + "wget https://github.com/xinntao/Real-ESRGAN/releases/download/v0.2.5.0/realesr-animevideov3.pth -P ./weights" + ) + + def choose_model(self, scale, version, tile=0): + half = True if torch.cuda.is_available() else False + if version == "General - RealESRGANplus": + model = RRDBNet( + num_in_ch=3, + num_out_ch=3, + num_feat=64, + num_block=23, + num_grow_ch=32, + scale=4, + ) + model_path = "weights/RealESRGAN_x4plus.pth" + self.upsampler = RealESRGANer( + scale=4, + model_path=model_path, + model=model, + tile=tile, + tile_pad=10, + pre_pad=0, + half=half, + ) + elif version == "General - v3": + model = SRVGGNetCompact( + num_in_ch=3, + num_out_ch=3, + num_feat=64, + num_conv=32, + upscale=4, + act_type="prelu", + ) + model_path = "weights/realesr-general-x4v3.pth" + self.upsampler = RealESRGANer( + scale=4, + model_path=model_path, + model=model, + tile=tile, + tile_pad=10, + pre_pad=0, + half=half, + ) + elif version == "Anime - anime6B": + model = RRDBNet( + num_in_ch=3, + num_out_ch=3, + num_feat=64, + num_block=6, + num_grow_ch=32, + scale=4, + ) + model_path = "weights/RealESRGAN_x4plus_anime_6B.pth" + self.upsampler = RealESRGANer( + scale=4, + model_path=model_path, + model=model, + tile=tile, + tile_pad=10, + pre_pad=0, + half=half, + ) + elif version == "AnimeVideo - v3": + model = SRVGGNetCompact( + num_in_ch=3, + num_out_ch=3, + num_feat=64, + num_conv=16, + upscale=4, + act_type="prelu", + ) + model_path = "weights/realesr-animevideov3.pth" + self.upsampler = RealESRGANer( + scale=4, + model_path=model_path, + model=model, + tile=tile, + tile_pad=10, + pre_pad=0, + half=half, + ) + + self.face_enhancer = GFPGANer( + model_path="weights/GFPGANv1.4.pth", + upscale=scale, + arch="clean", + channel_multiplier=2, + bg_upsampler=self.upsampler, + ) + + def predict( + self, + img: Path = Input(description="Input"), + version: str = Input( + description="RealESRGAN version. Please see [Readme] below for more descriptions", + choices=[ + "General - RealESRGANplus", + "General - v3", + "Anime - anime6B", + "AnimeVideo - v3", + ], + default="General - v3", + ), + scale: float = Input(description="Rescaling factor", default=2), + face_enhance: bool = Input( + description="Enhance faces with GFPGAN. Note that it does not work for anime images/vidoes", + default=False, + ), + tile: int = Input( + description="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", + default=0, + ), + ) -> Path: + if tile <= 100 or tile is None: + tile = 0 + print( + f"img: {img}. version: {version}. scale: {scale}. face_enhance: {face_enhance}. tile: {tile}." + ) + try: + extension = os.path.splitext(os.path.basename(str(img)))[1] + img = cv2.imread(str(img), cv2.IMREAD_UNCHANGED) + if len(img.shape) == 3 and img.shape[2] == 4: + img_mode = "RGBA" + elif len(img.shape) == 2: + img_mode = None + img = cv2.cvtColor(img, cv2.COLOR_GRAY2BGR) + else: + img_mode = None + + h, w = img.shape[0:2] + if h < 300: + img = cv2.resize(img, (w * 2, h * 2), interpolation=cv2.INTER_LANCZOS4) + + self.choose_model(scale, version, tile) + + try: + if face_enhance: + _, _, output = self.face_enhancer.enhance( + img, has_aligned=False, only_center_face=False, paste_back=True + ) + else: + output, _ = self.upsampler.enhance(img, outscale=scale) + except RuntimeError as error: + print("Error", error) + print( + 'If you encounter CUDA out of memory, try to set "tile" to a smaller size, e.g., 400.' + ) + + if img_mode == "RGBA": # RGBA images should be saved in png format + extension = "png" + # save_path = f'output/out.{extension}' + # cv2.imwrite(save_path, output) + out_path = Path(tempfile.mkdtemp()) / f"out.{extension}" + cv2.imwrite(str(out_path), output) + except Exception as error: + print("global exception: ", error) + finally: + clean_folder("output") + return out_path + + +def clean_folder(folder): + for filename in os.listdir(folder): + file_path = os.path.join(folder, filename) + try: + if os.path.isfile(file_path) or os.path.islink(file_path): + os.unlink(file_path) + elif os.path.isdir(file_path): + shutil.rmtree(file_path) + except Exception as e: + print(f"Failed to delete {file_path}. Reason: {e}") diff --git a/RealESRGANv030/docs/CONTRIBUTING.md b/RealESRGANv030/docs/CONTRIBUTING.md new file mode 100644 index 0000000000000000000000000000000000000000..75990c2ce7545b72fb6ebad8295ca4895f437205 --- /dev/null +++ b/RealESRGANv030/docs/CONTRIBUTING.md @@ -0,0 +1,44 @@ +# Contributing to Real-ESRGAN + +: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). + +We 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: + +- New features +- New models (your fine-tuned models) +- Bug fixes +- Typo fixes +- Suggestions +- Maintenance +- Documents +- *etc* + +## Workflow + +1. Fork and pull the latest Real-ESRGAN repository +1. Checkout a new branch (do not use master branch for PRs) +1. Commit your changes +1. Create a PR + +**Note**: + +1. Please check the code style and linting + 1. The style configuration is specified in [setup.cfg](setup.cfg) + 1. If you use VSCode, the settings are configured in [.vscode/settings.json](.vscode/settings.json) +1. Strongly recommend using `pre-commit hook`. It will check your code style and linting before your commit. + 1. In the root path of project folder, run `pre-commit install` + 1. The pre-commit configuration is listed in [.pre-commit-config.yaml](.pre-commit-config.yaml) +1. Better to [open a discussion](https://github.com/xinntao/Real-ESRGAN/discussions) before large changes. + 1. Welcome to discuss :sunglasses:. I will try my best to join the discussion. + +## TODO List + +:zero: The most straightforward way of improving model performance is to fine-tune on some specific datasets. + +Here are some TODOs: + +- [ ] optimize for human faces +- [ ] optimize for texts +- [ ] support controllable restoration strength + +: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: diff --git a/RealESRGANv030/docs/FAQ.md b/RealESRGANv030/docs/FAQ.md new file mode 100644 index 0000000000000000000000000000000000000000..843f4dd847487066a1c7c105c7292e2de0bd5f1a --- /dev/null +++ b/RealESRGANv030/docs/FAQ.md @@ -0,0 +1,10 @@ +# FAQ + +1. **Q: How to select models?**
+A: Please refer to [docs/model_zoo.md](docs/model_zoo.md) + +1. **Q: Can `face_enhance` be used for anime images/animation videos?**
+A: 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. + +1. **Q: Error "slow_conv2d_cpu" not implemented for 'Half'**
+A: 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`. diff --git a/RealESRGANv030/docs/Training.md b/RealESRGANv030/docs/Training.md new file mode 100644 index 0000000000000000000000000000000000000000..77da5ea5763f7a6ab291ebc28afb13be37df3f50 --- /dev/null +++ b/RealESRGANv030/docs/Training.md @@ -0,0 +1,271 @@ +# :computer: How to Train/Finetune Real-ESRGAN + +- [Train Real-ESRGAN](#train-real-esrgan) + - [Overview](#overview) + - [Dataset Preparation](#dataset-preparation) + - [Train Real-ESRNet](#Train-Real-ESRNet) + - [Train Real-ESRGAN](#Train-Real-ESRGAN) +- [Finetune Real-ESRGAN on your own dataset](#Finetune-Real-ESRGAN-on-your-own-dataset) + - [Generate degraded images on the fly](#Generate-degraded-images-on-the-fly) + - [Use paired training data](#use-your-own-paired-data) + +[English](Training.md) **|** [简体中文](Training_CN.md) + +## Train Real-ESRGAN + +### Overview + +The 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, + +1. We first train Real-ESRNet with L1 loss from the pre-trained model ESRGAN. +1. 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. + +### Dataset Preparation + +We use DF2K (DIV2K and Flickr2K) + OST datasets for our training. Only HR images are required.
+You can download from : + +1. DIV2K: http://data.vision.ee.ethz.ch/cvl/DIV2K/DIV2K_train_HR.zip +2. Flickr2K: https://cv.snu.ac.kr/research/EDSR/Flickr2K.tar +3. OST: https://openmmlab.oss-cn-hangzhou.aliyuncs.com/datasets/OST_dataset.zip + +Here are steps for data preparation. + +#### Step 1: [Optional] Generate multi-scale images + +For the DF2K dataset, we use a multi-scale strategy, *i.e.*, we downsample HR images to obtain several Ground-Truth images with different scales.
+You can use the [scripts/generate_multiscale_DF2K.py](scripts/generate_multiscale_DF2K.py) script to generate multi-scale images.
+Note that this step can be omitted if you just want to have a fast try. + +```bash +python scripts/generate_multiscale_DF2K.py --input datasets/DF2K/DF2K_HR --output datasets/DF2K/DF2K_multiscale +``` + +#### Step 2: [Optional] Crop to sub-images + +We then crop DF2K images into sub-images for faster IO and processing.
+This step is optional if your IO is enough or your disk space is limited. + +You can use the [scripts/extract_subimages.py](scripts/extract_subimages.py) script. Here is the example: + +```bash + python scripts/extract_subimages.py --input datasets/DF2K/DF2K_multiscale --output datasets/DF2K/DF2K_multiscale_sub --crop_size 400 --step 200 +``` + +#### Step 3: Prepare a txt for meta information + +You 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): + +```txt +DF2K_HR_sub/000001_s001.png +DF2K_HR_sub/000001_s002.png +DF2K_HR_sub/000001_s003.png +... +``` + +You can use the [scripts/generate_meta_info.py](scripts/generate_meta_info.py) script to generate the txt file.
+You can merge several folders into one meta_info txt. Here is the example: + +```bash + 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 +``` + +### Train Real-ESRNet + +1. 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`. + ```bash + wget https://github.com/xinntao/Real-ESRGAN/releases/download/v0.1.1/ESRGAN_SRx4_DF2KOST_official-ff704c30.pth -P experiments/pretrained_models + ``` +1. Modify the content in the option file `options/train_realesrnet_x4plus.yml` accordingly: + ```yml + train: + name: DF2K+OST + type: RealESRGANDataset + dataroot_gt: datasets/DF2K # modify to the root path of your folder + meta_info: realesrgan/meta_info/meta_info_DF2Kmultiscale+OST_sub.txt # modify to your own generate meta info txt + io_backend: + type: disk + ``` +1. If you want to perform validation during training, uncomment those lines and modify accordingly: + ```yml + # Uncomment these for validation + # val: + # name: validation + # type: PairedImageDataset + # dataroot_gt: path_to_gt + # dataroot_lq: path_to_lq + # io_backend: + # type: disk + + ... + + # Uncomment these for validation + # validation settings + # val: + # val_freq: !!float 5e3 + # save_img: True + + # metrics: + # psnr: # metric name, can be arbitrary + # type: calculate_psnr + # crop_border: 4 + # test_y_channel: false + ``` +1. Before the formal training, you may run in the `--debug` mode to see whether everything is OK. We use four GPUs for training: + ```bash + CUDA_VISIBLE_DEVICES=0,1,2,3 \ + python -m torch.distributed.launch --nproc_per_node=4 --master_port=4321 realesrgan/train.py -opt options/train_realesrnet_x4plus.yml --launcher pytorch --debug + ``` + + Train with **a single GPU** in the *debug* mode: + ```bash + python realesrgan/train.py -opt options/train_realesrnet_x4plus.yml --debug + ``` +1. The formal training. We use four GPUs for training. We use the `--auto_resume` argument to automatically resume the training if necessary. + ```bash + CUDA_VISIBLE_DEVICES=0,1,2,3 \ + 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 + ``` + + Train with **a single GPU**: + ```bash + python realesrgan/train.py -opt options/train_realesrnet_x4plus.yml --auto_resume + ``` + +### Train Real-ESRGAN + +1. 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`. +1. Modify the option file `train_realesrgan_x4plus.yml` accordingly. Most modifications are similar to those listed above. +1. Before the formal training, you may run in the `--debug` mode to see whether everything is OK. We use four GPUs for training: + ```bash + CUDA_VISIBLE_DEVICES=0,1,2,3 \ + python -m torch.distributed.launch --nproc_per_node=4 --master_port=4321 realesrgan/train.py -opt options/train_realesrgan_x4plus.yml --launcher pytorch --debug + ``` + + Train with **a single GPU** in the *debug* mode: + ```bash + python realesrgan/train.py -opt options/train_realesrgan_x4plus.yml --debug + ``` +1. The formal training. We use four GPUs for training. We use the `--auto_resume` argument to automatically resume the training if necessary. + ```bash + CUDA_VISIBLE_DEVICES=0,1,2,3 \ + 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 + ``` + + Train with **a single GPU**: + ```bash + python realesrgan/train.py -opt options/train_realesrgan_x4plus.yml --auto_resume + ``` + +## Finetune Real-ESRGAN on your own dataset + +You can finetune Real-ESRGAN on your own dataset. Typically, the fine-tuning process can be divided into two cases: + +1. [Generate degraded images on the fly](#Generate-degraded-images-on-the-fly) +1. [Use your own **paired** data](#Use-paired-training-data) + +### Generate degraded images on the fly + +Only high-resolution images are required. The low-quality images are generated with the degradation process described in Real-ESRGAN during training. + +**1. Prepare dataset** + +See [this section](#dataset-preparation) for more details. + +**2. Download pre-trained models** + +Download pre-trained models into `experiments/pretrained_models`. + +- *RealESRGAN_x4plus.pth*: + ```bash + wget https://github.com/xinntao/Real-ESRGAN/releases/download/v0.1.0/RealESRGAN_x4plus.pth -P experiments/pretrained_models + ``` + +- *RealESRGAN_x4plus_netD.pth*: + ```bash + wget https://github.com/xinntao/Real-ESRGAN/releases/download/v0.2.2.3/RealESRGAN_x4plus_netD.pth -P experiments/pretrained_models + ``` + +**3. Finetune** + +Modify [options/finetune_realesrgan_x4plus.yml](options/finetune_realesrgan_x4plus.yml) accordingly, especially the `datasets` part: + +```yml +train: + name: DF2K+OST + type: RealESRGANDataset + dataroot_gt: datasets/DF2K # modify to the root path of your folder + meta_info: realesrgan/meta_info/meta_info_DF2Kmultiscale+OST_sub.txt # modify to your own generate meta info txt + io_backend: + type: disk +``` + +We use four GPUs for training. We use the `--auto_resume` argument to automatically resume the training if necessary. + +```bash +CUDA_VISIBLE_DEVICES=0,1,2,3 \ +python -m torch.distributed.launch --nproc_per_node=4 --master_port=4321 realesrgan/train.py -opt options/finetune_realesrgan_x4plus.yml --launcher pytorch --auto_resume +``` + +Finetune with **a single GPU**: +```bash +python realesrgan/train.py -opt options/finetune_realesrgan_x4plus.yml --auto_resume +``` + +### Use your own paired data + +You can also finetune RealESRGAN with your own paired data. It is more similar to fine-tuning ESRGAN. + +**1. Prepare dataset** + +Assume that you already have two folders: + +- **gt folder** (Ground-truth, high-resolution images): *datasets/DF2K/DIV2K_train_HR_sub* +- **lq folder** (Low quality, low-resolution images): *datasets/DF2K/DIV2K_train_LR_bicubic_X4_sub* + +Then, you can prepare the meta_info txt file using the script [scripts/generate_meta_info_pairdata.py](scripts/generate_meta_info_pairdata.py): + +```bash +python 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 +``` + +**2. Download pre-trained models** + +Download pre-trained models into `experiments/pretrained_models`. + +- *RealESRGAN_x4plus.pth* + ```bash + wget https://github.com/xinntao/Real-ESRGAN/releases/download/v0.1.0/RealESRGAN_x4plus.pth -P experiments/pretrained_models + ``` + +- *RealESRGAN_x4plus_netD.pth* + ```bash + wget https://github.com/xinntao/Real-ESRGAN/releases/download/v0.2.2.3/RealESRGAN_x4plus_netD.pth -P experiments/pretrained_models + ``` + +**3. Finetune** + +Modify [options/finetune_realesrgan_x4plus_pairdata.yml](options/finetune_realesrgan_x4plus_pairdata.yml) accordingly, especially the `datasets` part: + +```yml +train: + name: DIV2K + type: RealESRGANPairedDataset + dataroot_gt: datasets/DF2K # modify to the root path of your folder + dataroot_lq: datasets/DF2K # modify to the root path of your folder + meta_info: datasets/DF2K/meta_info/meta_info_DIV2K_sub_pair.txt # modify to your own generate meta info txt + io_backend: + type: disk +``` + +We use four GPUs for training. We use the `--auto_resume` argument to automatically resume the training if necessary. + +```bash +CUDA_VISIBLE_DEVICES=0,1,2,3 \ +python -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 +``` + +Finetune with **a single GPU**: +```bash +python realesrgan/train.py -opt options/finetune_realesrgan_x4plus_pairdata.yml --auto_resume +``` diff --git a/RealESRGANv030/docs/Training_CN.md b/RealESRGANv030/docs/Training_CN.md new file mode 100644 index 0000000000000000000000000000000000000000..dabc3c5d97e134a2d551157c2dd03a629ec661bc --- /dev/null +++ b/RealESRGANv030/docs/Training_CN.md @@ -0,0 +1,271 @@ +# :computer: 如何训练/微调 Real-ESRGAN + +- [训练 Real-ESRGAN](#训练-real-esrgan) + - [概述](#概述) + - [准备数据集](#准备数据集) + - [训练 Real-ESRNet 模型](#训练-real-esrnet-模型) + - [训练 Real-ESRGAN 模型](#训练-real-esrgan-模型) +- [用自己的数据集微调 Real-ESRGAN](#用自己的数据集微调-real-esrgan) + - [动态生成降级图像](#动态生成降级图像) + - [使用已配对的数据](#使用已配对的数据) + +[English](Training.md) **|** [简体中文](Training_CN.md) + +## 训练 Real-ESRGAN + +### 概述 + +训练分为两个步骤。除了 loss 函数外,这两个步骤拥有相同数据合成以及训练的一条龙流程。具体点说: + +1. 首先使用 L1 loss 训练 Real-ESRNet 模型,其中 L1 loss 来自预先训练的 ESRGAN 模型。 + +2. 然后我们将 Real-ESRNet 模型作为生成器初始化,结合L1 loss、感知 loss、GAN loss 三者的参数对 Real-ESRGAN 进行训练。 + +### 准备数据集 + +我们使用 DF2K ( DIV2K 和 Flickr2K ) + OST 数据集进行训练。只需要HR图像!
+下面是网站链接: +1. DIV2K: http://data.vision.ee.ethz.ch/cvl/DIV2K/DIV2K_train_HR.zip +2. Flickr2K: https://cv.snu.ac.kr/research/EDSR/Flickr2K.tar +3. OST: https://openmmlab.oss-cn-hangzhou.aliyuncs.com/datasets/OST_dataset.zip + +以下是数据的准备步骤。 + +#### 第1步:【可选】生成多尺寸图片 + +针对 DF2K 数据集,我们使用多尺寸缩放策略,*换言之*,我们对 HR 图像进行下采样,就能获得多尺寸的标准参考(Ground-Truth)图像。
+您可以使用这个 [scripts/generate_multiscale_DF2K.py](scripts/generate_multiscale_DF2K.py) 脚本快速生成多尺寸的图像。
+注意:如果您只想简单试试,那么可以跳过此步骤。 + +```bash +python scripts/generate_multiscale_DF2K.py --input datasets/DF2K/DF2K_HR --output datasets/DF2K/DF2K_multiscale +``` + +#### 第2步:【可选】裁切为子图像 + +我们可以将 DF2K 图像裁切为子图像,以加快 IO 和处理速度。
+如果你的 IO 够好或储存空间有限,那么此步骤是可选的。
+ +您可以使用脚本 [scripts/extract_subimages.py](scripts/extract_subimages.py)。这是使用示例: + +```bash + python scripts/extract_subimages.py --input datasets/DF2K/DF2K_multiscale --output datasets/DF2K/DF2K_multiscale_sub --crop_size 400 --step 200 +``` + +#### 第3步:准备元信息 txt + +您需要准备一个包含图像路径的 txt 文件。下面是 `meta_info_DF2Kmultiscale+OST_sub.txt` 中的部分展示(由于各个用户可能有截然不同的子图像划分,这个文件不适合你的需求,你得准备自己的 txt 文件): + +```txt +DF2K_HR_sub/000001_s001.png +DF2K_HR_sub/000001_s002.png +DF2K_HR_sub/000001_s003.png +... +``` + +你可以使用该脚本 [scripts/generate_meta_info.py](scripts/generate_meta_info.py) 生成包含图像路径的 txt 文件。
+你还可以合并多个文件夹的图像路径到一个元信息(meta_info)txt。这是使用示例: + +```bash + 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 +``` + +### 训练 Real-ESRNet 模型 + +1. 下载预先训练的模型 [ESRGAN](https://github.com/xinntao/Real-ESRGAN/releases/download/v0.1.1/ESRGAN_SRx4_DF2KOST_official-ff704c30.pth),放到 `experiments/pretrained_models`目录下。 + ```bash + wget https://github.com/xinntao/Real-ESRGAN/releases/download/v0.1.1/ESRGAN_SRx4_DF2KOST_official-ff704c30.pth -P experiments/pretrained_models + ``` +2. 相应地修改选项文件 `options/train_realesrnet_x4plus.yml` 中的内容: + ```yml + train: + name: DF2K+OST + type: RealESRGANDataset + dataroot_gt: datasets/DF2K # 修改为你的数据集文件夹根目录 + meta_info: realesrgan/meta_info/meta_info_DF2Kmultiscale+OST_sub.txt # 修改为你自己生成的元信息txt + io_backend: + type: disk + ``` +3. 如果你想在训练过程中执行验证,就取消注释这些内容并进行相应的修改: + ```yml + # 取消注释这些以进行验证 + # val: + # name: validation + # type: PairedImageDataset + # dataroot_gt: path_to_gt + # dataroot_lq: path_to_lq + # io_backend: + # type: disk + + ... + + # 取消注释这些以进行验证 + # 验证设置 + # val: + # val_freq: !!float 5e3 + # save_img: True + + # metrics: + # psnr: # 指标名称,可以是任意的 + # type: calculate_psnr + # crop_border: 4 + # test_y_channel: false + ``` +4. 正式训练之前,你可以用 `--debug` 模式检查是否正常运行。我们用了4个GPU进行训练: + ```bash + CUDA_VISIBLE_DEVICES=0,1,2,3 \ + python -m torch.distributed.launch --nproc_per_node=4 --master_port=4321 realesrgan/train.py -opt options/train_realesrnet_x4plus.yml --launcher pytorch --debug + ``` + + 用 **1个GPU** 训练的 debug 模式示例: + ```bash + python realesrgan/train.py -opt options/train_realesrnet_x4plus.yml --debug + ``` +5. 正式训练开始。我们用了4个GPU进行训练。还可以使用参数 `--auto_resume` 在必要时自动恢复训练。 + ```bash + CUDA_VISIBLE_DEVICES=0,1,2,3 \ + 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 + ``` + + 用 **1个GPU** 训练: + ```bash + python realesrgan/train.py -opt options/train_realesrnet_x4plus.yml --auto_resume + ``` + +### 训练 Real-ESRGAN 模型 + +1. 训练 Real-ESRNet 模型后,您得到了这个 `experiments/train_RealESRNetx4plus_1000k_B12G4_fromESRGAN/model/net_g_1000000.pth` 文件。如果需要指定预训练路径到其他文件,请修改选项文件 `train_realesrgan_x4plus.yml` 中 `pretrain_network_g` 的值。 +1. 修改选项文件 `train_realesrgan_x4plus.yml` 的内容。大多数修改与上节提到的类似。 +1. 正式训练之前,你可以以 `--debug` 模式检查是否正常运行。我们使用了4个GPU进行训练: + ```bash + CUDA_VISIBLE_DEVICES=0,1,2,3 \ + python -m torch.distributed.launch --nproc_per_node=4 --master_port=4321 realesrgan/train.py -opt options/train_realesrgan_x4plus.yml --launcher pytorch --debug + ``` + + 用 **1个GPU** 训练的 debug 模式示例: + ```bash + python realesrgan/train.py -opt options/train_realesrgan_x4plus.yml --debug + ``` +1. 正式训练开始。我们使用4个GPU进行训练。还可以使用参数 `--auto_resume` 在必要时自动恢复训练。 + ```bash + CUDA_VISIBLE_DEVICES=0,1,2,3 \ + 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 + ``` + + 用 **1个GPU** 训练: + ```bash + python realesrgan/train.py -opt options/train_realesrgan_x4plus.yml --auto_resume + ``` + +## 用自己的数据集微调 Real-ESRGAN + +你可以用自己的数据集微调 Real-ESRGAN。一般地,微调(Fine-Tune)程序可以分为两种类型: + +1. [动态生成降级图像](#动态生成降级图像) +2. [使用**已配对**的数据](#使用已配对的数据) + +### 动态生成降级图像 + +只需要高分辨率图像。在训练过程中,使用 Real-ESRGAN 描述的降级模型生成低质量图像。 + +**1. 准备数据集** + +完整信息请参见[本节](#准备数据集)。 + +**2. 下载预训练模型** + +下载预先训练的模型到 `experiments/pretrained_models` 目录下。 + +- *RealESRGAN_x4plus.pth*: + ```bash + wget https://github.com/xinntao/Real-ESRGAN/releases/download/v0.1.0/RealESRGAN_x4plus.pth -P experiments/pretrained_models + ``` + +- *RealESRGAN_x4plus_netD.pth*: + ```bash + wget https://github.com/xinntao/Real-ESRGAN/releases/download/v0.2.2.3/RealESRGAN_x4plus_netD.pth -P experiments/pretrained_models + ``` + +**3. 微调** + +修改选项文件 [options/finetune_realesrgan_x4plus.yml](options/finetune_realesrgan_x4plus.yml) ,特别是 `datasets` 部分: + +```yml +train: + name: DF2K+OST + type: RealESRGANDataset + dataroot_gt: datasets/DF2K # 修改为你的数据集文件夹根目录 + meta_info: realesrgan/meta_info/meta_info_DF2Kmultiscale+OST_sub.txt # 修改为你自己生成的元信息txt + io_backend: + type: disk +``` + +我们使用4个GPU进行训练。还可以使用参数 `--auto_resume` 在必要时自动恢复训练。 + +```bash +CUDA_VISIBLE_DEVICES=0,1,2,3 \ +python -m torch.distributed.launch --nproc_per_node=4 --master_port=4321 realesrgan/train.py -opt options/finetune_realesrgan_x4plus.yml --launcher pytorch --auto_resume +``` + +用 **1个GPU** 训练: +```bash +python realesrgan/train.py -opt options/finetune_realesrgan_x4plus.yml --auto_resume +``` + +### 使用已配对的数据 + +你还可以用自己已经配对的数据微调 RealESRGAN。这个过程更类似于微调 ESRGAN。 + +**1. 准备数据集** + +假设你已经有两个文件夹(folder): + +- **gt folder**(标准参考,高分辨率图像):*datasets/DF2K/DIV2K_train_HR_sub* +- **lq folder**(低质量,低分辨率图像):*datasets/DF2K/DIV2K_train_LR_bicubic_X4_sub* + +然后,您可以使用脚本 [scripts/generate_meta_info_pairdata.py](scripts/generate_meta_info_pairdata.py) 生成元信息(meta_info)txt 文件。 + +```bash +python 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 +``` + +**2. 下载预训练模型** + +下载预先训练的模型到 `experiments/pretrained_models` 目录下。 + +- *RealESRGAN_x4plus.pth*: + ```bash + wget https://github.com/xinntao/Real-ESRGAN/releases/download/v0.1.0/RealESRGAN_x4plus.pth -P experiments/pretrained_models + ``` + +- *RealESRGAN_x4plus_netD.pth*: + ```bash + wget https://github.com/xinntao/Real-ESRGAN/releases/download/v0.2.2.3/RealESRGAN_x4plus_netD.pth -P experiments/pretrained_models + ``` + +**3. 微调** + +修改选项文件 [options/finetune_realesrgan_x4plus_pairdata.yml](options/finetune_realesrgan_x4plus_pairdata.yml) ,特别是 `datasets` 部分: + +```yml +train: + name: DIV2K + type: RealESRGANPairedDataset + dataroot_gt: datasets/DF2K # 修改为你的 gt folder 文件夹根目录 + dataroot_lq: datasets/DF2K # 修改为你的 lq folder 文件夹根目录 + meta_info: datasets/DF2K/meta_info/meta_info_DIV2K_sub_pair.txt # 修改为你自己生成的元信息txt + io_backend: + type: disk +``` + +我们使用4个GPU进行训练。还可以使用参数 `--auto_resume` 在必要时自动恢复训练。 + +```bash +CUDA_VISIBLE_DEVICES=0,1,2,3 \ +python -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 +``` + +用 **1个GPU** 训练: +```bash +python realesrgan/train.py -opt options/finetune_realesrgan_x4plus_pairdata.yml --auto_resume +``` diff --git a/RealESRGANv030/docs/anime_comparisons.md b/RealESRGANv030/docs/anime_comparisons.md new file mode 100644 index 0000000000000000000000000000000000000000..09603bdc989bbf68b1f9f466acac5d8e442b8a01 --- /dev/null +++ b/RealESRGANv030/docs/anime_comparisons.md @@ -0,0 +1,66 @@ +# Comparisons among different anime models + +[English](anime_comparisons.md) **|** [简体中文](anime_comparisons_CN.md) + +## Update News + +- 2022/04/24: Release **AnimeVideo-v3**. We have made the following improvements: + - **better naturalness** + - **Fewer artifacts** + - **more faithful to the original colors** + - **better texture restoration** + - **better background restoration** + +## Comparisons + +We have compared our RealESRGAN-AnimeVideo-v3 with the following methods. +Our RealESRGAN-AnimeVideo-v3 can achieve better results with faster inference speed. + +- [waifu2x](https://github.com/nihui/waifu2x-ncnn-vulkan) with the hyperparameters: `tile=0`, `noiselevel=2` +- [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`. +- our RealESRGAN-AnimeVideo-v3 + +## Results + +You may need to **zoom in** for comparing details, or **click the image** to see in the full size. Please note that the images +in 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) . + +**More natural results, better background restoration** +| Input | waifu2x | Real-CUGAN | RealESRGAN
AnimeVideo-v3 | +| :---: | :---: | :---: | :---: | +|![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) | +|![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) | +|![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) | + +**Fewer artifacts, better detailed textures** +| Input | waifu2x | Real-CUGAN | RealESRGAN
AnimeVideo-v3 | +| :---: | :---: | :---: | :---: | +|![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) | +|![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) | +|![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) | +|![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) | + +**Other better results** +| Input | waifu2x | Real-CUGAN | RealESRGAN
AnimeVideo-v3 | +| :---: | :---: | :---: | :---: | +|![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) | +|![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) | +|![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) | +|![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) | +|![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) | + +## Inference Speed + +### PyTorch + +Note that we only report the **model** time, and ignore the IO time. + +| GPU | Input Resolution | waifu2x | Real-CUGAN | RealESRGAN-AnimeVideo-v3 +| :---: | :---: | :---: | :---: | :---: | +| V100 | 1921 x 1080 | - | 3.4 fps | **10.0** fps | +| V100 | 1280 x 720 | - | 7.2 fps | **22.6** fps | +| V100 | 640 x 480 | - | 24.4 fps | **65.9** fps | + +### ncnn + +- [ ] TODO diff --git a/RealESRGANv030/docs/anime_comparisons_CN.md b/RealESRGANv030/docs/anime_comparisons_CN.md new file mode 100644 index 0000000000000000000000000000000000000000..43ba58344ed9554d5b30e2815d1b7d4ab8bc503f --- /dev/null +++ b/RealESRGANv030/docs/anime_comparisons_CN.md @@ -0,0 +1,68 @@ +# 动漫视频模型比较 + +[English](anime_comparisons.md) **|** [简体中文](anime_comparisons_CN.md) + +## 更新 + +- 2022/04/24: 发布 **AnimeVideo-v3**. 主要做了以下更新: + - **更自然** + - **更少瑕疵** + - **颜色保持得更好** + - **更好的纹理恢复** + - **虚化背景处理** + +## 比较 + +我们将 RealESRGAN-AnimeVideo-v3 与以下方法进行了比较。我们的 RealESRGAN-AnimeVideo-v3 可以以更快的推理速度获得更好的结果。 + +- [waifu2x](https://github.com/nihui/waifu2x-ncnn-vulkan). 超参数: `tile=0`, `noiselevel=2` +- [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`. +- 我们的 RealESRGAN-AnimeVideo-v3 + +## 结果 + +您可能需要**放大**以比较详细信息, 或者**单击图像**以查看完整尺寸。 请注意下面表格的图片是从原图里裁剪patch并且resize后的结果,您可以从 +[Google Drive](https://drive.google.com/drive/folders/1bc_Hje1Nqop9NDkUvci2VACSjL7HZMRp?usp=sharing) 里下载原始的输入和输出。 + +**更自然的结果,更好的虚化背景恢复** + +| 输入 | waifu2x | Real-CUGAN | RealESRGAN
AnimeVideo-v3 | +| :---: | :---: | :---: | :---: | +|![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) | +|![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) | +|![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) | + +**更少瑕疵,更好的细节纹理** + +| 输入 | waifu2x | Real-CUGAN | RealESRGAN
AnimeVideo-v3 | +| :---: | :---: | :---: | :---: | +|![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) | +|![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) | +|![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) | +|![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) | + +**其他更好的结果** + +| 输入 | waifu2x | Real-CUGAN | RealESRGAN
AnimeVideo-v3 | +| :---: | :---: | :---: | :---: | +|![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) | +|![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) | +|![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) | +|![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) | +|![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) | + +## 推理速度比较 + +### PyTorch + +请注意,我们只报告了**模型推理**的时间, 而忽略了读写硬盘的时间. + +| GPU | 输入尺寸 | waifu2x | Real-CUGAN | RealESRGAN-AnimeVideo-v3 +| :---: | :---: | :---: | :---: | :---: | +| V100 | 1921 x 1080 | - | 3.4 fps | **10.0** fps | +| V100 | 1280 x 720 | - | 7.2 fps | **22.6** fps | +| V100 | 640 x 480 | - | 24.4 fps | **65.9** fps | + +### ncnn + +- [ ] TODO diff --git a/RealESRGANv030/docs/anime_model.md b/RealESRGANv030/docs/anime_model.md new file mode 100644 index 0000000000000000000000000000000000000000..213328d92d0dbaeb188f8ef0f47192e74efeaccc --- /dev/null +++ b/RealESRGANv030/docs/anime_model.md @@ -0,0 +1,68 @@ +# Anime Model + +: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. + +- [How to Use](#how-to-use) + - [PyTorch Inference](#pytorch-inference) + - [ncnn Executable File](#ncnn-executable-file) +- [Comparisons with waifu2x](#comparisons-with-waifu2x) +- [Comparisons with Sliding Bars](#comparisons-with-sliding-bars) + +

+ +

+ +The 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. + + + +## How to Use + +### PyTorch Inference + +Pre-trained models: [RealESRGAN_x4plus_anime_6B](https://github.com/xinntao/Real-ESRGAN/releases/download/v0.2.2.4/RealESRGAN_x4plus_anime_6B.pth) + +```bash +# download model +wget https://github.com/xinntao/Real-ESRGAN/releases/download/v0.2.2.4/RealESRGAN_x4plus_anime_6B.pth -P weights +# inference +python inference_realesrgan.py -n RealESRGAN_x4plus_anime_6B -i inputs +``` + +### ncnn Executable File + +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**. + +Taking the Windows as example, run: + +```bash +./realesrgan-ncnn-vulkan.exe -i input.jpg -o output.png -n realesrgan-x4plus-anime +``` + +## Comparisons with waifu2x + +We compare Real-ESRGAN-anime with [waifu2x](https://github.com/nihui/waifu2x-ncnn-vulkan). We use the `-n 2 -s 4` for waifu2x. + +

+ +

+

+ +

+

+ +

+

+ +

+

+ +

+ +## Comparisons with Sliding Bars + +The 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. + + + + diff --git a/RealESRGANv030/docs/anime_video_model.md b/RealESRGANv030/docs/anime_video_model.md new file mode 100644 index 0000000000000000000000000000000000000000..0ad5c85804c1f8636c3720a652b40bbd9df0fe2e --- /dev/null +++ b/RealESRGANv030/docs/anime_video_model.md @@ -0,0 +1,136 @@ +# Anime Video Models + +:white_check_mark: We add small models that are optimized for anime videos :-)
+More comparisons can be found in [anime_comparisons.md](anime_comparisons.md) + +- [How to Use](#how-to-use) +- [PyTorch Inference](#pytorch-inference) +- [ncnn Executable File](#ncnn-executable-file) + - [Step 1: Use ffmpeg to extract frames from video](#step-1-use-ffmpeg-to-extract-frames-from-video) + - [Step 2: Inference with Real-ESRGAN executable file](#step-2-inference-with-real-esrgan-executable-file) + - [Step 3: Merge the enhanced frames back into a video](#step-3-merge-the-enhanced-frames-back-into-a-video) +- [More Demos](#more-demos) + +| Models | Scale | Description | +| ---------------------------------------------------------------------------------------------------------------------------------- | :---- | :----------------------------- | +| [realesr-animevideov3](https://github.com/xinntao/Real-ESRGAN/releases/download/v0.2.5.0/realesr-animevideov3.pth) | X4 1 | Anime video model with XS size | + +Note:
+1 This model can also be used for X1, X2, X3. + +--- + +The following are some demos (best view in the full screen mode). + + + + + + + +## How to Use + +### PyTorch Inference + +```bash +# download model +wget https://github.com/xinntao/Real-ESRGAN/releases/download/v0.2.5.0/realesr-animevideov3.pth -P weights +# single gpu and single process inference +CUDA_VISIBLE_DEVICES=0 python inference_realesrgan_video.py -i inputs/video/onepiece_demo.mp4 -n realesr-animevideov3 -s 2 --suffix outx2 +# single gpu and multi process inference (you can use multi-processing to improve GPU utilization) +CUDA_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 +# multi gpu and multi process inference +CUDA_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 +``` + +```console +Usage: +--num_process_per_gpu The total number of process is num_gpu * num_process_per_gpu. The bottleneck of + the program lies on the IO, so the GPUs are usually not fully utilized. To alleviate + this issue, you can use multi-processing by setting this parameter. As long as it + does not exceed the CUDA memory +--extract_frame_first If you encounter ffmpeg error when using multi-processing, you can turn this option on. +``` + +### NCNN Executable File + +#### Step 1: Use ffmpeg to extract frames from video + +```bash +ffmpeg -i onepiece_demo.mp4 -qscale:v 1 -qmin 1 -qmax 1 -vsync 0 tmp_frames/frame%08d.png +``` + +- Remember to create the folder `tmp_frames` ahead + +#### Step 2: Inference with Real-ESRGAN executable file + +1. 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** + +1. Taking the Windows as example, run: + + ```bash + ./realesrgan-ncnn-vulkan.exe -i tmp_frames -o out_frames -n realesr-animevideov3 -s 2 -f jpg + ``` + + - Remember to create the folder `out_frames` ahead + +#### Step 3: Merge the enhanced frames back into a video + +1. First obtain fps from input videos by + + ```bash + ffmpeg -i onepiece_demo.mp4 + ``` + + ```console + Usage: + -i input video path + ``` + + You will get the output similar to the following screenshot. + +

+ +

+ +2. Merge frames + + ```bash + ffmpeg -r 23.98 -i out_frames/frame%08d.jpg -c:v libx264 -r 23.98 -pix_fmt yuv420p output.mp4 + ``` + + ```console + Usage: + -i input video path + -c:v video encoder (usually we use libx264) + -r fps, remember to modify it to meet your needs + -pix_fmt pixel format in video + ``` + + If you also want to copy audio from the input videos, run: + + ```bash + 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 + ``` + + ```console + Usage: + -i input video path, here we use two input streams + -c:v video encoder (usually we use libx264) + -r fps, remember to modify it to meet your needs + -pix_fmt pixel format in video + ``` + +## More Demos + +- Input video for One Piece: + + + +- Out video for One Piece + + + +**More comparisons** + + diff --git a/RealESRGANv030/docs/feedback.md b/RealESRGANv030/docs/feedback.md new file mode 100644 index 0000000000000000000000000000000000000000..c621ed05e9bc122a2ae6309eac61583ab9f35e7a --- /dev/null +++ b/RealESRGANv030/docs/feedback.md @@ -0,0 +1,11 @@ +# Feedback 反馈 + +## 动漫插画模型 + +1. 视频处理不了: 目前的模型,不是针对视频的,所以视频效果很很不好。我们在探究针对视频的模型了 +1. 景深虚化有问题: 现在的模型把一些景深 和 特意的虚化 都复原了,感觉不好。这个后面我们会考虑把这个信息结合进入。一个简单的做法是识别景深和虚化,然后作为条件告诉神经网络,哪些地方复原强一些,哪些地方复原要弱一些 +1. 不可以调节: 像 Waifu2X 可以调节。可以根据自己的喜好,做调整,但是 Real-ESRGAN-anime 并不可以。导致有些恢复效果过了 +1. 把原来的风格改变了: 不同的动漫插画都有自己的风格,现在的 Real-ESRGAN-anime 倾向于恢复成一种风格(这是受到训练数据集影响的)。风格是动漫很重要的一个要素,所以要尽可能保持 +1. 模型太大: 目前的模型处理太慢,能够更快。这个我们有相关的工作在探究,希望能够尽快有结果,并应用到 Real-ESRGAN 这一系列的模型上 + +Thanks for the [detailed and valuable feedbacks/suggestions](https://github.com/xinntao/Real-ESRGAN/issues/131) by [2ji3150](https://github.com/2ji3150). diff --git a/RealESRGANv030/docs/model_zoo.md b/RealESRGANv030/docs/model_zoo.md new file mode 100644 index 0000000000000000000000000000000000000000..132cc514bac6b447addac8485e0622a834d34474 --- /dev/null +++ b/RealESRGANv030/docs/model_zoo.md @@ -0,0 +1,49 @@ +# :european_castle: Model Zoo + +- [For General Images](#for-general-images) +- [For Anime Images](#for-anime-images) +- [For Anime Videos](#for-anime-videos) + +--- + +## For General Images + +| Models | Scale | Description | +| ------------------------------------------------------------------------------------------------------------------------------- | :---- | :------------------------------------------- | +| [RealESRGAN_x4plus](https://github.com/xinntao/Real-ESRGAN/releases/download/v0.1.0/RealESRGAN_x4plus.pth) | X4 | X4 model for general images | +| [RealESRGAN_x2plus](https://github.com/xinntao/Real-ESRGAN/releases/download/v0.2.1/RealESRGAN_x2plus.pth) | X2 | X2 model for general images | +| [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) | +| [official ESRGAN_x4](https://github.com/xinntao/Real-ESRGAN/releases/download/v0.1.1/ESRGAN_SRx4_DF2KOST_official-ff704c30.pth) | X4 | official ESRGAN model | +| [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 | + +The following models are **discriminators**, which are usually used for fine-tuning. + +| Models | Corresponding model | +| ---------------------------------------------------------------------------------------------------------------------- | :------------------ | +| [RealESRGAN_x4plus_netD](https://github.com/xinntao/Real-ESRGAN/releases/download/v0.2.2.3/RealESRGAN_x4plus_netD.pth) | RealESRGAN_x4plus | +| [RealESRGAN_x2plus_netD](https://github.com/xinntao/Real-ESRGAN/releases/download/v0.2.2.3/RealESRGAN_x2plus_netD.pth) | RealESRGAN_x2plus | + +## For Anime Images / Illustrations + +| Models | Scale | Description | +| ------------------------------------------------------------------------------------------------------------------------------ | :---- | :---------------------------------------------------------- | +| [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) | + +The following models are **discriminators**, which are usually used for fine-tuning. + +| Models | Corresponding model | +| ---------------------------------------------------------------------------------------------------------------------------------------- | :------------------------- | +| [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 | + +## For Animation Videos + +| Models | Scale | Description | +| ---------------------------------------------------------------------------------------------------------------------------------- | :---- | :----------------------------- | +| [realesr-animevideov3](https://github.com/xinntao/Real-ESRGAN/releases/download/v0.2.5.0/realesr-animevideov3.pth) | X41 | Anime video model with XS size | + +Note:
+1 This model can also be used for X1, X2, X3. + +The following models are **discriminators**, which are usually used for fine-tuning. + +TODO diff --git a/RealESRGANv030/docs/ncnn_conversion.md b/RealESRGANv030/docs/ncnn_conversion.md new file mode 100644 index 0000000000000000000000000000000000000000..e1785cd079ccbb6f0a5ddefe24f63bfe81ce9b21 --- /dev/null +++ b/RealESRGANv030/docs/ncnn_conversion.md @@ -0,0 +1,11 @@ +# Instructions on converting to NCNN models + +1. Convert to onnx model with `scripts/pytorch2onnx.py`. Remember to modify codes accordingly +1. Convert onnx model to ncnn model + 1. `cd ncnn-master\ncnn\build\tools\onnx` + 1. `onnx2ncnn.exe realesrgan-x4.onnx realesrgan-x4-raw.param realesrgan-x4-raw.bin` +1. Optimize ncnn model + 1. fp16 mode + 1. `cd ncnn-master\ncnn\build\tools` + 1. `ncnnoptimize.exe realesrgan-x4-raw.param realesrgan-x4-raw.bin realesrgan-x4.param realesrgan-x4.bin 1` +1. Modify the blob name in `realesrgan-x4.param`: `data` and `output` diff --git a/RealESRGANv030/inference_realesrgan.py b/RealESRGANv030/inference_realesrgan.py new file mode 100644 index 0000000000000000000000000000000000000000..057eda86bababbd4e2828c0943695e40a99737f4 --- /dev/null +++ b/RealESRGANv030/inference_realesrgan.py @@ -0,0 +1,271 @@ +import argparse +import cv2 +import glob +import os +from basicsr.archs.rrdbnet_arch import RRDBNet +from basicsr.utils.download_util import load_file_from_url + +from realesrgan import RealESRGANer +from realesrgan.archs.srvgg_arch import SRVGGNetCompact + + +def main(): + """Inference demo for Real-ESRGAN.""" + parser = argparse.ArgumentParser() + parser.add_argument( + "-i", "--input", type=str, default="inputs", help="Input image or folder" + ) + parser.add_argument( + "-n", + "--model_name", + type=str, + default="RealESRGAN_x4plus", + help=( + "Model names: RealESRGAN_x4plus | RealESRNet_x4plus | RealESRGAN_x4plus_anime_6B | RealESRGAN_x2plus | " + "realesr-animevideov3 | realesr-general-x4v3" + ), + ) + parser.add_argument( + "-o", "--output", type=str, default="results", help="Output folder" + ) + parser.add_argument( + "-dn", + "--denoise_strength", + type=float, + default=0.5, + help=( + "Denoise strength. 0 for weak denoise (keep noise), 1 for strong denoise ability. " + "Only used for the realesr-general-x4v3 model" + ), + ) + parser.add_argument( + "-s", + "--outscale", + type=float, + default=4, + help="The final upsampling scale of the image", + ) + parser.add_argument( + "--model_path", + type=str, + default=None, + help="[Option] Model path. Usually, you do not need to specify it", + ) + parser.add_argument( + "--suffix", type=str, default="out", help="Suffix of the restored image" + ) + parser.add_argument( + "-t", + "--tile", + type=int, + default=0, + help="Tile size, 0 for no tile during testing", + ) + parser.add_argument("--tile_pad", type=int, default=10, help="Tile padding") + parser.add_argument( + "--pre_pad", type=int, default=0, help="Pre padding size at each border" + ) + parser.add_argument( + "--face_enhance", action="store_true", help="Use GFPGAN to enhance face" + ) + parser.add_argument( + "--fp32", + action="store_true", + help="Use fp32 precision during inference. Default: fp16 (half precision).", + ) + parser.add_argument( + "--alpha_upsampler", + type=str, + default="realesrgan", + help="The upsampler for the alpha channels. Options: realesrgan | bicubic", + ) + parser.add_argument( + "--ext", + type=str, + default="auto", + help="Image extension. Options: auto | jpg | png, auto means using the same extension as inputs", + ) + parser.add_argument( + "-g", + "--gpu-id", + type=int, + default=None, + help="gpu device to use (default=None) can be 0,1,2 for multi-gpu", + ) + + args = parser.parse_args() + + # determine models according to model names + args.model_name = args.model_name.split(".")[0] + if args.model_name == "RealESRGAN_x4plus": # x4 RRDBNet model + model = RRDBNet( + num_in_ch=3, + num_out_ch=3, + num_feat=64, + num_block=23, + num_grow_ch=32, + scale=4, + ) + netscale = 4 + file_url = [ + "https://github.com/xinntao/Real-ESRGAN/releases/download/v0.1.0/RealESRGAN_x4plus.pth" + ] + elif args.model_name == "RealESRNet_x4plus": # x4 RRDBNet model + model = RRDBNet( + num_in_ch=3, + num_out_ch=3, + num_feat=64, + num_block=23, + num_grow_ch=32, + scale=4, + ) + netscale = 4 + file_url = [ + "https://github.com/xinntao/Real-ESRGAN/releases/download/v0.1.1/RealESRNet_x4plus.pth" + ] + elif ( + args.model_name == "RealESRGAN_x4plus_anime_6B" + ): # x4 RRDBNet model with 6 blocks + model = RRDBNet( + num_in_ch=3, num_out_ch=3, num_feat=64, num_block=6, num_grow_ch=32, scale=4 + ) + netscale = 4 + file_url = [ + "https://github.com/xinntao/Real-ESRGAN/releases/download/v0.2.2.4/RealESRGAN_x4plus_anime_6B.pth" + ] + elif args.model_name == "RealESRGAN_x2plus": # x2 RRDBNet model + model = RRDBNet( + num_in_ch=3, + num_out_ch=3, + num_feat=64, + num_block=23, + num_grow_ch=32, + scale=2, + ) + netscale = 2 + file_url = [ + "https://github.com/xinntao/Real-ESRGAN/releases/download/v0.2.1/RealESRGAN_x2plus.pth" + ] + elif args.model_name == "realesr-animevideov3": # x4 VGG-style model (XS size) + model = SRVGGNetCompact( + num_in_ch=3, + num_out_ch=3, + num_feat=64, + num_conv=16, + upscale=4, + act_type="prelu", + ) + netscale = 4 + file_url = [ + "https://github.com/xinntao/Real-ESRGAN/releases/download/v0.2.5.0/realesr-animevideov3.pth" + ] + elif args.model_name == "realesr-general-x4v3": # x4 VGG-style model (S size) + model = SRVGGNetCompact( + num_in_ch=3, + num_out_ch=3, + num_feat=64, + num_conv=32, + upscale=4, + act_type="prelu", + ) + netscale = 4 + file_url = [ + "https://github.com/xinntao/Real-ESRGAN/releases/download/v0.2.5.0/realesr-general-wdn-x4v3.pth", + "https://github.com/xinntao/Real-ESRGAN/releases/download/v0.2.5.0/realesr-general-x4v3.pth", + ] + + # determine model paths + if args.model_path is not None: + model_path = args.model_path + else: + model_path = os.path.join("weights", args.model_name + ".pth") + if not os.path.isfile(model_path): + ROOT_DIR = os.path.dirname(os.path.abspath(__file__)) + for url in file_url: + # model_path will be updated + model_path = load_file_from_url( + url=url, + model_dir=os.path.join(ROOT_DIR, "weights"), + progress=True, + file_name=None, + ) + + # use dni to control the denoise strength + dni_weight = None + if args.model_name == "realesr-general-x4v3" and args.denoise_strength != 1: + wdn_model_path = model_path.replace( + "realesr-general-x4v3", "realesr-general-wdn-x4v3" + ) + model_path = [model_path, wdn_model_path] + dni_weight = [args.denoise_strength, 1 - args.denoise_strength] + + # restorer + upsampler = RealESRGANer( + scale=netscale, + model_path=model_path, + dni_weight=dni_weight, + model=model, + tile=args.tile, + tile_pad=args.tile_pad, + pre_pad=args.pre_pad, + half=not args.fp32, + gpu_id=args.gpu_id, + ) + + if args.face_enhance: # Use GFPGAN for face enhancement + from gfpgan import GFPGANer + + face_enhancer = GFPGANer( + model_path="https://github.com/TencentARC/GFPGAN/releases/download/v1.3.0/GFPGANv1.3.pth", + upscale=args.outscale, + arch="clean", + channel_multiplier=2, + bg_upsampler=upsampler, + ) + os.makedirs(args.output, exist_ok=True) + + if os.path.isfile(args.input): + paths = [args.input] + else: + paths = sorted(glob.glob(os.path.join(args.input, "*"))) + + for idx, path in enumerate(paths): + imgname, extension = os.path.splitext(os.path.basename(path)) + print("Testing", idx, imgname) + + img = cv2.imread(path, cv2.IMREAD_UNCHANGED) + if len(img.shape) == 3 and img.shape[2] == 4: + img_mode = "RGBA" + else: + img_mode = None + + try: + if args.face_enhance: + _, _, output = face_enhancer.enhance( + img, has_aligned=False, only_center_face=False, paste_back=True + ) + else: + output, _ = upsampler.enhance(img, outscale=args.outscale) + except RuntimeError as error: + print("Error", error) + print( + "If you encounter CUDA out of memory, try to set --tile with a smaller number." + ) + else: + if args.ext == "auto": + extension = extension[1:] + else: + extension = args.ext + if img_mode == "RGBA": # RGBA images should be saved in png format + extension = "png" + if args.suffix == "": + save_path = os.path.join(args.output, f"{imgname}.{extension}") + else: + save_path = os.path.join( + args.output, f"{imgname}_{args.suffix}.{extension}" + ) + cv2.imwrite(save_path, output) + + +if __name__ == "__main__": + main() diff --git a/RealESRGANv030/inference_realesrgan_video.py b/RealESRGANv030/inference_realesrgan_video.py new file mode 100644 index 0000000000000000000000000000000000000000..170fb23971d135ebf0c854c652a0005d3f31abaa --- /dev/null +++ b/RealESRGANv030/inference_realesrgan_video.py @@ -0,0 +1,566 @@ +import argparse +import cv2 +import glob +import mimetypes +import numpy as np +import os +import shutil +import subprocess +import torch +from basicsr.archs.rrdbnet_arch import RRDBNet +from basicsr.utils.download_util import load_file_from_url +from os import path as osp +from tqdm import tqdm + +from realesrgan import RealESRGANer +from realesrgan.archs.srvgg_arch import SRVGGNetCompact + +try: + import ffmpeg +except ImportError: + import pip + + pip.main(["install", "--user", "ffmpeg-python"]) + import ffmpeg + + +def get_video_meta_info(video_path): + ret = {} + probe = ffmpeg.probe(video_path) + video_streams = [ + stream for stream in probe["streams"] if stream["codec_type"] == "video" + ] + has_audio = any(stream["codec_type"] == "audio" for stream in probe["streams"]) + ret["width"] = video_streams[0]["width"] + ret["height"] = video_streams[0]["height"] + ret["fps"] = eval(video_streams[0]["avg_frame_rate"]) + ret["audio"] = ffmpeg.input(video_path).audio if has_audio else None + ret["nb_frames"] = int(video_streams[0]["nb_frames"]) + return ret + + +def get_sub_video(args, num_process, process_idx): + if num_process == 1: + return args.input + meta = get_video_meta_info(args.input) + duration = int(meta["nb_frames"] / meta["fps"]) + part_time = duration // num_process + print(f"duration: {duration}, part_time: {part_time}") + os.makedirs( + osp.join(args.output, f"{args.video_name}_inp_tmp_videos"), exist_ok=True + ) + out_path = osp.join( + args.output, f"{args.video_name}_inp_tmp_videos", f"{process_idx:03d}.mp4" + ) + cmd = [ + args.ffmpeg_bin, + f"-i {args.input}", + "-ss", + f"{part_time * process_idx}", + f"-to {part_time * (process_idx + 1)}" + if process_idx != num_process - 1 + else "", + "-async 1", + out_path, + "-y", + ] + print(" ".join(cmd)) + subprocess.call(" ".join(cmd), shell=True) + return out_path + + +class Reader: + def __init__(self, args, total_workers=1, worker_idx=0): + self.args = args + input_type = mimetypes.guess_type(args.input)[0] + self.input_type = "folder" if input_type is None else input_type + self.paths = [] # for image&folder type + self.audio = None + self.input_fps = None + if self.input_type.startswith("video"): + video_path = get_sub_video(args, total_workers, worker_idx) + self.stream_reader = ( + ffmpeg.input(video_path) + .output("pipe:", format="rawvideo", pix_fmt="bgr24", loglevel="error") + .run_async(pipe_stdin=True, pipe_stdout=True, cmd=args.ffmpeg_bin) + ) + meta = get_video_meta_info(video_path) + self.width = meta["width"] + self.height = meta["height"] + self.input_fps = meta["fps"] + self.audio = meta["audio"] + self.nb_frames = meta["nb_frames"] + + else: + if self.input_type.startswith("image"): + self.paths = [args.input] + else: + paths = sorted(glob.glob(os.path.join(args.input, "*"))) + tot_frames = len(paths) + num_frame_per_worker = tot_frames // total_workers + ( + 1 if tot_frames % total_workers else 0 + ) + self.paths = paths[ + num_frame_per_worker + * worker_idx : num_frame_per_worker + * (worker_idx + 1) + ] + + self.nb_frames = len(self.paths) + assert self.nb_frames > 0, "empty folder" + from PIL import Image + + tmp_img = Image.open(self.paths[0]) + self.width, self.height = tmp_img.size + self.idx = 0 + + def get_resolution(self): + return self.height, self.width + + def get_fps(self): + if self.args.fps is not None: + return self.args.fps + elif self.input_fps is not None: + return self.input_fps + return 24 + + def get_audio(self): + return self.audio + + def __len__(self): + return self.nb_frames + + def get_frame_from_stream(self): + img_bytes = self.stream_reader.stdout.read( + self.width * self.height * 3 + ) # 3 bytes for one pixel + if not img_bytes: + return None + img = np.frombuffer(img_bytes, np.uint8).reshape([self.height, self.width, 3]) + return img + + def get_frame_from_list(self): + if self.idx >= self.nb_frames: + return None + img = cv2.imread(self.paths[self.idx]) + self.idx += 1 + return img + + def get_frame(self): + if self.input_type.startswith("video"): + return self.get_frame_from_stream() + else: + return self.get_frame_from_list() + + def close(self): + if self.input_type.startswith("video"): + self.stream_reader.stdin.close() + self.stream_reader.wait() + + +class Writer: + def __init__(self, args, audio, height, width, video_save_path, fps): + out_width, out_height = int(width * args.outscale), int(height * args.outscale) + if out_height > 2160: + print( + "You are generating video that is larger than 4K, which will be very slow due to IO speed.", + "We highly recommend to decrease the outscale(aka, -s).", + ) + + if audio is not None: + self.stream_writer = ( + ffmpeg.input( + "pipe:", + format="rawvideo", + pix_fmt="bgr24", + s=f"{out_width}x{out_height}", + framerate=fps, + ) + .output( + audio, + video_save_path, + pix_fmt="yuv420p", + vcodec="libx264", + loglevel="error", + acodec="copy", + ) + .overwrite_output() + .run_async(pipe_stdin=True, pipe_stdout=True, cmd=args.ffmpeg_bin) + ) + else: + self.stream_writer = ( + ffmpeg.input( + "pipe:", + format="rawvideo", + pix_fmt="bgr24", + s=f"{out_width}x{out_height}", + framerate=fps, + ) + .output( + video_save_path, + pix_fmt="yuv420p", + vcodec="libx264", + loglevel="error", + ) + .overwrite_output() + .run_async(pipe_stdin=True, pipe_stdout=True, cmd=args.ffmpeg_bin) + ) + + def write_frame(self, frame): + frame = frame.astype(np.uint8).tobytes() + self.stream_writer.stdin.write(frame) + + def close(self): + self.stream_writer.stdin.close() + self.stream_writer.wait() + + +def inference_video(args, video_save_path, device=None, total_workers=1, worker_idx=0): + # ---------------------- determine models according to model names ---------------------- # + args.model_name = args.model_name.split(".pth")[0] + if args.model_name == "RealESRGAN_x4plus": # x4 RRDBNet model + model = RRDBNet( + num_in_ch=3, + num_out_ch=3, + num_feat=64, + num_block=23, + num_grow_ch=32, + scale=4, + ) + netscale = 4 + file_url = [ + "https://github.com/xinntao/Real-ESRGAN/releases/download/v0.1.0/RealESRGAN_x4plus.pth" + ] + elif args.model_name == "RealESRNet_x4plus": # x4 RRDBNet model + model = RRDBNet( + num_in_ch=3, + num_out_ch=3, + num_feat=64, + num_block=23, + num_grow_ch=32, + scale=4, + ) + netscale = 4 + file_url = [ + "https://github.com/xinntao/Real-ESRGAN/releases/download/v0.1.1/RealESRNet_x4plus.pth" + ] + elif ( + args.model_name == "RealESRGAN_x4plus_anime_6B" + ): # x4 RRDBNet model with 6 blocks + model = RRDBNet( + num_in_ch=3, num_out_ch=3, num_feat=64, num_block=6, num_grow_ch=32, scale=4 + ) + netscale = 4 + file_url = [ + "https://github.com/xinntao/Real-ESRGAN/releases/download/v0.2.2.4/RealESRGAN_x4plus_anime_6B.pth" + ] + elif args.model_name == "RealESRGAN_x2plus": # x2 RRDBNet model + model = RRDBNet( + num_in_ch=3, + num_out_ch=3, + num_feat=64, + num_block=23, + num_grow_ch=32, + scale=2, + ) + netscale = 2 + file_url = [ + "https://github.com/xinntao/Real-ESRGAN/releases/download/v0.2.1/RealESRGAN_x2plus.pth" + ] + elif args.model_name == "realesr-animevideov3": # x4 VGG-style model (XS size) + model = SRVGGNetCompact( + num_in_ch=3, + num_out_ch=3, + num_feat=64, + num_conv=16, + upscale=4, + act_type="prelu", + ) + netscale = 4 + file_url = [ + "https://github.com/xinntao/Real-ESRGAN/releases/download/v0.2.5.0/realesr-animevideov3.pth" + ] + elif args.model_name == "realesr-general-x4v3": # x4 VGG-style model (S size) + model = SRVGGNetCompact( + num_in_ch=3, + num_out_ch=3, + num_feat=64, + num_conv=32, + upscale=4, + act_type="prelu", + ) + netscale = 4 + file_url = [ + "https://github.com/xinntao/Real-ESRGAN/releases/download/v0.2.5.0/realesr-general-wdn-x4v3.pth", + "https://github.com/xinntao/Real-ESRGAN/releases/download/v0.2.5.0/realesr-general-x4v3.pth", + ] + + # ---------------------- determine model paths ---------------------- # + model_path = os.path.join("weights", args.model_name + ".pth") + if not os.path.isfile(model_path): + ROOT_DIR = os.path.dirname(os.path.abspath(__file__)) + for url in file_url: + # model_path will be updated + model_path = load_file_from_url( + url=url, + model_dir=os.path.join(ROOT_DIR, "weights"), + progress=True, + file_name=None, + ) + + # use dni to control the denoise strength + dni_weight = None + if args.model_name == "realesr-general-x4v3" and args.denoise_strength != 1: + wdn_model_path = model_path.replace( + "realesr-general-x4v3", "realesr-general-wdn-x4v3" + ) + model_path = [model_path, wdn_model_path] + dni_weight = [args.denoise_strength, 1 - args.denoise_strength] + + # restorer + upsampler = RealESRGANer( + scale=netscale, + model_path=model_path, + dni_weight=dni_weight, + model=model, + tile=args.tile, + tile_pad=args.tile_pad, + pre_pad=args.pre_pad, + half=not args.fp32, + device=device, + ) + + if "anime" in args.model_name and args.face_enhance: + print( + "face_enhance is not supported in anime models, we turned this option off for you. " + "if you insist on turning it on, please manually comment the relevant lines of code." + ) + args.face_enhance = False + + if args.face_enhance: # Use GFPGAN for face enhancement + from gfpgan import GFPGANer + + face_enhancer = GFPGANer( + model_path="https://github.com/TencentARC/GFPGAN/releases/download/v1.3.0/GFPGANv1.3.pth", + upscale=args.outscale, + arch="clean", + channel_multiplier=2, + bg_upsampler=upsampler, + ) # TODO support custom device + else: + face_enhancer = None + + reader = Reader(args, total_workers, worker_idx) + audio = reader.get_audio() + height, width = reader.get_resolution() + fps = reader.get_fps() + writer = Writer(args, audio, height, width, video_save_path, fps) + + pbar = tqdm(total=len(reader), unit="frame", desc="inference") + while True: + img = reader.get_frame() + if img is None: + break + + try: + if args.face_enhance: + _, _, output = face_enhancer.enhance( + img, has_aligned=False, only_center_face=False, paste_back=True + ) + else: + output, _ = upsampler.enhance(img, outscale=args.outscale) + except RuntimeError as error: + print("Error", error) + print( + "If you encounter CUDA out of memory, try to set --tile with a smaller number." + ) + else: + writer.write_frame(output) + + torch.cuda.synchronize(device) + pbar.update(1) + + reader.close() + writer.close() + + +def run(args): + args.video_name = osp.splitext(os.path.basename(args.input))[0] + video_save_path = osp.join(args.output, f"{args.video_name}_{args.suffix}.mp4") + + if args.extract_frame_first: + tmp_frames_folder = osp.join(args.output, f"{args.video_name}_inp_tmp_frames") + os.makedirs(tmp_frames_folder, exist_ok=True) + os.system( + f"ffmpeg -i {args.input} -qscale:v 1 -qmin 1 -qmax 1 -vsync 0 {tmp_frames_folder}/frame%08d.png" + ) + args.input = tmp_frames_folder + + num_gpus = torch.cuda.device_count() + num_process = num_gpus * args.num_process_per_gpu + if num_process == 1: + inference_video(args, video_save_path) + return + + ctx = torch.multiprocessing.get_context("spawn") + pool = ctx.Pool(num_process) + os.makedirs( + osp.join(args.output, f"{args.video_name}_out_tmp_videos"), exist_ok=True + ) + pbar = tqdm(total=num_process, unit="sub_video", desc="inference") + for i in range(num_process): + sub_video_save_path = osp.join( + args.output, f"{args.video_name}_out_tmp_videos", f"{i:03d}.mp4" + ) + pool.apply_async( + inference_video, + args=( + args, + sub_video_save_path, + torch.device(i % num_gpus), + num_process, + i, + ), + callback=lambda arg: pbar.update(1), + ) + pool.close() + pool.join() + + # combine sub videos + # prepare vidlist.txt + with open(f"{args.output}/{args.video_name}_vidlist.txt", "w") as f: + for i in range(num_process): + f.write(f"file '{args.video_name}_out_tmp_videos/{i:03d}.mp4'\n") + + cmd = [ + args.ffmpeg_bin, + "-f", + "concat", + "-safe", + "0", + "-i", + f"{args.output}/{args.video_name}_vidlist.txt", + "-c", + "copy", + f"{video_save_path}", + ] + print(" ".join(cmd)) + subprocess.call(cmd) + shutil.rmtree(osp.join(args.output, f"{args.video_name}_out_tmp_videos")) + if osp.exists(osp.join(args.output, f"{args.video_name}_inp_tmp_videos")): + shutil.rmtree(osp.join(args.output, f"{args.video_name}_inp_tmp_videos")) + os.remove(f"{args.output}/{args.video_name}_vidlist.txt") + + +def main(): + """Inference demo for Real-ESRGAN. + It mainly for restoring anime videos. + + """ + parser = argparse.ArgumentParser() + parser.add_argument( + "-i", "--input", type=str, default="inputs", help="Input video, image or folder" + ) + parser.add_argument( + "-n", + "--model_name", + type=str, + default="realesr-animevideov3", + help=( + "Model names: realesr-animevideov3 | RealESRGAN_x4plus_anime_6B | RealESRGAN_x4plus | RealESRNet_x4plus |" + " RealESRGAN_x2plus | realesr-general-x4v3" + "Default:realesr-animevideov3" + ), + ) + parser.add_argument( + "-o", "--output", type=str, default="results", help="Output folder" + ) + parser.add_argument( + "-dn", + "--denoise_strength", + type=float, + default=0.5, + help=( + "Denoise strength. 0 for weak denoise (keep noise), 1 for strong denoise ability. " + "Only used for the realesr-general-x4v3 model" + ), + ) + parser.add_argument( + "-s", + "--outscale", + type=float, + default=4, + help="The final upsampling scale of the image", + ) + parser.add_argument( + "--suffix", type=str, default="out", help="Suffix of the restored video" + ) + parser.add_argument( + "-t", + "--tile", + type=int, + default=0, + help="Tile size, 0 for no tile during testing", + ) + parser.add_argument("--tile_pad", type=int, default=10, help="Tile padding") + parser.add_argument( + "--pre_pad", type=int, default=0, help="Pre padding size at each border" + ) + parser.add_argument( + "--face_enhance", action="store_true", help="Use GFPGAN to enhance face" + ) + parser.add_argument( + "--fp32", + action="store_true", + help="Use fp32 precision during inference. Default: fp16 (half precision).", + ) + parser.add_argument( + "--fps", type=float, default=None, help="FPS of the output video" + ) + parser.add_argument( + "--ffmpeg_bin", type=str, default="ffmpeg", help="The path to ffmpeg" + ) + parser.add_argument("--extract_frame_first", action="store_true") + parser.add_argument("--num_process_per_gpu", type=int, default=1) + + parser.add_argument( + "--alpha_upsampler", + type=str, + default="realesrgan", + help="The upsampler for the alpha channels. Options: realesrgan | bicubic", + ) + parser.add_argument( + "--ext", + type=str, + default="auto", + help="Image extension. Options: auto | jpg | png, auto means using the same extension as inputs", + ) + args = parser.parse_args() + + args.input = args.input.rstrip("/").rstrip("\\") + os.makedirs(args.output, exist_ok=True) + + if mimetypes.guess_type(args.input)[0] is not None and mimetypes.guess_type( + args.input + )[0].startswith("video"): + is_video = True + else: + is_video = False + + if is_video and args.input.endswith(".flv"): + mp4_path = args.input.replace(".flv", ".mp4") + os.system(f"ffmpeg -i {args.input} -codec copy {mp4_path}") + args.input = mp4_path + + if args.extract_frame_first and not is_video: + args.extract_frame_first = False + + run(args) + + if args.extract_frame_first: + tmp_frames_folder = osp.join(args.output, f"{args.video_name}_inp_tmp_frames") + shutil.rmtree(tmp_frames_folder) + + +if __name__ == "__main__": + main() diff --git a/RealESRGANv030/inputs/00003.png b/RealESRGANv030/inputs/00003.png new file mode 100644 index 0000000000000000000000000000000000000000..00cad23adf5d658caf03a0a2874f0c89d96c5ddc Binary files /dev/null and b/RealESRGANv030/inputs/00003.png differ diff --git a/RealESRGANv030/inputs/00017_gray.png b/RealESRGANv030/inputs/00017_gray.png new file mode 100644 index 0000000000000000000000000000000000000000..79af68e8aa0f036211734b7271633d88b2fc8f0d Binary files /dev/null and b/RealESRGANv030/inputs/00017_gray.png differ diff --git a/RealESRGANv030/inputs/0014.jpg b/RealESRGANv030/inputs/0014.jpg new file mode 100644 index 0000000000000000000000000000000000000000..f59554fe3143b3ffa27d6fcb04143124b4d0412b Binary files /dev/null and b/RealESRGANv030/inputs/0014.jpg differ diff --git a/RealESRGANv030/inputs/0030.jpg b/RealESRGANv030/inputs/0030.jpg new file mode 100644 index 0000000000000000000000000000000000000000..61868926af738046e984bcf652134e3ea9b958d9 Binary files /dev/null and b/RealESRGANv030/inputs/0030.jpg differ diff --git a/RealESRGANv030/inputs/ADE_val_00000114.jpg b/RealESRGANv030/inputs/ADE_val_00000114.jpg new file mode 100644 index 0000000000000000000000000000000000000000..b4d9c9067adbcdd153527cef2c0cab4cf40bbfa5 Binary files /dev/null and b/RealESRGANv030/inputs/ADE_val_00000114.jpg differ diff --git a/RealESRGANv030/inputs/OST_009.png b/RealESRGANv030/inputs/OST_009.png new file mode 100644 index 0000000000000000000000000000000000000000..10bbc831acb7065827a14eb7e0538312a8d6f3e2 Binary files /dev/null and b/RealESRGANv030/inputs/OST_009.png differ diff --git a/RealESRGANv030/inputs/children-alpha.png b/RealESRGANv030/inputs/children-alpha.png new file mode 100644 index 0000000000000000000000000000000000000000..41dcc3b6cc7a8a1b073f6dbe09d0c12e18c1b4b3 Binary files /dev/null and b/RealESRGANv030/inputs/children-alpha.png differ diff --git a/RealESRGANv030/inputs/tree_alpha_16bit.png b/RealESRGANv030/inputs/tree_alpha_16bit.png new file mode 100644 index 0000000000000000000000000000000000000000..ca7c2aac2c5c9cdaea66ecc8e06d6b43e3d8bf20 Binary files /dev/null and b/RealESRGANv030/inputs/tree_alpha_16bit.png differ diff --git a/RealESRGANv030/inputs/video/onepiece_demo.mp4 b/RealESRGANv030/inputs/video/onepiece_demo.mp4 new file mode 100644 index 0000000000000000000000000000000000000000..29b4e5246b19008885611c23921fe4423f17e43f Binary files /dev/null and b/RealESRGANv030/inputs/video/onepiece_demo.mp4 differ diff --git a/RealESRGANv030/inputs/wolf_gray.jpg b/RealESRGANv030/inputs/wolf_gray.jpg new file mode 100644 index 0000000000000000000000000000000000000000..614766bdbcaa3730a8191afcb9616305381245ea Binary files /dev/null and b/RealESRGANv030/inputs/wolf_gray.jpg differ diff --git a/RealESRGANv030/interface.py b/RealESRGANv030/interface.py new file mode 100644 index 0000000000000000000000000000000000000000..cebf9fc96b819b6133d2bfb8ba9b1796397c7454 --- /dev/null +++ b/RealESRGANv030/interface.py @@ -0,0 +1,206 @@ +import cv2 +import numpy as np +from PIL import Image +import glob +import os +from basicsr.archs.rrdbnet_arch import RRDBNet +from basicsr.utils.download_util import load_file_from_url + +from realesrgan import RealESRGANer +from realesrgan.archs.srvgg_arch import SRVGGNetCompact + + +def realEsrgan( + model_name="RealESRGAN_x4plus_anime_6B", + model_path=None, + input_dir="inputs", + output_dir="results", + denoise_strength=0.5, + outscale=4, + suffix="out", + tile=200, + tile_pad=10, + pre_pad=0, + face_enhance=True, + alpha_upsampler="realsrgan", + out_ext="auto", + fp32=True, + gpu_id=None, +): + + # determine models according to model names + model_name = model_name.split(".")[0] + if model_name == "RealESRGAN_x4plus": # x4 RRDBNet model + model = RRDBNet( + num_in_ch=3, + num_out_ch=3, + num_feat=64, + num_block=23, + num_grow_ch=32, + scale=4, + ) + netscale = 4 + file_url = [ + "https://github.com/xinntao/Real-ESRGAN/releases/download/v0.1.0/RealESRGAN_x4plus.pth" + ] + elif model_name == "RealESRNet_x4plus": # x4 RRDBNet model + model = RRDBNet( + num_in_ch=3, + num_out_ch=3, + num_feat=64, + num_block=23, + num_grow_ch=32, + scale=4, + ) + netscale = 4 + file_url = [ + "https://github.com/xinntao/Real-ESRGAN/releases/download/v0.1.1/RealESRNet_x4plus.pth" + ] + elif model_name == "RealESRGAN_x4plus_anime_6B": # x4 RRDBNet model with 6 blocks + model = RRDBNet( + num_in_ch=3, num_out_ch=3, num_feat=64, num_block=6, num_grow_ch=32, scale=4 + ) + netscale = 4 + file_url = [ + "https://github.com/xinntao/Real-ESRGAN/releases/download/v0.2.2.4/RealESRGAN_x4plus_anime_6B.pth" + ] + elif model_name == "RealESRGAN_x2plus": # x2 RRDBNet model + model = RRDBNet( + num_in_ch=3, + num_out_ch=3, + num_feat=64, + num_block=23, + num_grow_ch=32, + scale=2, + ) + netscale = 2 + file_url = [ + "https://github.com/xinntao/Real-ESRGAN/releases/download/v0.2.1/RealESRGAN_x2plus.pth" + ] + elif model_name == "realesr-animevideov3": # x4 VGG-style model (XS size) + model = SRVGGNetCompact( + num_in_ch=3, + num_out_ch=3, + num_feat=64, + num_conv=16, + upscale=4, + act_type="prelu", + ) + netscale = 4 + file_url = [ + "https://github.com/xinntao/Real-ESRGAN/releases/download/v0.2.5.0/realesr-animevideov3.pth" + ] + elif model_name == "realesr-general-x4v3": # x4 VGG-style model (S size) + model = SRVGGNetCompact( + num_in_ch=3, + num_out_ch=3, + num_feat=64, + num_conv=32, + upscale=4, + act_type="prelu", + ) + netscale = 4 + file_url = [ + "https://github.com/xinntao/Real-ESRGAN/releases/download/v0.2.5.0/realesr-general-wdn-x4v3.pth", + "https://github.com/xinntao/Real-ESRGAN/releases/download/v0.2.5.0/realesr-general-x4v3.pth", + ] + + # determine model paths + if model_path is None: + model_path = os.path.join("weights", model_name + ".pth") + if not os.path.isfile(model_path): + ROOT_DIR = os.path.dirname(os.path.abspath(__file__)) + for url in file_url: + # model_path will be updated + model_path = load_file_from_url( + url=url, + model_dir=os.path.join(ROOT_DIR, "weights"), + progress=True, + file_name=None, + ) + + # use dni to control the denoise strength + dni_weight = None + if model_name == "realesr-general-x4v3" and denoise_strength != 1: + wdn_model_path = model_path.replace( + "realesr-general-x4v3", "realesr-general-wdn-x4v3" + ) + model_path = [model_path, wdn_model_path] + dni_weight = [denoise_strength, 1 - denoise_strength] + + # restorer + upsampler = RealESRGANer( + scale=netscale, + model_path=model_path, + dni_weight=dni_weight, + model=model, + tile=tile, + tile_pad=tile_pad, + pre_pad=pre_pad, + half=not fp32, + gpu_id=gpu_id, + ) + + if face_enhance: # Use GFPGAN for face enhancement + from gfpgan import GFPGANer + + face_enhancer = GFPGANer( + model_path="https://github.com/TencentARC/GFPGAN/releases/download/v1.3.0/GFPGANv1.3.pth", + upscale=outscale, + arch="clean", + channel_multiplier=2, + bg_upsampler=upsampler, + ) + os.makedirs(output_dir, exist_ok=True) + + if not isinstance(input_dir, list): + paths = [input_dir] + else: + paths = sorted(glob.glob(os.path.join(input_dir, "*"))) + + Imgs = [] + for idx, path in enumerate(paths): + print(f"Scaling x{outscale}:", path) + if isinstance(path, Image.Image): + img = path + img = cv2.cvtColor(np.asarray(img), cv2.COLOR_RGB2BGR) + imgname = f"img_{idx}" + else: + imgname, extension = os.path.splitext(os.path.basename(path)) + img = cv2.imread(path, cv2.IMREAD_UNCHANGED) + if len(img.shape) == 3 and img.shape[2] == 4: + img_mode = "RGBA" + else: + img_mode = None + + try: + if face_enhance: + _, _, output = face_enhancer.enhance( + img, has_aligned=False, only_center_face=False, paste_back=True + ) + else: + output, _ = upsampler.enhance(img, outscale=outscale) + except RuntimeError as error: + print("Error", error) + print( + "If you encounter CUDA or RAM out of memory, try to set --tile with a smaller number." + ) + else: + # if out_ext == "auto": + # extension = extension[1:] + # else: + # extension = out_ext + # if img_mode == "RGBA": # RGBA images should be saved in png format + # extension = "png" + # if suffix == "": + # save_path = os.path.join(output_dir, f"{imgname}.{extension}") + # else: + # save_path = os.path.join(output_dir, f"{imgname}_{suffix}.{extension}") + # + # cv2.imwrite(save_path, output) + + img = cv2.cvtColor(img, cv2.COLOR_BGR2RGB) + img = Image.fromarray(img) + Imgs.append(img) + + return Imgs diff --git a/RealESRGANv030/options/finetune_realesrgan_x4plus.yml b/RealESRGANv030/options/finetune_realesrgan_x4plus.yml new file mode 100644 index 0000000000000000000000000000000000000000..aa9806570025dce0a967ca0541a0ea497a57d6a9 --- /dev/null +++ b/RealESRGANv030/options/finetune_realesrgan_x4plus.yml @@ -0,0 +1,188 @@ +# general settings +name: finetune_RealESRGANx4plus_400k +model_type: RealESRGANModel +scale: 4 +num_gpu: auto +manual_seed: 0 + +# ----------------- options for synthesizing training data in RealESRGANModel ----------------- # +# USM the ground-truth +l1_gt_usm: True +percep_gt_usm: True +gan_gt_usm: False + +# the first degradation process +resize_prob: [0.2, 0.7, 0.1] # up, down, keep +resize_range: [0.15, 1.5] +gaussian_noise_prob: 0.5 +noise_range: [1, 30] +poisson_scale_range: [0.05, 3] +gray_noise_prob: 0.4 +jpeg_range: [30, 95] + +# the second degradation process +second_blur_prob: 0.8 +resize_prob2: [0.3, 0.4, 0.3] # up, down, keep +resize_range2: [0.3, 1.2] +gaussian_noise_prob2: 0.5 +noise_range2: [1, 25] +poisson_scale_range2: [0.05, 2.5] +gray_noise_prob2: 0.4 +jpeg_range2: [30, 95] + +gt_size: 256 +queue_size: 180 + +# dataset and data loader settings +datasets: + train: + name: DF2K+OST + type: RealESRGANDataset + dataroot_gt: datasets/DF2K + meta_info: datasets/DF2K/meta_info/meta_info_DF2Kmultiscale+OST_sub.txt + io_backend: + type: disk + + blur_kernel_size: 21 + kernel_list: ['iso', 'aniso', 'generalized_iso', 'generalized_aniso', 'plateau_iso', 'plateau_aniso'] + kernel_prob: [0.45, 0.25, 0.12, 0.03, 0.12, 0.03] + sinc_prob: 0.1 + blur_sigma: [0.2, 3] + betag_range: [0.5, 4] + betap_range: [1, 2] + + blur_kernel_size2: 21 + kernel_list2: ['iso', 'aniso', 'generalized_iso', 'generalized_aniso', 'plateau_iso', 'plateau_aniso'] + kernel_prob2: [0.45, 0.25, 0.12, 0.03, 0.12, 0.03] + sinc_prob2: 0.1 + blur_sigma2: [0.2, 1.5] + betag_range2: [0.5, 4] + betap_range2: [1, 2] + + final_sinc_prob: 0.8 + + gt_size: 256 + use_hflip: True + use_rot: False + + # data loader + use_shuffle: true + num_worker_per_gpu: 5 + batch_size_per_gpu: 12 + dataset_enlarge_ratio: 1 + prefetch_mode: ~ + + # Uncomment these for validation + # val: + # name: validation + # type: PairedImageDataset + # dataroot_gt: path_to_gt + # dataroot_lq: path_to_lq + # io_backend: + # type: disk + +# network structures +network_g: + type: RRDBNet + num_in_ch: 3 + num_out_ch: 3 + num_feat: 64 + num_block: 23 + num_grow_ch: 32 + +network_d: + type: UNetDiscriminatorSN + num_in_ch: 3 + num_feat: 64 + skip_connection: True + +# path +path: + # use the pre-trained Real-ESRNet model + pretrain_network_g: experiments/pretrained_models/RealESRNet_x4plus.pth + param_key_g: params_ema + strict_load_g: true + pretrain_network_d: experiments/pretrained_models/RealESRGAN_x4plus_netD.pth + param_key_d: params + strict_load_d: true + resume_state: ~ + +# training settings +train: + ema_decay: 0.999 + optim_g: + type: Adam + lr: !!float 1e-4 + weight_decay: 0 + betas: [0.9, 0.99] + optim_d: + type: Adam + lr: !!float 1e-4 + weight_decay: 0 + betas: [0.9, 0.99] + + scheduler: + type: MultiStepLR + milestones: [400000] + gamma: 0.5 + + total_iter: 400000 + warmup_iter: -1 # no warm up + + # losses + pixel_opt: + type: L1Loss + loss_weight: 1.0 + reduction: mean + # perceptual loss (content and style losses) + perceptual_opt: + type: PerceptualLoss + layer_weights: + # before relu + 'conv1_2': 0.1 + 'conv2_2': 0.1 + 'conv3_4': 1 + 'conv4_4': 1 + 'conv5_4': 1 + vgg_type: vgg19 + use_input_norm: true + perceptual_weight: !!float 1.0 + style_weight: 0 + range_norm: false + criterion: l1 + # gan loss + gan_opt: + type: GANLoss + gan_type: vanilla + real_label_val: 1.0 + fake_label_val: 0.0 + loss_weight: !!float 1e-1 + + net_d_iters: 1 + net_d_init_iters: 0 + +# Uncomment these for validation +# validation settings +# val: +# val_freq: !!float 5e3 +# save_img: True + +# metrics: +# psnr: # metric name +# type: calculate_psnr +# crop_border: 4 +# test_y_channel: false + +# logging settings +logger: + print_freq: 100 + save_checkpoint_freq: !!float 5e3 + use_tb_logger: true + wandb: + project: ~ + resume_id: ~ + +# dist training settings +dist_params: + backend: nccl + port: 29500 diff --git a/RealESRGANv030/options/finetune_realesrgan_x4plus_pairdata.yml b/RealESRGANv030/options/finetune_realesrgan_x4plus_pairdata.yml new file mode 100644 index 0000000000000000000000000000000000000000..db45d4d275facc1191caa87d2d8618c30624477a --- /dev/null +++ b/RealESRGANv030/options/finetune_realesrgan_x4plus_pairdata.yml @@ -0,0 +1,150 @@ +# general settings +name: finetune_RealESRGANx4plus_400k_pairdata +model_type: RealESRGANModel +scale: 4 +num_gpu: auto +manual_seed: 0 + +# USM the ground-truth +l1_gt_usm: True +percep_gt_usm: True +gan_gt_usm: False + +high_order_degradation: False # do not use the high-order degradation generation process + +# dataset and data loader settings +datasets: + train: + name: DIV2K + type: RealESRGANPairedDataset + dataroot_gt: datasets/DF2K + dataroot_lq: datasets/DF2K + meta_info: datasets/DF2K/meta_info/meta_info_DIV2K_sub_pair.txt + io_backend: + type: disk + + gt_size: 256 + use_hflip: True + use_rot: False + + # data loader + use_shuffle: true + num_worker_per_gpu: 5 + batch_size_per_gpu: 12 + dataset_enlarge_ratio: 1 + prefetch_mode: ~ + + # Uncomment these for validation + # val: + # name: validation + # type: PairedImageDataset + # dataroot_gt: path_to_gt + # dataroot_lq: path_to_lq + # io_backend: + # type: disk + +# network structures +network_g: + type: RRDBNet + num_in_ch: 3 + num_out_ch: 3 + num_feat: 64 + num_block: 23 + num_grow_ch: 32 + +network_d: + type: UNetDiscriminatorSN + num_in_ch: 3 + num_feat: 64 + skip_connection: True + +# path +path: + # use the pre-trained Real-ESRNet model + pretrain_network_g: experiments/pretrained_models/RealESRNet_x4plus.pth + param_key_g: params_ema + strict_load_g: true + pretrain_network_d: experiments/pretrained_models/RealESRGAN_x4plus_netD.pth + param_key_d: params + strict_load_d: true + resume_state: ~ + +# training settings +train: + ema_decay: 0.999 + optim_g: + type: Adam + lr: !!float 1e-4 + weight_decay: 0 + betas: [0.9, 0.99] + optim_d: + type: Adam + lr: !!float 1e-4 + weight_decay: 0 + betas: [0.9, 0.99] + + scheduler: + type: MultiStepLR + milestones: [400000] + gamma: 0.5 + + total_iter: 400000 + warmup_iter: -1 # no warm up + + # losses + pixel_opt: + type: L1Loss + loss_weight: 1.0 + reduction: mean + # perceptual loss (content and style losses) + perceptual_opt: + type: PerceptualLoss + layer_weights: + # before relu + 'conv1_2': 0.1 + 'conv2_2': 0.1 + 'conv3_4': 1 + 'conv4_4': 1 + 'conv5_4': 1 + vgg_type: vgg19 + use_input_norm: true + perceptual_weight: !!float 1.0 + style_weight: 0 + range_norm: false + criterion: l1 + # gan loss + gan_opt: + type: GANLoss + gan_type: vanilla + real_label_val: 1.0 + fake_label_val: 0.0 + loss_weight: !!float 1e-1 + + net_d_iters: 1 + net_d_init_iters: 0 + +# Uncomment these for validation +# validation settings +# val: +# val_freq: !!float 5e3 +# save_img: True + +# metrics: +# psnr: # metric name +# type: calculate_psnr +# crop_border: 4 +# test_y_channel: false + +# logging settings +logger: + print_freq: 100 + save_checkpoint_freq: !!float 5e3 + use_tb_logger: true + wandb: + project: ~ + resume_id: ~ + +# dist training settings +dist_params: + backend: nccl + port: 29500 diff --git a/RealESRGANv030/options/train_realesrgan_x2plus.yml b/RealESRGANv030/options/train_realesrgan_x2plus.yml new file mode 100644 index 0000000000000000000000000000000000000000..3c98a0f370def397bdf47ede0fa5f6dd6a4411d5 --- /dev/null +++ b/RealESRGANv030/options/train_realesrgan_x2plus.yml @@ -0,0 +1,186 @@ +# general settings +name: train_RealESRGANx2plus_400k_B12G4 +model_type: RealESRGANModel +scale: 2 +num_gpu: auto # auto: can infer from your visible devices automatically. official: 4 GPUs +manual_seed: 0 + +# ----------------- options for synthesizing training data in RealESRGANModel ----------------- # +# USM the ground-truth +l1_gt_usm: True +percep_gt_usm: True +gan_gt_usm: False + +# the first degradation process +resize_prob: [0.2, 0.7, 0.1] # up, down, keep +resize_range: [0.15, 1.5] +gaussian_noise_prob: 0.5 +noise_range: [1, 30] +poisson_scale_range: [0.05, 3] +gray_noise_prob: 0.4 +jpeg_range: [30, 95] + +# the second degradation process +second_blur_prob: 0.8 +resize_prob2: [0.3, 0.4, 0.3] # up, down, keep +resize_range2: [0.3, 1.2] +gaussian_noise_prob2: 0.5 +noise_range2: [1, 25] +poisson_scale_range2: [0.05, 2.5] +gray_noise_prob2: 0.4 +jpeg_range2: [30, 95] + +gt_size: 256 +queue_size: 180 + +# dataset and data loader settings +datasets: + train: + name: DF2K+OST + type: RealESRGANDataset + dataroot_gt: datasets/DF2K + meta_info: datasets/DF2K/meta_info/meta_info_DF2Kmultiscale+OST_sub.txt + io_backend: + type: disk + + blur_kernel_size: 21 + kernel_list: ['iso', 'aniso', 'generalized_iso', 'generalized_aniso', 'plateau_iso', 'plateau_aniso'] + kernel_prob: [0.45, 0.25, 0.12, 0.03, 0.12, 0.03] + sinc_prob: 0.1 + blur_sigma: [0.2, 3] + betag_range: [0.5, 4] + betap_range: [1, 2] + + blur_kernel_size2: 21 + kernel_list2: ['iso', 'aniso', 'generalized_iso', 'generalized_aniso', 'plateau_iso', 'plateau_aniso'] + kernel_prob2: [0.45, 0.25, 0.12, 0.03, 0.12, 0.03] + sinc_prob2: 0.1 + blur_sigma2: [0.2, 1.5] + betag_range2: [0.5, 4] + betap_range2: [1, 2] + + final_sinc_prob: 0.8 + + gt_size: 256 + use_hflip: True + use_rot: False + + # data loader + use_shuffle: true + num_worker_per_gpu: 5 + batch_size_per_gpu: 12 + dataset_enlarge_ratio: 1 + prefetch_mode: ~ + + # Uncomment these for validation + # val: + # name: validation + # type: PairedImageDataset + # dataroot_gt: path_to_gt + # dataroot_lq: path_to_lq + # io_backend: + # type: disk + +# network structures +network_g: + type: RRDBNet + num_in_ch: 3 + num_out_ch: 3 + num_feat: 64 + num_block: 23 + num_grow_ch: 32 + scale: 2 + +network_d: + type: UNetDiscriminatorSN + num_in_ch: 3 + num_feat: 64 + skip_connection: True + +# path +path: + # use the pre-trained Real-ESRNet model + pretrain_network_g: experiments/pretrained_models/RealESRNet_x2plus.pth + param_key_g: params_ema + strict_load_g: true + resume_state: ~ + +# training settings +train: + ema_decay: 0.999 + optim_g: + type: Adam + lr: !!float 1e-4 + weight_decay: 0 + betas: [0.9, 0.99] + optim_d: + type: Adam + lr: !!float 1e-4 + weight_decay: 0 + betas: [0.9, 0.99] + + scheduler: + type: MultiStepLR + milestones: [400000] + gamma: 0.5 + + total_iter: 400000 + warmup_iter: -1 # no warm up + + # losses + pixel_opt: + type: L1Loss + loss_weight: 1.0 + reduction: mean + # perceptual loss (content and style losses) + perceptual_opt: + type: PerceptualLoss + layer_weights: + # before relu + 'conv1_2': 0.1 + 'conv2_2': 0.1 + 'conv3_4': 1 + 'conv4_4': 1 + 'conv5_4': 1 + vgg_type: vgg19 + use_input_norm: true + perceptual_weight: !!float 1.0 + style_weight: 0 + range_norm: false + criterion: l1 + # gan loss + gan_opt: + type: GANLoss + gan_type: vanilla + real_label_val: 1.0 + fake_label_val: 0.0 + loss_weight: !!float 1e-1 + + net_d_iters: 1 + net_d_init_iters: 0 + +# Uncomment these for validation +# validation settings +# val: +# val_freq: !!float 5e3 +# save_img: True + +# metrics: +# psnr: # metric name +# type: calculate_psnr +# crop_border: 4 +# test_y_channel: false + +# logging settings +logger: + print_freq: 100 + save_checkpoint_freq: !!float 5e3 + use_tb_logger: true + wandb: + project: ~ + resume_id: ~ + +# dist training settings +dist_params: + backend: nccl + port: 29500 diff --git a/RealESRGANv030/options/train_realesrgan_x4plus.yml b/RealESRGANv030/options/train_realesrgan_x4plus.yml new file mode 100644 index 0000000000000000000000000000000000000000..763199a35fa0135713b4a87b00c25f63062ac8aa --- /dev/null +++ b/RealESRGANv030/options/train_realesrgan_x4plus.yml @@ -0,0 +1,185 @@ +# general settings +name: train_RealESRGANx4plus_400k_B12G4 +model_type: RealESRGANModel +scale: 4 +num_gpu: auto # auto: can infer from your visible devices automatically. official: 4 GPUs +manual_seed: 0 + +# ----------------- options for synthesizing training data in RealESRGANModel ----------------- # +# USM the ground-truth +l1_gt_usm: True +percep_gt_usm: True +gan_gt_usm: False + +# the first degradation process +resize_prob: [0.2, 0.7, 0.1] # up, down, keep +resize_range: [0.15, 1.5] +gaussian_noise_prob: 0.5 +noise_range: [1, 30] +poisson_scale_range: [0.05, 3] +gray_noise_prob: 0.4 +jpeg_range: [30, 95] + +# the second degradation process +second_blur_prob: 0.8 +resize_prob2: [0.3, 0.4, 0.3] # up, down, keep +resize_range2: [0.3, 1.2] +gaussian_noise_prob2: 0.5 +noise_range2: [1, 25] +poisson_scale_range2: [0.05, 2.5] +gray_noise_prob2: 0.4 +jpeg_range2: [30, 95] + +gt_size: 256 +queue_size: 180 + +# dataset and data loader settings +datasets: + train: + name: DF2K+OST + type: RealESRGANDataset + dataroot_gt: datasets/DF2K + meta_info: datasets/DF2K/meta_info/meta_info_DF2Kmultiscale+OST_sub.txt + io_backend: + type: disk + + blur_kernel_size: 21 + kernel_list: ['iso', 'aniso', 'generalized_iso', 'generalized_aniso', 'plateau_iso', 'plateau_aniso'] + kernel_prob: [0.45, 0.25, 0.12, 0.03, 0.12, 0.03] + sinc_prob: 0.1 + blur_sigma: [0.2, 3] + betag_range: [0.5, 4] + betap_range: [1, 2] + + blur_kernel_size2: 21 + kernel_list2: ['iso', 'aniso', 'generalized_iso', 'generalized_aniso', 'plateau_iso', 'plateau_aniso'] + kernel_prob2: [0.45, 0.25, 0.12, 0.03, 0.12, 0.03] + sinc_prob2: 0.1 + blur_sigma2: [0.2, 1.5] + betag_range2: [0.5, 4] + betap_range2: [1, 2] + + final_sinc_prob: 0.8 + + gt_size: 256 + use_hflip: True + use_rot: False + + # data loader + use_shuffle: true + num_worker_per_gpu: 5 + batch_size_per_gpu: 12 + dataset_enlarge_ratio: 1 + prefetch_mode: ~ + + # Uncomment these for validation + # val: + # name: validation + # type: PairedImageDataset + # dataroot_gt: path_to_gt + # dataroot_lq: path_to_lq + # io_backend: + # type: disk + +# network structures +network_g: + type: RRDBNet + num_in_ch: 3 + num_out_ch: 3 + num_feat: 64 + num_block: 23 + num_grow_ch: 32 + +network_d: + type: UNetDiscriminatorSN + num_in_ch: 3 + num_feat: 64 + skip_connection: True + +# path +path: + # use the pre-trained Real-ESRNet model + pretrain_network_g: experiments/pretrained_models/RealESRNet_x4plus.pth + param_key_g: params_ema + strict_load_g: true + resume_state: ~ + +# training settings +train: + ema_decay: 0.999 + optim_g: + type: Adam + lr: !!float 1e-4 + weight_decay: 0 + betas: [0.9, 0.99] + optim_d: + type: Adam + lr: !!float 1e-4 + weight_decay: 0 + betas: [0.9, 0.99] + + scheduler: + type: MultiStepLR + milestones: [400000] + gamma: 0.5 + + total_iter: 400000 + warmup_iter: -1 # no warm up + + # losses + pixel_opt: + type: L1Loss + loss_weight: 1.0 + reduction: mean + # perceptual loss (content and style losses) + perceptual_opt: + type: PerceptualLoss + layer_weights: + # before relu + 'conv1_2': 0.1 + 'conv2_2': 0.1 + 'conv3_4': 1 + 'conv4_4': 1 + 'conv5_4': 1 + vgg_type: vgg19 + use_input_norm: true + perceptual_weight: !!float 1.0 + style_weight: 0 + range_norm: false + criterion: l1 + # gan loss + gan_opt: + type: GANLoss + gan_type: vanilla + real_label_val: 1.0 + fake_label_val: 0.0 + loss_weight: !!float 1e-1 + + net_d_iters: 1 + net_d_init_iters: 0 + +# Uncomment these for validation +# validation settings +# val: +# val_freq: !!float 5e3 +# save_img: True + +# metrics: +# psnr: # metric name +# type: calculate_psnr +# crop_border: 4 +# test_y_channel: false + +# logging settings +logger: + print_freq: 100 + save_checkpoint_freq: !!float 5e3 + use_tb_logger: true + wandb: + project: ~ + resume_id: ~ + +# dist training settings +dist_params: + backend: nccl + port: 29500 diff --git a/RealESRGANv030/options/train_realesrnet_x2plus.yml b/RealESRGANv030/options/train_realesrnet_x2plus.yml new file mode 100644 index 0000000000000000000000000000000000000000..81ee9ef16817eaf17cf993cea1a4a8d51815d96c --- /dev/null +++ b/RealESRGANv030/options/train_realesrnet_x2plus.yml @@ -0,0 +1,145 @@ +# general settings +name: train_RealESRNetx2plus_1000k_B12G4 +model_type: RealESRNetModel +scale: 2 +num_gpu: auto # auto: can infer from your visible devices automatically. official: 4 GPUs +manual_seed: 0 + +# ----------------- options for synthesizing training data in RealESRNetModel ----------------- # +gt_usm: True # USM the ground-truth + +# the first degradation process +resize_prob: [0.2, 0.7, 0.1] # up, down, keep +resize_range: [0.15, 1.5] +gaussian_noise_prob: 0.5 +noise_range: [1, 30] +poisson_scale_range: [0.05, 3] +gray_noise_prob: 0.4 +jpeg_range: [30, 95] + +# the second degradation process +second_blur_prob: 0.8 +resize_prob2: [0.3, 0.4, 0.3] # up, down, keep +resize_range2: [0.3, 1.2] +gaussian_noise_prob2: 0.5 +noise_range2: [1, 25] +poisson_scale_range2: [0.05, 2.5] +gray_noise_prob2: 0.4 +jpeg_range2: [30, 95] + +gt_size: 256 +queue_size: 180 + +# dataset and data loader settings +datasets: + train: + name: DF2K+OST + type: RealESRGANDataset + dataroot_gt: datasets/DF2K + meta_info: datasets/DF2K/meta_info/meta_info_DF2Kmultiscale+OST_sub.txt + io_backend: + type: disk + + blur_kernel_size: 21 + kernel_list: ['iso', 'aniso', 'generalized_iso', 'generalized_aniso', 'plateau_iso', 'plateau_aniso'] + kernel_prob: [0.45, 0.25, 0.12, 0.03, 0.12, 0.03] + sinc_prob: 0.1 + blur_sigma: [0.2, 3] + betag_range: [0.5, 4] + betap_range: [1, 2] + + blur_kernel_size2: 21 + kernel_list2: ['iso', 'aniso', 'generalized_iso', 'generalized_aniso', 'plateau_iso', 'plateau_aniso'] + kernel_prob2: [0.45, 0.25, 0.12, 0.03, 0.12, 0.03] + sinc_prob2: 0.1 + blur_sigma2: [0.2, 1.5] + betag_range2: [0.5, 4] + betap_range2: [1, 2] + + final_sinc_prob: 0.8 + + gt_size: 256 + use_hflip: True + use_rot: False + + # data loader + use_shuffle: true + num_worker_per_gpu: 5 + batch_size_per_gpu: 12 + dataset_enlarge_ratio: 1 + prefetch_mode: ~ + + # Uncomment these for validation + # val: + # name: validation + # type: PairedImageDataset + # dataroot_gt: path_to_gt + # dataroot_lq: path_to_lq + # io_backend: + # type: disk + +# network structures +network_g: + type: RRDBNet + num_in_ch: 3 + num_out_ch: 3 + num_feat: 64 + num_block: 23 + num_grow_ch: 32 + scale: 2 + +# path +path: + pretrain_network_g: experiments/pretrained_models/RealESRGAN_x4plus.pth + param_key_g: params_ema + strict_load_g: False + resume_state: ~ + +# training settings +train: + ema_decay: 0.999 + optim_g: + type: Adam + lr: !!float 2e-4 + weight_decay: 0 + betas: [0.9, 0.99] + + scheduler: + type: MultiStepLR + milestones: [1000000] + gamma: 0.5 + + total_iter: 1000000 + warmup_iter: -1 # no warm up + + # losses + pixel_opt: + type: L1Loss + loss_weight: 1.0 + reduction: mean + +# Uncomment these for validation +# validation settings +# val: +# val_freq: !!float 5e3 +# save_img: True + +# metrics: +# psnr: # metric name +# type: calculate_psnr +# crop_border: 4 +# test_y_channel: false + +# logging settings +logger: + print_freq: 100 + save_checkpoint_freq: !!float 5e3 + use_tb_logger: true + wandb: + project: ~ + resume_id: ~ + +# dist training settings +dist_params: + backend: nccl + port: 29500 diff --git a/RealESRGANv030/options/train_realesrnet_x4plus.yml b/RealESRGANv030/options/train_realesrnet_x4plus.yml new file mode 100644 index 0000000000000000000000000000000000000000..45670ed824ae0c697a395049b089e50364292dfc --- /dev/null +++ b/RealESRGANv030/options/train_realesrnet_x4plus.yml @@ -0,0 +1,144 @@ +# general settings +name: train_RealESRNetx4plus_1000k_B12G4 +model_type: RealESRNetModel +scale: 4 +num_gpu: auto # auto: can infer from your visible devices automatically. official: 4 GPUs +manual_seed: 0 + +# ----------------- options for synthesizing training data in RealESRNetModel ----------------- # +gt_usm: True # USM the ground-truth + +# the first degradation process +resize_prob: [0.2, 0.7, 0.1] # up, down, keep +resize_range: [0.15, 1.5] +gaussian_noise_prob: 0.5 +noise_range: [1, 30] +poisson_scale_range: [0.05, 3] +gray_noise_prob: 0.4 +jpeg_range: [30, 95] + +# the second degradation process +second_blur_prob: 0.8 +resize_prob2: [0.3, 0.4, 0.3] # up, down, keep +resize_range2: [0.3, 1.2] +gaussian_noise_prob2: 0.5 +noise_range2: [1, 25] +poisson_scale_range2: [0.05, 2.5] +gray_noise_prob2: 0.4 +jpeg_range2: [30, 95] + +gt_size: 256 +queue_size: 180 + +# dataset and data loader settings +datasets: + train: + name: DF2K+OST + type: RealESRGANDataset + dataroot_gt: datasets/DF2K + meta_info: datasets/DF2K/meta_info/meta_info_DF2Kmultiscale+OST_sub.txt + io_backend: + type: disk + + blur_kernel_size: 21 + kernel_list: ['iso', 'aniso', 'generalized_iso', 'generalized_aniso', 'plateau_iso', 'plateau_aniso'] + kernel_prob: [0.45, 0.25, 0.12, 0.03, 0.12, 0.03] + sinc_prob: 0.1 + blur_sigma: [0.2, 3] + betag_range: [0.5, 4] + betap_range: [1, 2] + + blur_kernel_size2: 21 + kernel_list2: ['iso', 'aniso', 'generalized_iso', 'generalized_aniso', 'plateau_iso', 'plateau_aniso'] + kernel_prob2: [0.45, 0.25, 0.12, 0.03, 0.12, 0.03] + sinc_prob2: 0.1 + blur_sigma2: [0.2, 1.5] + betag_range2: [0.5, 4] + betap_range2: [1, 2] + + final_sinc_prob: 0.8 + + gt_size: 256 + use_hflip: True + use_rot: False + + # data loader + use_shuffle: true + num_worker_per_gpu: 5 + batch_size_per_gpu: 12 + dataset_enlarge_ratio: 1 + prefetch_mode: ~ + + # Uncomment these for validation + # val: + # name: validation + # type: PairedImageDataset + # dataroot_gt: path_to_gt + # dataroot_lq: path_to_lq + # io_backend: + # type: disk + +# network structures +network_g: + type: RRDBNet + num_in_ch: 3 + num_out_ch: 3 + num_feat: 64 + num_block: 23 + num_grow_ch: 32 + +# path +path: + pretrain_network_g: experiments/pretrained_models/ESRGAN_SRx4_DF2KOST_official-ff704c30.pth + param_key_g: params_ema + strict_load_g: true + resume_state: ~ + +# training settings +train: + ema_decay: 0.999 + optim_g: + type: Adam + lr: !!float 2e-4 + weight_decay: 0 + betas: [0.9, 0.99] + + scheduler: + type: MultiStepLR + milestones: [1000000] + gamma: 0.5 + + total_iter: 1000000 + warmup_iter: -1 # no warm up + + # losses + pixel_opt: + type: L1Loss + loss_weight: 1.0 + reduction: mean + +# Uncomment these for validation +# validation settings +# val: +# val_freq: !!float 5e3 +# save_img: True + +# metrics: +# psnr: # metric name +# type: calculate_psnr +# crop_border: 4 +# test_y_channel: false + +# logging settings +logger: + print_freq: 100 + save_checkpoint_freq: !!float 5e3 + use_tb_logger: true + wandb: + project: ~ + resume_id: ~ + +# dist training settings +dist_params: + backend: nccl + port: 29500 diff --git a/RealESRGANv030/realesrgan/__init__.py b/RealESRGANv030/realesrgan/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..2276f1eecded80d1f00ff97b45c66c7a8922b987 --- /dev/null +++ b/RealESRGANv030/realesrgan/__init__.py @@ -0,0 +1,6 @@ +# flake8: noqa +from .archs import * +from .data import * +from .models import * +from .utils import * +from .version import * diff --git a/RealESRGANv030/realesrgan/archs/__init__.py b/RealESRGANv030/realesrgan/archs/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..d787f84e99eabda721d89640f3602038062fbc92 --- /dev/null +++ b/RealESRGANv030/realesrgan/archs/__init__.py @@ -0,0 +1,17 @@ +import importlib +from basicsr.utils import scandir +from os import path as osp + +# automatically scan and import arch modules for registry +# scan all the files that end with '_arch.py' under the archs folder +arch_folder = osp.dirname(osp.abspath(__file__)) +arch_filenames = [ + osp.splitext(osp.basename(v))[0] + for v in scandir(arch_folder) + if v.endswith("_arch.py") +] +# import all the arch modules +_arch_modules = [ + importlib.import_module(f"realesrgan.archs.{file_name}") + for file_name in arch_filenames +] diff --git a/RealESRGANv030/realesrgan/archs/discriminator_arch.py b/RealESRGANv030/realesrgan/archs/discriminator_arch.py new file mode 100644 index 0000000000000000000000000000000000000000..ccd810559201624bc6c20ea9b60009b927ecadd6 --- /dev/null +++ b/RealESRGANv030/realesrgan/archs/discriminator_arch.py @@ -0,0 +1,67 @@ +from basicsr.utils.registry import ARCH_REGISTRY +from torch import nn as nn +from torch.nn import functional as F +from torch.nn.utils import spectral_norm + + +@ARCH_REGISTRY.register() +class UNetDiscriminatorSN(nn.Module): + """Defines a U-Net discriminator with spectral normalization (SN) + + It is used in Real-ESRGAN: Training Real-World Blind Super-Resolution with Pure Synthetic Data. + + Arg: + num_in_ch (int): Channel number of inputs. Default: 3. + num_feat (int): Channel number of base intermediate features. Default: 64. + skip_connection (bool): Whether to use skip connections between U-Net. Default: True. + """ + + def __init__(self, num_in_ch, num_feat=64, skip_connection=True): + super(UNetDiscriminatorSN, self).__init__() + self.skip_connection = skip_connection + norm = spectral_norm + # the first convolution + self.conv0 = nn.Conv2d(num_in_ch, num_feat, kernel_size=3, stride=1, padding=1) + # downsample + self.conv1 = norm(nn.Conv2d(num_feat, num_feat * 2, 4, 2, 1, bias=False)) + self.conv2 = norm(nn.Conv2d(num_feat * 2, num_feat * 4, 4, 2, 1, bias=False)) + self.conv3 = norm(nn.Conv2d(num_feat * 4, num_feat * 8, 4, 2, 1, bias=False)) + # upsample + self.conv4 = norm(nn.Conv2d(num_feat * 8, num_feat * 4, 3, 1, 1, bias=False)) + self.conv5 = norm(nn.Conv2d(num_feat * 4, num_feat * 2, 3, 1, 1, bias=False)) + self.conv6 = norm(nn.Conv2d(num_feat * 2, num_feat, 3, 1, 1, bias=False)) + # extra convolutions + self.conv7 = norm(nn.Conv2d(num_feat, num_feat, 3, 1, 1, bias=False)) + self.conv8 = norm(nn.Conv2d(num_feat, num_feat, 3, 1, 1, bias=False)) + self.conv9 = nn.Conv2d(num_feat, 1, 3, 1, 1) + + def forward(self, x): + # downsample + x0 = F.leaky_relu(self.conv0(x), negative_slope=0.2, inplace=True) + x1 = F.leaky_relu(self.conv1(x0), negative_slope=0.2, inplace=True) + x2 = F.leaky_relu(self.conv2(x1), negative_slope=0.2, inplace=True) + x3 = F.leaky_relu(self.conv3(x2), negative_slope=0.2, inplace=True) + + # upsample + x3 = F.interpolate(x3, scale_factor=2, mode="bilinear", align_corners=False) + x4 = F.leaky_relu(self.conv4(x3), negative_slope=0.2, inplace=True) + + if self.skip_connection: + x4 = x4 + x2 + x4 = F.interpolate(x4, scale_factor=2, mode="bilinear", align_corners=False) + x5 = F.leaky_relu(self.conv5(x4), negative_slope=0.2, inplace=True) + + if self.skip_connection: + x5 = x5 + x1 + x5 = F.interpolate(x5, scale_factor=2, mode="bilinear", align_corners=False) + x6 = F.leaky_relu(self.conv6(x5), negative_slope=0.2, inplace=True) + + if self.skip_connection: + x6 = x6 + x0 + + # extra convolutions + out = F.leaky_relu(self.conv7(x6), negative_slope=0.2, inplace=True) + out = F.leaky_relu(self.conv8(out), negative_slope=0.2, inplace=True) + out = self.conv9(out) + + return out diff --git a/RealESRGANv030/realesrgan/archs/srvgg_arch.py b/RealESRGANv030/realesrgan/archs/srvgg_arch.py new file mode 100644 index 0000000000000000000000000000000000000000..23b2f372a2975b499b6c05bf213cf7dec1a1cea6 --- /dev/null +++ b/RealESRGANv030/realesrgan/archs/srvgg_arch.py @@ -0,0 +1,77 @@ +from basicsr.utils.registry import ARCH_REGISTRY +from torch import nn as nn +from torch.nn import functional as F + + +@ARCH_REGISTRY.register() +class SRVGGNetCompact(nn.Module): + """A compact VGG-style network structure for super-resolution. + + It is a compact network structure, which performs upsampling in the last layer and no convolution is + conducted on the HR feature space. + + Args: + num_in_ch (int): Channel number of inputs. Default: 3. + num_out_ch (int): Channel number of outputs. Default: 3. + num_feat (int): Channel number of intermediate features. Default: 64. + num_conv (int): Number of convolution layers in the body network. Default: 16. + upscale (int): Upsampling factor. Default: 4. + act_type (str): Activation type, options: 'relu', 'prelu', 'leakyrelu'. Default: prelu. + """ + + def __init__( + self, + num_in_ch=3, + num_out_ch=3, + num_feat=64, + num_conv=16, + upscale=4, + act_type="prelu", + ): + super(SRVGGNetCompact, self).__init__() + self.num_in_ch = num_in_ch + self.num_out_ch = num_out_ch + self.num_feat = num_feat + self.num_conv = num_conv + self.upscale = upscale + self.act_type = act_type + + self.body = nn.ModuleList() + # the first conv + self.body.append(nn.Conv2d(num_in_ch, num_feat, 3, 1, 1)) + # the first activation + if act_type == "relu": + activation = nn.ReLU(inplace=True) + elif act_type == "prelu": + activation = nn.PReLU(num_parameters=num_feat) + elif act_type == "leakyrelu": + activation = nn.LeakyReLU(negative_slope=0.1, inplace=True) + self.body.append(activation) + + # the body structure + for _ in range(num_conv): + self.body.append(nn.Conv2d(num_feat, num_feat, 3, 1, 1)) + # activation + if act_type == "relu": + activation = nn.ReLU(inplace=True) + elif act_type == "prelu": + activation = nn.PReLU(num_parameters=num_feat) + elif act_type == "leakyrelu": + activation = nn.LeakyReLU(negative_slope=0.1, inplace=True) + self.body.append(activation) + + # the last conv + self.body.append(nn.Conv2d(num_feat, num_out_ch * upscale * upscale, 3, 1, 1)) + # upsample + self.upsampler = nn.PixelShuffle(upscale) + + def forward(self, x): + out = x + for i in range(0, len(self.body)): + out = self.body[i](out) + + out = self.upsampler(out) + # add the nearest upsampled image, so that the network learns the residual + base = F.interpolate(x, scale_factor=self.upscale, mode="nearest") + out += base + return out diff --git a/RealESRGANv030/realesrgan/data/__init__.py b/RealESRGANv030/realesrgan/data/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..20d7df4af5007ba1b14bae40118fbd3fbe61f759 --- /dev/null +++ b/RealESRGANv030/realesrgan/data/__init__.py @@ -0,0 +1,17 @@ +import importlib +from basicsr.utils import scandir +from os import path as osp + +# automatically scan and import dataset modules for registry +# scan all the files that end with '_dataset.py' under the data folder +data_folder = osp.dirname(osp.abspath(__file__)) +dataset_filenames = [ + osp.splitext(osp.basename(v))[0] + for v in scandir(data_folder) + if v.endswith("_dataset.py") +] +# import all the dataset modules +_dataset_modules = [ + importlib.import_module(f"realesrgan.data.{file_name}") + for file_name in dataset_filenames +] diff --git a/RealESRGANv030/realesrgan/data/realesrgan_dataset.py b/RealESRGANv030/realesrgan/data/realesrgan_dataset.py new file mode 100644 index 0000000000000000000000000000000000000000..5d2a2fbd7b19d1eb7e320a170531fbf676ce7cec --- /dev/null +++ b/RealESRGANv030/realesrgan/data/realesrgan_dataset.py @@ -0,0 +1,216 @@ +import cv2 +import math +import numpy as np +import os +import os.path as osp +import random +import time +import torch +from basicsr.data.degradations import circular_lowpass_kernel, random_mixed_kernels +from basicsr.data.transforms import augment +from basicsr.utils import FileClient, get_root_logger, imfrombytes, img2tensor +from basicsr.utils.registry import DATASET_REGISTRY +from torch.utils import data as data + + +@DATASET_REGISTRY.register() +class RealESRGANDataset(data.Dataset): + """Dataset used for Real-ESRGAN model: + Real-ESRGAN: Training Real-World Blind Super-Resolution with Pure Synthetic Data. + + It loads gt (Ground-Truth) images, and augments them. + It also generates blur kernels and sinc kernels for generating low-quality images. + Note that the low-quality images are processed in tensors on GPUS for faster processing. + + Args: + opt (dict): Config for train datasets. It contains the following keys: + dataroot_gt (str): Data root path for gt. + meta_info (str): Path for meta information file. + io_backend (dict): IO backend type and other kwarg. + use_hflip (bool): Use horizontal flips. + use_rot (bool): Use rotation (use vertical flip and transposing h and w for implementation). + Please see more options in the codes. + """ + + def __init__(self, opt): + super(RealESRGANDataset, self).__init__() + self.opt = opt + self.file_client = None + self.io_backend_opt = opt["io_backend"] + self.gt_folder = opt["dataroot_gt"] + + # file client (lmdb io backend) + if self.io_backend_opt["type"] == "lmdb": + self.io_backend_opt["db_paths"] = [self.gt_folder] + self.io_backend_opt["client_keys"] = ["gt"] + if not self.gt_folder.endswith(".lmdb"): + raise ValueError( + f"'dataroot_gt' should end with '.lmdb', but received {self.gt_folder}" + ) + with open(osp.join(self.gt_folder, "meta_info.txt")) as fin: + self.paths = [line.split(".")[0] for line in fin] + else: + # disk backend with meta_info + # Each line in the meta_info describes the relative path to an image + with open(self.opt["meta_info"]) as fin: + paths = [line.strip().split(" ")[0] for line in fin] + self.paths = [os.path.join(self.gt_folder, v) for v in paths] + + # blur settings for the first degradation + self.blur_kernel_size = opt["blur_kernel_size"] + self.kernel_list = opt["kernel_list"] + self.kernel_prob = opt["kernel_prob"] # a list for each kernel probability + self.blur_sigma = opt["blur_sigma"] + self.betag_range = opt[ + "betag_range" + ] # betag used in generalized Gaussian blur kernels + self.betap_range = opt["betap_range"] # betap used in plateau blur kernels + self.sinc_prob = opt["sinc_prob"] # the probability for sinc filters + + # blur settings for the second degradation + self.blur_kernel_size2 = opt["blur_kernel_size2"] + self.kernel_list2 = opt["kernel_list2"] + self.kernel_prob2 = opt["kernel_prob2"] + self.blur_sigma2 = opt["blur_sigma2"] + self.betag_range2 = opt["betag_range2"] + self.betap_range2 = opt["betap_range2"] + self.sinc_prob2 = opt["sinc_prob2"] + + # a final sinc filter + self.final_sinc_prob = opt["final_sinc_prob"] + + self.kernel_range = [ + 2 * v + 1 for v in range(3, 11) + ] # kernel size ranges from 7 to 21 + # TODO: kernel range is now hard-coded, should be in the configure file + self.pulse_tensor = torch.zeros( + 21, 21 + ).float() # convolving with pulse tensor brings no blurry effect + self.pulse_tensor[10, 10] = 1 + + def __getitem__(self, index): + if self.file_client is None: + self.file_client = FileClient( + self.io_backend_opt.pop("type"), **self.io_backend_opt + ) + + # -------------------------------- Load gt images -------------------------------- # + # Shape: (h, w, c); channel order: BGR; image range: [0, 1], float32. + gt_path = self.paths[index] + # avoid errors caused by high latency in reading files + retry = 3 + while retry > 0: + try: + img_bytes = self.file_client.get(gt_path, "gt") + except (IOError, OSError) as e: + logger = get_root_logger() + logger.warn( + f"File client error: {e}, remaining retry times: {retry - 1}" + ) + # change another file to read + index = random.randint(0, self.__len__()) + gt_path = self.paths[index] + time.sleep(1) # sleep 1s for occasional server congestion + else: + break + finally: + retry -= 1 + img_gt = imfrombytes(img_bytes, float32=True) + + # -------------------- Do augmentation for training: flip, rotation -------------------- # + img_gt = augment(img_gt, self.opt["use_hflip"], self.opt["use_rot"]) + + # crop or pad to 400 + # TODO: 400 is hard-coded. You may change it accordingly + h, w = img_gt.shape[0:2] + crop_pad_size = 400 + # pad + if h < crop_pad_size or w < crop_pad_size: + pad_h = max(0, crop_pad_size - h) + pad_w = max(0, crop_pad_size - w) + img_gt = cv2.copyMakeBorder( + img_gt, 0, pad_h, 0, pad_w, cv2.BORDER_REFLECT_101 + ) + # crop + if img_gt.shape[0] > crop_pad_size or img_gt.shape[1] > crop_pad_size: + h, w = img_gt.shape[0:2] + # randomly choose top and left coordinates + top = random.randint(0, h - crop_pad_size) + left = random.randint(0, w - crop_pad_size) + img_gt = img_gt[top : top + crop_pad_size, left : left + crop_pad_size, ...] + + # ------------------------ Generate kernels (used in the first degradation) ------------------------ # + kernel_size = random.choice(self.kernel_range) + if np.random.uniform() < self.opt["sinc_prob"]: + # this sinc filter setting is for kernels ranging from [7, 21] + if kernel_size < 13: + omega_c = np.random.uniform(np.pi / 3, np.pi) + else: + omega_c = np.random.uniform(np.pi / 5, np.pi) + kernel = circular_lowpass_kernel(omega_c, kernel_size, pad_to=False) + else: + kernel = random_mixed_kernels( + self.kernel_list, + self.kernel_prob, + kernel_size, + self.blur_sigma, + self.blur_sigma, + [-math.pi, math.pi], + self.betag_range, + self.betap_range, + noise_range=None, + ) + # pad kernel + pad_size = (21 - kernel_size) // 2 + kernel = np.pad(kernel, ((pad_size, pad_size), (pad_size, pad_size))) + + # ------------------------ Generate kernels (used in the second degradation) ------------------------ # + kernel_size = random.choice(self.kernel_range) + if np.random.uniform() < self.opt["sinc_prob2"]: + if kernel_size < 13: + omega_c = np.random.uniform(np.pi / 3, np.pi) + else: + omega_c = np.random.uniform(np.pi / 5, np.pi) + kernel2 = circular_lowpass_kernel(omega_c, kernel_size, pad_to=False) + else: + kernel2 = random_mixed_kernels( + self.kernel_list2, + self.kernel_prob2, + kernel_size, + self.blur_sigma2, + self.blur_sigma2, + [-math.pi, math.pi], + self.betag_range2, + self.betap_range2, + noise_range=None, + ) + + # pad kernel + pad_size = (21 - kernel_size) // 2 + kernel2 = np.pad(kernel2, ((pad_size, pad_size), (pad_size, pad_size))) + + # ------------------------------------- the final sinc kernel ------------------------------------- # + if np.random.uniform() < self.opt["final_sinc_prob"]: + kernel_size = random.choice(self.kernel_range) + omega_c = np.random.uniform(np.pi / 3, np.pi) + sinc_kernel = circular_lowpass_kernel(omega_c, kernel_size, pad_to=21) + sinc_kernel = torch.FloatTensor(sinc_kernel) + else: + sinc_kernel = self.pulse_tensor + + # BGR to RGB, HWC to CHW, numpy to tensor + img_gt = img2tensor([img_gt], bgr2rgb=True, float32=True)[0] + kernel = torch.FloatTensor(kernel) + kernel2 = torch.FloatTensor(kernel2) + + return_d = { + "gt": img_gt, + "kernel1": kernel, + "kernel2": kernel2, + "sinc_kernel": sinc_kernel, + "gt_path": gt_path, + } + return return_d + + def __len__(self): + return len(self.paths) diff --git a/RealESRGANv030/realesrgan/data/realesrgan_paired_dataset.py b/RealESRGANv030/realesrgan/data/realesrgan_paired_dataset.py new file mode 100644 index 0000000000000000000000000000000000000000..815d98ca6fd65138442367b7939afa2b7b20aec5 --- /dev/null +++ b/RealESRGANv030/realesrgan/data/realesrgan_paired_dataset.py @@ -0,0 +1,116 @@ +import os +from basicsr.data.data_util import paired_paths_from_folder, paired_paths_from_lmdb +from basicsr.data.transforms import augment, paired_random_crop +from basicsr.utils import FileClient, imfrombytes, img2tensor +from basicsr.utils.registry import DATASET_REGISTRY +from torch.utils import data as data +from torchvision.transforms.functional import normalize + + +@DATASET_REGISTRY.register() +class RealESRGANPairedDataset(data.Dataset): + """Paired image dataset for image restoration. + + Read LQ (Low Quality, e.g. LR (Low Resolution), blurry, noisy, etc) and GT image pairs. + + There are three modes: + 1. 'lmdb': Use lmdb files. + If opt['io_backend'] == lmdb. + 2. 'meta_info': Use meta information file to generate paths. + If opt['io_backend'] != lmdb and opt['meta_info'] is not None. + 3. 'folder': Scan folders to generate paths. + The rest. + + Args: + opt (dict): Config for train datasets. It contains the following keys: + dataroot_gt (str): Data root path for gt. + dataroot_lq (str): Data root path for lq. + meta_info (str): Path for meta information file. + io_backend (dict): IO backend type and other kwarg. + filename_tmpl (str): Template for each filename. Note that the template excludes the file extension. + Default: '{}'. + gt_size (int): Cropped patched size for gt patches. + use_hflip (bool): Use horizontal flips. + use_rot (bool): Use rotation (use vertical flip and transposing h + and w for implementation). + + scale (bool): Scale, which will be added automatically. + phase (str): 'train' or 'val'. + """ + + def __init__(self, opt): + super(RealESRGANPairedDataset, self).__init__() + self.opt = opt + self.file_client = None + self.io_backend_opt = opt["io_backend"] + # mean and std for normalizing the input images + self.mean = opt["mean"] if "mean" in opt else None + self.std = opt["std"] if "std" in opt else None + + self.gt_folder, self.lq_folder = opt["dataroot_gt"], opt["dataroot_lq"] + self.filename_tmpl = opt["filename_tmpl"] if "filename_tmpl" in opt else "{}" + + # file client (lmdb io backend) + if self.io_backend_opt["type"] == "lmdb": + self.io_backend_opt["db_paths"] = [self.lq_folder, self.gt_folder] + self.io_backend_opt["client_keys"] = ["lq", "gt"] + self.paths = paired_paths_from_lmdb( + [self.lq_folder, self.gt_folder], ["lq", "gt"] + ) + elif "meta_info" in self.opt and self.opt["meta_info"] is not None: + # disk backend with meta_info + # Each line in the meta_info describes the relative path to an image + with open(self.opt["meta_info"]) as fin: + paths = [line.strip() for line in fin] + self.paths = [] + for path in paths: + gt_path, lq_path = path.split(", ") + gt_path = os.path.join(self.gt_folder, gt_path) + lq_path = os.path.join(self.lq_folder, lq_path) + self.paths.append(dict([("gt_path", gt_path), ("lq_path", lq_path)])) + else: + # disk backend + # it will scan the whole folder to get meta info + # it will be time-consuming for folders with too many files. It is recommended using an extra meta txt file + self.paths = paired_paths_from_folder( + [self.lq_folder, self.gt_folder], ["lq", "gt"], self.filename_tmpl + ) + + def __getitem__(self, index): + if self.file_client is None: + self.file_client = FileClient( + self.io_backend_opt.pop("type"), **self.io_backend_opt + ) + + scale = self.opt["scale"] + + # Load gt and lq images. Dimension order: HWC; channel order: BGR; + # image range: [0, 1], float32. + gt_path = self.paths[index]["gt_path"] + img_bytes = self.file_client.get(gt_path, "gt") + img_gt = imfrombytes(img_bytes, float32=True) + lq_path = self.paths[index]["lq_path"] + img_bytes = self.file_client.get(lq_path, "lq") + img_lq = imfrombytes(img_bytes, float32=True) + + # augmentation for training + if self.opt["phase"] == "train": + gt_size = self.opt["gt_size"] + # random crop + img_gt, img_lq = paired_random_crop(img_gt, img_lq, gt_size, scale, gt_path) + # flip, rotation + img_gt, img_lq = augment( + [img_gt, img_lq], self.opt["use_hflip"], self.opt["use_rot"] + ) + + # BGR to RGB, HWC to CHW, numpy to tensor + img_gt, img_lq = img2tensor([img_gt, img_lq], bgr2rgb=True, float32=True) + # normalize + if self.mean is not None or self.std is not None: + normalize(img_lq, self.mean, self.std, inplace=True) + normalize(img_gt, self.mean, self.std, inplace=True) + + return {"lq": img_lq, "gt": img_gt, "lq_path": lq_path, "gt_path": gt_path} + + def __len__(self): + return len(self.paths) diff --git a/RealESRGANv030/realesrgan/models/__init__.py b/RealESRGANv030/realesrgan/models/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..b9fad1eb307d042215e733255c162d956aa23703 --- /dev/null +++ b/RealESRGANv030/realesrgan/models/__init__.py @@ -0,0 +1,17 @@ +import importlib +from basicsr.utils import scandir +from os import path as osp + +# automatically scan and import model modules for registry +# scan all the files that end with '_model.py' under the model folder +model_folder = osp.dirname(osp.abspath(__file__)) +model_filenames = [ + osp.splitext(osp.basename(v))[0] + for v in scandir(model_folder) + if v.endswith("_model.py") +] +# import all the model modules +_model_modules = [ + importlib.import_module(f"realesrgan.models.{file_name}") + for file_name in model_filenames +] diff --git a/RealESRGANv030/realesrgan/models/realesrgan_model.py b/RealESRGANv030/realesrgan/models/realesrgan_model.py new file mode 100644 index 0000000000000000000000000000000000000000..e4cf1c29beb28abe524c3dad2c3416a4d9049e3c --- /dev/null +++ b/RealESRGANv030/realesrgan/models/realesrgan_model.py @@ -0,0 +1,308 @@ +import numpy as np +import random +import torch +from basicsr.data.degradations import ( + random_add_gaussian_noise_pt, + random_add_poisson_noise_pt, +) +from basicsr.data.transforms import paired_random_crop +from basicsr.models.srgan_model import SRGANModel +from basicsr.utils import DiffJPEG, USMSharp +from basicsr.utils.img_process_util import filter2D +from basicsr.utils.registry import MODEL_REGISTRY +from collections import OrderedDict +from torch.nn import functional as F + + +@MODEL_REGISTRY.register() +class RealESRGANModel(SRGANModel): + """RealESRGAN Model for Real-ESRGAN: Training Real-World Blind Super-Resolution with Pure Synthetic Data. + + It mainly performs: + 1. randomly synthesize LQ images in GPU tensors + 2. optimize the networks with GAN training. + """ + + def __init__(self, opt): + super(RealESRGANModel, self).__init__(opt) + self.jpeger = DiffJPEG( + differentiable=False + ).cuda() # simulate JPEG compression artifacts + self.usm_sharpener = USMSharp().cuda() # do usm sharpening + self.queue_size = opt.get("queue_size", 180) + + @torch.no_grad() + def _dequeue_and_enqueue(self): + """It is the training pair pool for increasing the diversity in a batch. + + Batch processing limits the diversity of synthetic degradations in a batch. For example, samples in a + batch could not have different resize scaling factors. Therefore, we employ this training pair pool + to increase the degradation diversity in a batch. + """ + # initialize + b, c, h, w = self.lq.size() + if not hasattr(self, "queue_lr"): + assert ( + self.queue_size % b == 0 + ), f"queue size {self.queue_size} should be divisible by batch size {b}" + self.queue_lr = torch.zeros(self.queue_size, c, h, w).cuda() + _, c, h, w = self.gt.size() + self.queue_gt = torch.zeros(self.queue_size, c, h, w).cuda() + self.queue_ptr = 0 + if self.queue_ptr == self.queue_size: # the pool is full + # do dequeue and enqueue + # shuffle + idx = torch.randperm(self.queue_size) + self.queue_lr = self.queue_lr[idx] + self.queue_gt = self.queue_gt[idx] + # get first b samples + lq_dequeue = self.queue_lr[0:b, :, :, :].clone() + gt_dequeue = self.queue_gt[0:b, :, :, :].clone() + # update the queue + self.queue_lr[0:b, :, :, :] = self.lq.clone() + self.queue_gt[0:b, :, :, :] = self.gt.clone() + + self.lq = lq_dequeue + self.gt = gt_dequeue + else: + # only do enqueue + self.queue_lr[ + self.queue_ptr : self.queue_ptr + b, :, :, : + ] = self.lq.clone() + self.queue_gt[ + self.queue_ptr : self.queue_ptr + b, :, :, : + ] = self.gt.clone() + self.queue_ptr = self.queue_ptr + b + + @torch.no_grad() + def feed_data(self, data): + """Accept data from dataloader, and then add two-order degradations to obtain LQ images.""" + if self.is_train and self.opt.get("high_order_degradation", True): + # training data synthesis + self.gt = data["gt"].to(self.device) + self.gt_usm = self.usm_sharpener(self.gt) + + self.kernel1 = data["kernel1"].to(self.device) + self.kernel2 = data["kernel2"].to(self.device) + self.sinc_kernel = data["sinc_kernel"].to(self.device) + + ori_h, ori_w = self.gt.size()[2:4] + + # ----------------------- The first degradation process ----------------------- # + # blur + out = filter2D(self.gt_usm, self.kernel1) + # random resize + updown_type = random.choices( + ["up", "down", "keep"], self.opt["resize_prob"] + )[0] + if updown_type == "up": + scale = np.random.uniform(1, self.opt["resize_range"][1]) + elif updown_type == "down": + scale = np.random.uniform(self.opt["resize_range"][0], 1) + else: + scale = 1 + mode = random.choice(["area", "bilinear", "bicubic"]) + out = F.interpolate(out, scale_factor=scale, mode=mode) + # add noise + gray_noise_prob = self.opt["gray_noise_prob"] + if np.random.uniform() < self.opt["gaussian_noise_prob"]: + out = random_add_gaussian_noise_pt( + out, + sigma_range=self.opt["noise_range"], + clip=True, + rounds=False, + gray_prob=gray_noise_prob, + ) + else: + out = random_add_poisson_noise_pt( + out, + scale_range=self.opt["poisson_scale_range"], + gray_prob=gray_noise_prob, + clip=True, + rounds=False, + ) + # JPEG compression + jpeg_p = out.new_zeros(out.size(0)).uniform_(*self.opt["jpeg_range"]) + out = torch.clamp( + out, 0, 1 + ) # clamp to [0, 1], otherwise JPEGer will result in unpleasant artifacts + out = self.jpeger(out, quality=jpeg_p) + + # ----------------------- The second degradation process ----------------------- # + # blur + if np.random.uniform() < self.opt["second_blur_prob"]: + out = filter2D(out, self.kernel2) + # random resize + updown_type = random.choices( + ["up", "down", "keep"], self.opt["resize_prob2"] + )[0] + if updown_type == "up": + scale = np.random.uniform(1, self.opt["resize_range2"][1]) + elif updown_type == "down": + scale = np.random.uniform(self.opt["resize_range2"][0], 1) + else: + scale = 1 + mode = random.choice(["area", "bilinear", "bicubic"]) + out = F.interpolate( + out, + size=( + int(ori_h / self.opt["scale"] * scale), + int(ori_w / self.opt["scale"] * scale), + ), + mode=mode, + ) + # add noise + gray_noise_prob = self.opt["gray_noise_prob2"] + if np.random.uniform() < self.opt["gaussian_noise_prob2"]: + out = random_add_gaussian_noise_pt( + out, + sigma_range=self.opt["noise_range2"], + clip=True, + rounds=False, + gray_prob=gray_noise_prob, + ) + else: + out = random_add_poisson_noise_pt( + out, + scale_range=self.opt["poisson_scale_range2"], + gray_prob=gray_noise_prob, + clip=True, + rounds=False, + ) + + # JPEG compression + the final sinc filter + # We also need to resize images to desired sizes. We group [resize back + sinc filter] together + # as one operation. + # We consider two orders: + # 1. [resize back + sinc filter] + JPEG compression + # 2. JPEG compression + [resize back + sinc filter] + # Empirically, we find other combinations (sinc + JPEG + Resize) will introduce twisted lines. + if np.random.uniform() < 0.5: + # resize back + the final sinc filter + mode = random.choice(["area", "bilinear", "bicubic"]) + out = F.interpolate( + out, + size=(ori_h // self.opt["scale"], ori_w // self.opt["scale"]), + mode=mode, + ) + out = filter2D(out, self.sinc_kernel) + # JPEG compression + jpeg_p = out.new_zeros(out.size(0)).uniform_(*self.opt["jpeg_range2"]) + out = torch.clamp(out, 0, 1) + out = self.jpeger(out, quality=jpeg_p) + else: + # JPEG compression + jpeg_p = out.new_zeros(out.size(0)).uniform_(*self.opt["jpeg_range2"]) + out = torch.clamp(out, 0, 1) + out = self.jpeger(out, quality=jpeg_p) + # resize back + the final sinc filter + mode = random.choice(["area", "bilinear", "bicubic"]) + out = F.interpolate( + out, + size=(ori_h // self.opt["scale"], ori_w // self.opt["scale"]), + mode=mode, + ) + out = filter2D(out, self.sinc_kernel) + + # clamp and round + self.lq = torch.clamp((out * 255.0).round(), 0, 255) / 255.0 + + # random crop + gt_size = self.opt["gt_size"] + (self.gt, self.gt_usm), self.lq = paired_random_crop( + [self.gt, self.gt_usm], self.lq, gt_size, self.opt["scale"] + ) + + # training pair pool + self._dequeue_and_enqueue() + # sharpen self.gt again, as we have changed the self.gt with self._dequeue_and_enqueue + self.gt_usm = self.usm_sharpener(self.gt) + self.lq = ( + self.lq.contiguous() + ) # for the warning: grad and param do not obey the gradient layout contract + else: + # for paired training or validation + self.lq = data["lq"].to(self.device) + if "gt" in data: + self.gt = data["gt"].to(self.device) + self.gt_usm = self.usm_sharpener(self.gt) + + def nondist_validation(self, dataloader, current_iter, tb_logger, save_img): + # do not use the synthetic process during validation + self.is_train = False + super(RealESRGANModel, self).nondist_validation( + dataloader, current_iter, tb_logger, save_img + ) + self.is_train = True + + def optimize_parameters(self, current_iter): + # usm sharpening + l1_gt = self.gt_usm + percep_gt = self.gt_usm + gan_gt = self.gt_usm + if self.opt["l1_gt_usm"] is False: + l1_gt = self.gt + if self.opt["percep_gt_usm"] is False: + percep_gt = self.gt + if self.opt["gan_gt_usm"] is False: + gan_gt = self.gt + + # optimize net_g + for p in self.net_d.parameters(): + p.requires_grad = False + + self.optimizer_g.zero_grad() + self.output = self.net_g(self.lq) + + l_g_total = 0 + loss_dict = OrderedDict() + if ( + current_iter % self.net_d_iters == 0 + and current_iter > self.net_d_init_iters + ): + # pixel loss + if self.cri_pix: + l_g_pix = self.cri_pix(self.output, l1_gt) + l_g_total += l_g_pix + loss_dict["l_g_pix"] = l_g_pix + # perceptual loss + if self.cri_perceptual: + l_g_percep, l_g_style = self.cri_perceptual(self.output, percep_gt) + if l_g_percep is not None: + l_g_total += l_g_percep + loss_dict["l_g_percep"] = l_g_percep + if l_g_style is not None: + l_g_total += l_g_style + loss_dict["l_g_style"] = l_g_style + # gan loss + fake_g_pred = self.net_d(self.output) + l_g_gan = self.cri_gan(fake_g_pred, True, is_disc=False) + l_g_total += l_g_gan + loss_dict["l_g_gan"] = l_g_gan + + l_g_total.backward() + self.optimizer_g.step() + + # optimize net_d + for p in self.net_d.parameters(): + p.requires_grad = True + + self.optimizer_d.zero_grad() + # real + real_d_pred = self.net_d(gan_gt) + l_d_real = self.cri_gan(real_d_pred, True, is_disc=True) + loss_dict["l_d_real"] = l_d_real + loss_dict["out_d_real"] = torch.mean(real_d_pred.detach()) + l_d_real.backward() + # fake + fake_d_pred = self.net_d(self.output.detach().clone()) # clone for pt1.9 + l_d_fake = self.cri_gan(fake_d_pred, False, is_disc=True) + loss_dict["l_d_fake"] = l_d_fake + loss_dict["out_d_fake"] = torch.mean(fake_d_pred.detach()) + l_d_fake.backward() + self.optimizer_d.step() + + if self.ema_decay > 0: + self.model_ema(decay=self.ema_decay) + + self.log_dict = self.reduce_loss_dict(loss_dict) diff --git a/RealESRGANv030/realesrgan/models/realesrnet_model.py b/RealESRGANv030/realesrgan/models/realesrnet_model.py new file mode 100644 index 0000000000000000000000000000000000000000..e55af653aa786adf36c1f7e0822752739376302b --- /dev/null +++ b/RealESRGANv030/realesrgan/models/realesrnet_model.py @@ -0,0 +1,236 @@ +import numpy as np +import random +import torch +from basicsr.data.degradations import ( + random_add_gaussian_noise_pt, + random_add_poisson_noise_pt, +) +from basicsr.data.transforms import paired_random_crop +from basicsr.models.sr_model import SRModel +from basicsr.utils import DiffJPEG, USMSharp +from basicsr.utils.img_process_util import filter2D +from basicsr.utils.registry import MODEL_REGISTRY +from torch.nn import functional as F + + +@MODEL_REGISTRY.register() +class RealESRNetModel(SRModel): + """RealESRNet Model for Real-ESRGAN: Training Real-World Blind Super-Resolution with Pure Synthetic Data. + + It is trained without GAN losses. + It mainly performs: + 1. randomly synthesize LQ images in GPU tensors + 2. optimize the networks with GAN training. + """ + + def __init__(self, opt): + super(RealESRNetModel, self).__init__(opt) + self.jpeger = DiffJPEG( + differentiable=False + ).cuda() # simulate JPEG compression artifacts + self.usm_sharpener = USMSharp().cuda() # do usm sharpening + self.queue_size = opt.get("queue_size", 180) + + @torch.no_grad() + def _dequeue_and_enqueue(self): + """It is the training pair pool for increasing the diversity in a batch. + + Batch processing limits the diversity of synthetic degradations in a batch. For example, samples in a + batch could not have different resize scaling factors. Therefore, we employ this training pair pool + to increase the degradation diversity in a batch. + """ + # initialize + b, c, h, w = self.lq.size() + if not hasattr(self, "queue_lr"): + assert ( + self.queue_size % b == 0 + ), f"queue size {self.queue_size} should be divisible by batch size {b}" + self.queue_lr = torch.zeros(self.queue_size, c, h, w).cuda() + _, c, h, w = self.gt.size() + self.queue_gt = torch.zeros(self.queue_size, c, h, w).cuda() + self.queue_ptr = 0 + if self.queue_ptr == self.queue_size: # the pool is full + # do dequeue and enqueue + # shuffle + idx = torch.randperm(self.queue_size) + self.queue_lr = self.queue_lr[idx] + self.queue_gt = self.queue_gt[idx] + # get first b samples + lq_dequeue = self.queue_lr[0:b, :, :, :].clone() + gt_dequeue = self.queue_gt[0:b, :, :, :].clone() + # update the queue + self.queue_lr[0:b, :, :, :] = self.lq.clone() + self.queue_gt[0:b, :, :, :] = self.gt.clone() + + self.lq = lq_dequeue + self.gt = gt_dequeue + else: + # only do enqueue + self.queue_lr[ + self.queue_ptr : self.queue_ptr + b, :, :, : + ] = self.lq.clone() + self.queue_gt[ + self.queue_ptr : self.queue_ptr + b, :, :, : + ] = self.gt.clone() + self.queue_ptr = self.queue_ptr + b + + @torch.no_grad() + def feed_data(self, data): + """Accept data from dataloader, and then add two-order degradations to obtain LQ images.""" + if self.is_train and self.opt.get("high_order_degradation", True): + # training data synthesis + self.gt = data["gt"].to(self.device) + # USM sharpen the GT images + if self.opt["gt_usm"] is True: + self.gt = self.usm_sharpener(self.gt) + + self.kernel1 = data["kernel1"].to(self.device) + self.kernel2 = data["kernel2"].to(self.device) + self.sinc_kernel = data["sinc_kernel"].to(self.device) + + ori_h, ori_w = self.gt.size()[2:4] + + # ----------------------- The first degradation process ----------------------- # + # blur + out = filter2D(self.gt, self.kernel1) + # random resize + updown_type = random.choices( + ["up", "down", "keep"], self.opt["resize_prob"] + )[0] + if updown_type == "up": + scale = np.random.uniform(1, self.opt["resize_range"][1]) + elif updown_type == "down": + scale = np.random.uniform(self.opt["resize_range"][0], 1) + else: + scale = 1 + mode = random.choice(["area", "bilinear", "bicubic"]) + out = F.interpolate(out, scale_factor=scale, mode=mode) + # add noise + gray_noise_prob = self.opt["gray_noise_prob"] + if np.random.uniform() < self.opt["gaussian_noise_prob"]: + out = random_add_gaussian_noise_pt( + out, + sigma_range=self.opt["noise_range"], + clip=True, + rounds=False, + gray_prob=gray_noise_prob, + ) + else: + out = random_add_poisson_noise_pt( + out, + scale_range=self.opt["poisson_scale_range"], + gray_prob=gray_noise_prob, + clip=True, + rounds=False, + ) + # JPEG compression + jpeg_p = out.new_zeros(out.size(0)).uniform_(*self.opt["jpeg_range"]) + out = torch.clamp( + out, 0, 1 + ) # clamp to [0, 1], otherwise JPEGer will result in unpleasant artifacts + out = self.jpeger(out, quality=jpeg_p) + + # ----------------------- The second degradation process ----------------------- # + # blur + if np.random.uniform() < self.opt["second_blur_prob"]: + out = filter2D(out, self.kernel2) + # random resize + updown_type = random.choices( + ["up", "down", "keep"], self.opt["resize_prob2"] + )[0] + if updown_type == "up": + scale = np.random.uniform(1, self.opt["resize_range2"][1]) + elif updown_type == "down": + scale = np.random.uniform(self.opt["resize_range2"][0], 1) + else: + scale = 1 + mode = random.choice(["area", "bilinear", "bicubic"]) + out = F.interpolate( + out, + size=( + int(ori_h / self.opt["scale"] * scale), + int(ori_w / self.opt["scale"] * scale), + ), + mode=mode, + ) + # add noise + gray_noise_prob = self.opt["gray_noise_prob2"] + if np.random.uniform() < self.opt["gaussian_noise_prob2"]: + out = random_add_gaussian_noise_pt( + out, + sigma_range=self.opt["noise_range2"], + clip=True, + rounds=False, + gray_prob=gray_noise_prob, + ) + else: + out = random_add_poisson_noise_pt( + out, + scale_range=self.opt["poisson_scale_range2"], + gray_prob=gray_noise_prob, + clip=True, + rounds=False, + ) + + # JPEG compression + the final sinc filter + # We also need to resize images to desired sizes. We group [resize back + sinc filter] together + # as one operation. + # We consider two orders: + # 1. [resize back + sinc filter] + JPEG compression + # 2. JPEG compression + [resize back + sinc filter] + # Empirically, we find other combinations (sinc + JPEG + Resize) will introduce twisted lines. + if np.random.uniform() < 0.5: + # resize back + the final sinc filter + mode = random.choice(["area", "bilinear", "bicubic"]) + out = F.interpolate( + out, + size=(ori_h // self.opt["scale"], ori_w // self.opt["scale"]), + mode=mode, + ) + out = filter2D(out, self.sinc_kernel) + # JPEG compression + jpeg_p = out.new_zeros(out.size(0)).uniform_(*self.opt["jpeg_range2"]) + out = torch.clamp(out, 0, 1) + out = self.jpeger(out, quality=jpeg_p) + else: + # JPEG compression + jpeg_p = out.new_zeros(out.size(0)).uniform_(*self.opt["jpeg_range2"]) + out = torch.clamp(out, 0, 1) + out = self.jpeger(out, quality=jpeg_p) + # resize back + the final sinc filter + mode = random.choice(["area", "bilinear", "bicubic"]) + out = F.interpolate( + out, + size=(ori_h // self.opt["scale"], ori_w // self.opt["scale"]), + mode=mode, + ) + out = filter2D(out, self.sinc_kernel) + + # clamp and round + self.lq = torch.clamp((out * 255.0).round(), 0, 255) / 255.0 + + # random crop + gt_size = self.opt["gt_size"] + self.gt, self.lq = paired_random_crop( + self.gt, self.lq, gt_size, self.opt["scale"] + ) + + # training pair pool + self._dequeue_and_enqueue() + self.lq = ( + self.lq.contiguous() + ) # for the warning: grad and param do not obey the gradient layout contract + else: + # for paired training or validation + self.lq = data["lq"].to(self.device) + if "gt" in data: + self.gt = data["gt"].to(self.device) + self.gt_usm = self.usm_sharpener(self.gt) + + def nondist_validation(self, dataloader, current_iter, tb_logger, save_img): + # do not use the synthetic process during validation + self.is_train = False + super(RealESRNetModel, self).nondist_validation( + dataloader, current_iter, tb_logger, save_img + ) + self.is_train = True diff --git a/RealESRGANv030/realesrgan/train.py b/RealESRGANv030/realesrgan/train.py new file mode 100644 index 0000000000000000000000000000000000000000..5097ff26a590abd8fb47b4875c8ea71db79f7a02 --- /dev/null +++ b/RealESRGANv030/realesrgan/train.py @@ -0,0 +1,11 @@ +# flake8: noqa +import os.path as osp +from basicsr.train import train_pipeline + +import realesrgan.archs +import realesrgan.data +import realesrgan.models + +if __name__ == "__main__": + root_path = osp.abspath(osp.join(__file__, osp.pardir, osp.pardir)) + train_pipeline(root_path) diff --git a/RealESRGANv030/realesrgan/utils.py b/RealESRGANv030/realesrgan/utils.py new file mode 100644 index 0000000000000000000000000000000000000000..97258f1706cc76773011e24a11bf417ea76ae112 --- /dev/null +++ b/RealESRGANv030/realesrgan/utils.py @@ -0,0 +1,357 @@ +import cv2 +import math +import numpy as np +import os +import queue +import threading +import torch +from basicsr.utils.download_util import load_file_from_url +from torch.nn import functional as F + +ROOT_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__))) + + +class RealESRGANer: + """A helper class for upsampling images with RealESRGAN. + + Args: + scale (int): Upsampling scale factor used in the networks. It is usually 2 or 4. + model_path (str): The path to the pretrained model. It can be urls (will first download it automatically). + model (nn.Module): The defined network. Default: None. + tile (int): As too large images result in the out of GPU memory issue, so this tile option will first crop + input images into tiles, and then process each of them. Finally, they will be merged into one image. + 0 denotes for do not use tile. Default: 0. + tile_pad (int): The pad size for each tile, to remove border artifacts. Default: 10. + pre_pad (int): Pad the input images to avoid border artifacts. Default: 10. + half (float): Whether to use half precision during inference. Default: False. + """ + + def __init__( + self, + scale, + model_path, + dni_weight=None, + model=None, + tile=0, + tile_pad=10, + pre_pad=10, + half=False, + device=None, + gpu_id=None, + ): + self.scale = scale + self.tile_size = tile + self.tile_pad = tile_pad + self.pre_pad = pre_pad + self.mod_scale = None + self.half = half + + # initialize model + if gpu_id: + self.device = ( + torch.device(f"cuda:{gpu_id}" if torch.cuda.is_available() else "cpu") + if device is None + else device + ) + else: + self.device = ( + torch.device("cuda" if torch.cuda.is_available() else "cpu") + if device is None + else device + ) + + if isinstance(model_path, list): + # dni + assert len(model_path) == len( + dni_weight + ), "model_path and dni_weight should have the save length." + loadnet = self.dni(model_path[0], model_path[1], dni_weight) + else: + # if the model_path starts with https, it will first download models to the folder: weights + if model_path.startswith("https://"): + model_path = load_file_from_url( + url=model_path, + model_dir=os.path.join(ROOT_DIR, "weights"), + progress=True, + file_name=None, + ) + loadnet = torch.load(model_path, map_location=torch.device("cpu")) + + # prefer to use params_ema + if "params_ema" in loadnet: + keyname = "params_ema" + else: + keyname = "params" + model.load_state_dict(loadnet[keyname], strict=True) + + model.eval() + self.model = model.to(self.device) + if self.half: + self.model = self.model.half() + + def dni(self, net_a, net_b, dni_weight, key="params", loc="cpu"): + """Deep network interpolation. + + ``Paper: Deep Network Interpolation for Continuous Imagery Effect Transition`` + """ + net_a = torch.load(net_a, map_location=torch.device(loc)) + net_b = torch.load(net_b, map_location=torch.device(loc)) + for k, v_a in net_a[key].items(): + net_a[key][k] = dni_weight[0] * v_a + dni_weight[1] * net_b[key][k] + return net_a + + def pre_process(self, img): + """Pre-process, such as pre-pad and mod pad, so that the images can be divisible""" + img = torch.from_numpy(np.transpose(img, (2, 0, 1))).float() + self.img = img.unsqueeze(0).to(self.device) + if self.half: + self.img = self.img.half() + + # pre_pad + if self.pre_pad != 0: + self.img = F.pad(self.img, (0, self.pre_pad, 0, self.pre_pad), "reflect") + # mod pad for divisible borders + if self.scale == 2: + self.mod_scale = 2 + elif self.scale == 1: + self.mod_scale = 4 + if self.mod_scale is not None: + self.mod_pad_h, self.mod_pad_w = 0, 0 + _, _, h, w = self.img.size() + if h % self.mod_scale != 0: + self.mod_pad_h = self.mod_scale - h % self.mod_scale + if w % self.mod_scale != 0: + self.mod_pad_w = self.mod_scale - w % self.mod_scale + self.img = F.pad( + self.img, (0, self.mod_pad_w, 0, self.mod_pad_h), "reflect" + ) + + def process(self): + # model inference + self.output = self.model(self.img) + + def tile_process(self): + """It will first crop input images to tiles, and then process each tile. + Finally, all the processed tiles are merged into one images. + + Modified from: https://github.com/ata4/esrgan-launcher + """ + batch, channel, height, width = self.img.shape + output_height = height * self.scale + output_width = width * self.scale + output_shape = (batch, channel, output_height, output_width) + + # start with black image + self.output = self.img.new_zeros(output_shape) + tiles_x = math.ceil(width / self.tile_size) + tiles_y = math.ceil(height / self.tile_size) + + # loop over all tiles + for y in range(tiles_y): + for x in range(tiles_x): + # extract tile from input image + ofs_x = x * self.tile_size + ofs_y = y * self.tile_size + # input tile area on total image + input_start_x = ofs_x + input_end_x = min(ofs_x + self.tile_size, width) + input_start_y = ofs_y + input_end_y = min(ofs_y + self.tile_size, height) + + # input tile area on total image with padding + input_start_x_pad = max(input_start_x - self.tile_pad, 0) + input_end_x_pad = min(input_end_x + self.tile_pad, width) + input_start_y_pad = max(input_start_y - self.tile_pad, 0) + input_end_y_pad = min(input_end_y + self.tile_pad, height) + + # input tile dimensions + input_tile_width = input_end_x - input_start_x + input_tile_height = input_end_y - input_start_y + tile_idx = y * tiles_x + x + 1 + input_tile = self.img[ + :, + :, + input_start_y_pad:input_end_y_pad, + input_start_x_pad:input_end_x_pad, + ] + + # upscale tile + try: + with torch.no_grad(): + output_tile = self.model(input_tile) + except RuntimeError as error: + print("Error", error) + print(f"\tTile {tile_idx}/{tiles_x * tiles_y}") + + # output tile area on total image + output_start_x = input_start_x * self.scale + output_end_x = input_end_x * self.scale + output_start_y = input_start_y * self.scale + output_end_y = input_end_y * self.scale + + # output tile area without padding + output_start_x_tile = (input_start_x - input_start_x_pad) * self.scale + output_end_x_tile = output_start_x_tile + input_tile_width * self.scale + output_start_y_tile = (input_start_y - input_start_y_pad) * self.scale + output_end_y_tile = output_start_y_tile + input_tile_height * self.scale + + # put tile into output image + self.output[ + :, :, output_start_y:output_end_y, output_start_x:output_end_x + ] = output_tile[ + :, + :, + output_start_y_tile:output_end_y_tile, + output_start_x_tile:output_end_x_tile, + ] + + def post_process(self): + # remove extra pad + if self.mod_scale is not None: + _, _, h, w = self.output.size() + self.output = self.output[ + :, + :, + 0 : h - self.mod_pad_h * self.scale, + 0 : w - self.mod_pad_w * self.scale, + ] + # remove prepad + if self.pre_pad != 0: + _, _, h, w = self.output.size() + self.output = self.output[ + :, + :, + 0 : h - self.pre_pad * self.scale, + 0 : w - self.pre_pad * self.scale, + ] + return self.output + + @torch.no_grad() + def enhance(self, img, outscale=None, alpha_upsampler="realesrgan"): + h_input, w_input = img.shape[0:2] + # img: numpy + img = img.astype(np.float32) + if np.max(img) > 256: # 16-bit image + max_range = 65535 + print("\tInput is a 16-bit image") + else: + max_range = 255 + img = img / max_range + if len(img.shape) == 2: # gray image + img_mode = "L" + img = cv2.cvtColor(img, cv2.COLOR_GRAY2RGB) + elif img.shape[2] == 4: # RGBA image with alpha channel + img_mode = "RGBA" + alpha = img[:, :, 3] + img = img[:, :, 0:3] + img = cv2.cvtColor(img, cv2.COLOR_BGR2RGB) + if alpha_upsampler == "realesrgan": + alpha = cv2.cvtColor(alpha, cv2.COLOR_GRAY2RGB) + else: + img_mode = "RGB" + img = cv2.cvtColor(img, cv2.COLOR_BGR2RGB) + + # ------------------- process image (without the alpha channel) ------------------- # + self.pre_process(img) + if self.tile_size > 0: + self.tile_process() + else: + self.process() + output_img = self.post_process() + output_img = output_img.data.squeeze().float().cpu().clamp_(0, 1).numpy() + output_img = np.transpose(output_img[[2, 1, 0], :, :], (1, 2, 0)) + if img_mode == "L": + output_img = cv2.cvtColor(output_img, cv2.COLOR_BGR2GRAY) + + # ------------------- process the alpha channel if necessary ------------------- # + if img_mode == "RGBA": + if alpha_upsampler == "realesrgan": + self.pre_process(alpha) + if self.tile_size > 0: + self.tile_process() + else: + self.process() + output_alpha = self.post_process() + output_alpha = ( + output_alpha.data.squeeze().float().cpu().clamp_(0, 1).numpy() + ) + output_alpha = np.transpose(output_alpha[[2, 1, 0], :, :], (1, 2, 0)) + output_alpha = cv2.cvtColor(output_alpha, cv2.COLOR_BGR2GRAY) + else: # use the cv2 resize for alpha channel + h, w = alpha.shape[0:2] + output_alpha = cv2.resize( + alpha, + (w * self.scale, h * self.scale), + interpolation=cv2.INTER_LINEAR, + ) + + # merge the alpha channel + output_img = cv2.cvtColor(output_img, cv2.COLOR_BGR2BGRA) + output_img[:, :, 3] = output_alpha + + # ------------------------------ return ------------------------------ # + if max_range == 65535: # 16-bit image + output = (output_img * 65535.0).round().astype(np.uint16) + else: + output = (output_img * 255.0).round().astype(np.uint8) + + if outscale is not None and outscale != float(self.scale): + output = cv2.resize( + output, + ( + int(w_input * outscale), + int(h_input * outscale), + ), + interpolation=cv2.INTER_LANCZOS4, + ) + + return output, img_mode + + +class PrefetchReader(threading.Thread): + """Prefetch images. + + Args: + img_list (list[str]): A image list of image paths to be read. + num_prefetch_queue (int): Number of prefetch queue. + """ + + def __init__(self, img_list, num_prefetch_queue): + super().__init__() + self.que = queue.Queue(num_prefetch_queue) + self.img_list = img_list + + def run(self): + for img_path in self.img_list: + img = cv2.imread(img_path, cv2.IMREAD_UNCHANGED) + self.que.put(img) + + self.que.put(None) + + def __next__(self): + next_item = self.que.get() + if next_item is None: + raise StopIteration + return next_item + + def __iter__(self): + return self + + +class IOConsumer(threading.Thread): + def __init__(self, opt, que, qid): + super().__init__() + self._queue = que + self.qid = qid + self.opt = opt + + def run(self): + while True: + msg = self._queue.get() + if isinstance(msg, str) and msg == "quit": + break + + output = msg["output"] + save_path = msg["save_path"] + cv2.imwrite(save_path, output) + print(f"IO worker {self.qid} is done.") diff --git a/RealESRGANv030/requirements.txt b/RealESRGANv030/requirements.txt new file mode 100644 index 0000000000000000000000000000000000000000..0c8f3f0e75ea0174a4055bdce8255c541187e4b1 --- /dev/null +++ b/RealESRGANv030/requirements.txt @@ -0,0 +1,9 @@ +basicsr>=1.4.2 +facexlib>=0.2.5 +gfpgan>=1.3.5 +numpy +opencv-python +Pillow +torch>=1.7 +torchvision +tqdm diff --git a/RealESRGANv030/scripts/extract_subimages.py b/RealESRGANv030/scripts/extract_subimages.py new file mode 100644 index 0000000000000000000000000000000000000000..50a819d6148b53ee0482f4f6133a41b9620c0b0a --- /dev/null +++ b/RealESRGANv030/scripts/extract_subimages.py @@ -0,0 +1,148 @@ +import argparse +import cv2 +import numpy as np +import os +import sys +from basicsr.utils import scandir +from multiprocessing import Pool +from os import path as osp +from tqdm import tqdm + + +def main(args): + """A multi-thread tool to crop large images to sub-images for faster IO. + + opt (dict): Configuration dict. It contains: + n_thread (int): Thread number. + compression_level (int): CV_IMWRITE_PNG_COMPRESSION from 0 to 9. A higher value means a smaller size + and longer compression time. Use 0 for faster CPU decompression. Default: 3, same in cv2. + input_folder (str): Path to the input folder. + save_folder (str): Path to save folder. + crop_size (int): Crop size. + step (int): Step for overlapped sliding window. + thresh_size (int): Threshold size. Patches whose size is lower than thresh_size will be dropped. + + Usage: + For each folder, run this script. + Typically, there are GT folder and LQ folder to be processed for DIV2K dataset. + After process, each sub_folder should have the same number of subimages. + Remember to modify opt configurations according to your settings. + """ + + opt = {} + opt["n_thread"] = args.n_thread + opt["compression_level"] = args.compression_level + opt["input_folder"] = args.input + opt["save_folder"] = args.output + opt["crop_size"] = args.crop_size + opt["step"] = args.step + opt["thresh_size"] = args.thresh_size + extract_subimages(opt) + + +def extract_subimages(opt): + """Crop images to subimages. + + Args: + opt (dict): Configuration dict. It contains: + input_folder (str): Path to the input folder. + save_folder (str): Path to save folder. + n_thread (int): Thread number. + """ + input_folder = opt["input_folder"] + save_folder = opt["save_folder"] + if not osp.exists(save_folder): + os.makedirs(save_folder) + print(f"mkdir {save_folder} ...") + else: + print(f"Folder {save_folder} already exists. Exit.") + sys.exit(1) + + # scan all images + img_list = list(scandir(input_folder, full_path=True)) + + pbar = tqdm(total=len(img_list), unit="image", desc="Extract") + pool = Pool(opt["n_thread"]) + for path in img_list: + pool.apply_async(worker, args=(path, opt), callback=lambda arg: pbar.update(1)) + pool.close() + pool.join() + pbar.close() + print("All processes done.") + + +def worker(path, opt): + """Worker for each process. + + Args: + path (str): Image path. + opt (dict): Configuration dict. It contains: + crop_size (int): Crop size. + step (int): Step for overlapped sliding window. + thresh_size (int): Threshold size. Patches whose size is lower than thresh_size will be dropped. + save_folder (str): Path to save folder. + compression_level (int): for cv2.IMWRITE_PNG_COMPRESSION. + + Returns: + process_info (str): Process information displayed in progress bar. + """ + crop_size = opt["crop_size"] + step = opt["step"] + thresh_size = opt["thresh_size"] + img_name, extension = osp.splitext(osp.basename(path)) + + # remove the x2, x3, x4 and x8 in the filename for DIV2K + img_name = ( + img_name.replace("x2", "").replace("x3", "").replace("x4", "").replace("x8", "") + ) + + img = cv2.imread(path, cv2.IMREAD_UNCHANGED) + + h, w = img.shape[0:2] + h_space = np.arange(0, h - crop_size + 1, step) + if h - (h_space[-1] + crop_size) > thresh_size: + h_space = np.append(h_space, h - crop_size) + w_space = np.arange(0, w - crop_size + 1, step) + if w - (w_space[-1] + crop_size) > thresh_size: + w_space = np.append(w_space, w - crop_size) + + index = 0 + for x in h_space: + for y in w_space: + index += 1 + cropped_img = img[x : x + crop_size, y : y + crop_size, ...] + cropped_img = np.ascontiguousarray(cropped_img) + cv2.imwrite( + osp.join(opt["save_folder"], f"{img_name}_s{index:03d}{extension}"), + cropped_img, + [cv2.IMWRITE_PNG_COMPRESSION, opt["compression_level"]], + ) + process_info = f"Processing {img_name} ..." + return process_info + + +if __name__ == "__main__": + parser = argparse.ArgumentParser() + parser.add_argument( + "--input", type=str, default="datasets/DF2K/DF2K_HR", help="Input folder" + ) + parser.add_argument( + "--output", type=str, default="datasets/DF2K/DF2K_HR_sub", help="Output folder" + ) + parser.add_argument("--crop_size", type=int, default=480, help="Crop size") + parser.add_argument( + "--step", type=int, default=240, help="Step for overlapped sliding window" + ) + parser.add_argument( + "--thresh_size", + type=int, + default=0, + help="Threshold size. Patches whose size is lower than thresh_size will be dropped.", + ) + parser.add_argument("--n_thread", type=int, default=20, help="Thread number.") + parser.add_argument( + "--compression_level", type=int, default=3, help="Compression level" + ) + args = parser.parse_args() + + main(args) diff --git a/RealESRGANv030/scripts/generate_meta_info.py b/RealESRGANv030/scripts/generate_meta_info.py new file mode 100644 index 0000000000000000000000000000000000000000..081cd085b917b114a97673d3ee900bf578104e28 --- /dev/null +++ b/RealESRGANv030/scripts/generate_meta_info.py @@ -0,0 +1,65 @@ +import argparse +import cv2 +import glob +import os + + +def main(args): + txt_file = open(args.meta_info, "w") + for folder, root in zip(args.input, args.root): + img_paths = sorted(glob.glob(os.path.join(folder, "*"))) + for img_path in img_paths: + status = True + if args.check: + # read the image once for check, as some images may have errors + try: + img = cv2.imread(img_path) + except (IOError, OSError) as error: + print(f"Read {img_path} error: {error}") + status = False + if img is None: + status = False + print(f"Img is None: {img_path}") + if status: + # get the relative path + img_name = os.path.relpath(img_path, root) + print(img_name) + txt_file.write(f"{img_name}\n") + + +if __name__ == "__main__": + """Generate meta info (txt file) for only Ground-Truth images. + + It can also generate meta info from several folders into one txt file. + """ + parser = argparse.ArgumentParser() + parser.add_argument( + "--input", + nargs="+", + default=["datasets/DF2K/DF2K_HR", "datasets/DF2K/DF2K_multiscale"], + help="Input folder, can be a list", + ) + parser.add_argument( + "--root", + nargs="+", + default=["datasets/DF2K", "datasets/DF2K"], + help="Folder root, should have the length as input folders", + ) + parser.add_argument( + "--meta_info", + type=str, + default="datasets/DF2K/meta_info/meta_info_DF2Kmultiscale.txt", + help="txt path for meta info", + ) + parser.add_argument( + "--check", action="store_true", help="Read image to check whether it is ok" + ) + args = parser.parse_args() + + assert len(args.input) == len(args.root), ( + "Input folder and folder root should have the same length, but got " + f"{len(args.input)} and {len(args.root)}." + ) + os.makedirs(os.path.dirname(args.meta_info), exist_ok=True) + + main(args) diff --git a/RealESRGANv030/scripts/generate_meta_info_pairdata.py b/RealESRGANv030/scripts/generate_meta_info_pairdata.py new file mode 100644 index 0000000000000000000000000000000000000000..58c4c1f07566a95622d6e350b0a552496e3a179e --- /dev/null +++ b/RealESRGANv030/scripts/generate_meta_info_pairdata.py @@ -0,0 +1,61 @@ +import argparse +import glob +import os + + +def main(args): + txt_file = open(args.meta_info, "w") + # sca images + img_paths_gt = sorted(glob.glob(os.path.join(args.input[0], "*"))) + img_paths_lq = sorted(glob.glob(os.path.join(args.input[1], "*"))) + + assert len(img_paths_gt) == len(img_paths_lq), ( + "GT folder and LQ folder should have the same length, but got " + f"{len(img_paths_gt)} and {len(img_paths_lq)}." + ) + + for img_path_gt, img_path_lq in zip(img_paths_gt, img_paths_lq): + # get the relative paths + img_name_gt = os.path.relpath(img_path_gt, args.root[0]) + img_name_lq = os.path.relpath(img_path_lq, args.root[1]) + print(f"{img_name_gt}, {img_name_lq}") + txt_file.write(f"{img_name_gt}, {img_name_lq}\n") + + +if __name__ == "__main__": + """This script is used to generate meta info (txt file) for paired images.""" + parser = argparse.ArgumentParser() + parser.add_argument( + "--input", + nargs="+", + default=[ + "datasets/DF2K/DIV2K_train_HR_sub", + "datasets/DF2K/DIV2K_train_LR_bicubic_X4_sub", + ], + help="Input folder, should be [gt_folder, lq_folder]", + ) + parser.add_argument( + "--root", nargs="+", default=[None, None], help="Folder root, will use the " + ) + parser.add_argument( + "--meta_info", + type=str, + default="datasets/DF2K/meta_info/meta_info_DIV2K_sub_pair.txt", + help="txt path for meta info", + ) + args = parser.parse_args() + + assert ( + len(args.input) == 2 + ), "Input folder should have two elements: gt folder and lq folder" + assert ( + len(args.root) == 2 + ), "Root path should have two elements: root for gt folder and lq folder" + os.makedirs(os.path.dirname(args.meta_info), exist_ok=True) + for i in range(2): + if args.input[i].endswith("/"): + args.input[i] = args.input[i][:-1] + if args.root[i] is None: + args.root[i] = os.path.dirname(args.input[i]) + + main(args) diff --git a/RealESRGANv030/scripts/generate_multiscale_DF2K.py b/RealESRGANv030/scripts/generate_multiscale_DF2K.py new file mode 100644 index 0000000000000000000000000000000000000000..7ae6484e5c7a325bc55fdfb490ce4acd394f721a --- /dev/null +++ b/RealESRGANv030/scripts/generate_multiscale_DF2K.py @@ -0,0 +1,57 @@ +import argparse +import glob +import os +from PIL import Image + + +def main(args): + # For DF2K, we consider the following three scales, + # and the smallest image whose shortest edge is 400 + scale_list = [0.75, 0.5, 1 / 3] + shortest_edge = 400 + + path_list = sorted(glob.glob(os.path.join(args.input, "*"))) + for path in path_list: + print(path) + basename = os.path.splitext(os.path.basename(path))[0] + + img = Image.open(path) + width, height = img.size + for idx, scale in enumerate(scale_list): + print(f"\t{scale:.2f}") + rlt = img.resize( + (int(width * scale), int(height * scale)), resample=Image.LANCZOS + ) + rlt.save(os.path.join(args.output, f"{basename}T{idx}.png")) + + # save the smallest image which the shortest edge is 400 + if width < height: + ratio = height / width + width = shortest_edge + height = int(width * ratio) + else: + ratio = width / height + height = shortest_edge + width = int(height * ratio) + rlt = img.resize((int(width), int(height)), resample=Image.LANCZOS) + rlt.save(os.path.join(args.output, f"{basename}T{idx+1}.png")) + + +if __name__ == "__main__": + """Generate multi-scale versions for GT images with LANCZOS resampling. + It is now used for DF2K dataset (DIV2K + Flickr 2K) + """ + parser = argparse.ArgumentParser() + parser.add_argument( + "--input", type=str, default="datasets/DF2K/DF2K_HR", help="Input folder" + ) + parser.add_argument( + "--output", + type=str, + default="datasets/DF2K/DF2K_multiscale", + help="Output folder", + ) + args = parser.parse_args() + + os.makedirs(args.output, exist_ok=True) + main(args) diff --git a/RealESRGANv030/scripts/pytorch2onnx.py b/RealESRGANv030/scripts/pytorch2onnx.py new file mode 100644 index 0000000000000000000000000000000000000000..15bbabb8b56065a1e520c2ce31d09dbf8e324110 --- /dev/null +++ b/RealESRGANv030/scripts/pytorch2onnx.py @@ -0,0 +1,48 @@ +import argparse +import torch +import torch.onnx +from basicsr.archs.rrdbnet_arch import RRDBNet + + +def main(args): + # An instance of the model + model = RRDBNet( + num_in_ch=3, num_out_ch=3, num_feat=64, num_block=23, num_grow_ch=32, scale=4 + ) + if args.params: + keyname = "params" + else: + keyname = "params_ema" + model.load_state_dict(torch.load(args.input)[keyname]) + # set the train mode to false since we will only run the forward pass. + model.train(False) + model.cpu().eval() + + # An example input + x = torch.rand(1, 3, 64, 64) + # Export the model + with torch.no_grad(): + torch_out = torch.onnx._export( + model, x, args.output, opset_version=11, export_params=True + ) + print(torch_out.shape) + + +if __name__ == "__main__": + """Convert pytorch model to onnx models""" + parser = argparse.ArgumentParser() + parser.add_argument( + "--input", + type=str, + default="experiments/pretrained_models/RealESRGAN_x4plus.pth", + help="Input model path", + ) + parser.add_argument( + "--output", type=str, default="realesrgan-x4.onnx", help="Output onnx path" + ) + parser.add_argument( + "--params", action="store_false", help="Use params instead of params_ema" + ) + args = parser.parse_args() + + main(args) diff --git a/RealESRGANv030/setup.cfg b/RealESRGANv030/setup.cfg new file mode 100644 index 0000000000000000000000000000000000000000..9cecd96943e729db110b1960295d9d4bf76c1754 --- /dev/null +++ b/RealESRGANv030/setup.cfg @@ -0,0 +1,33 @@ +[flake8] +ignore = + # line break before binary operator (W503) + W503, + # line break after binary operator (W504) + W504, +max-line-length=120 + +[yapf] +based_on_style = pep8 +column_limit = 120 +blank_line_before_nested_class_or_def = true +split_before_expression_after_opening_paren = true + +[isort] +line_length = 120 +multi_line_output = 0 +known_standard_library = pkg_resources,setuptools +known_first_party = realesrgan +known_third_party = PIL,basicsr,cv2,numpy,pytest,torch,torchvision,tqdm,yaml +no_lines_before = STDLIB,LOCALFOLDER +default_section = THIRDPARTY + +[codespell] +skip = .git,./docs/build +count = +quiet-level = 3 + +[aliases] +test=pytest + +[tool:pytest] +addopts=tests/ diff --git a/RealESRGANv030/setup.py b/RealESRGANv030/setup.py new file mode 100644 index 0000000000000000000000000000000000000000..32a4c9c9b72a15b1a4e1ad0cc83308fb9f465426 --- /dev/null +++ b/RealESRGANv030/setup.py @@ -0,0 +1,118 @@ +#!/usr/bin/env python + +from setuptools import find_packages, setup + +import os +import subprocess +import time + +version_file = "realesrgan/version.py" + + +def readme(): + with open("README.md", encoding="utf-8") as f: + content = f.read() + return content + + +def get_git_hash(): + def _minimal_ext_cmd(cmd): + # construct minimal environment + env = {} + for k in ["SYSTEMROOT", "PATH", "HOME"]: + v = os.environ.get(k) + if v is not None: + env[k] = v + # LANGUAGE is used on win32 + env["LANGUAGE"] = "C" + env["LANG"] = "C" + env["LC_ALL"] = "C" + out = subprocess.Popen(cmd, stdout=subprocess.PIPE, env=env).communicate()[0] + return out + + try: + out = _minimal_ext_cmd(["git", "rev-parse", "HEAD"]) + sha = out.strip().decode("ascii") + except OSError: + sha = "unknown" + + return sha + + +def get_hash(): + if os.path.exists(".git"): + sha = get_git_hash()[:7] + else: + sha = "unknown" + + return sha + + +def write_version_py(): + content = """# GENERATED VERSION FILE +# TIME: {} +__version__ = '{}' +__gitsha__ = '{}' +version_info = ({}) +""" + sha = get_hash() + with open("VERSION", "r") as f: + SHORT_VERSION = f.read().strip() + VERSION_INFO = ", ".join( + [x if x.isdigit() else f'"{x}"' for x in SHORT_VERSION.split(".")] + ) + + version_file_str = content.format(time.asctime(), SHORT_VERSION, sha, VERSION_INFO) + with open(version_file, "w") as f: + f.write(version_file_str) + + +def get_version(): + with open(version_file, "r") as f: + exec(compile(f.read(), version_file, "exec")) + return locals()["__version__"] + + +def get_requirements(filename="requirements.txt"): + here = os.path.dirname(os.path.realpath(__file__)) + with open(os.path.join(here, filename), "r") as f: + requires = [line.replace("\n", "") for line in f.readlines()] + return requires + + +if __name__ == "__main__": + write_version_py() + setup( + name="realesrgan", + version=get_version(), + description="Real-ESRGAN aims at developing Practical Algorithms for General Image Restoration", + long_description=readme(), + long_description_content_type="text/markdown", + author="Xintao Wang", + author_email="xintao.wang@outlook.com", + keywords="computer vision, pytorch, image restoration, super-resolution, esrgan, real-esrgan", + url="https://github.com/xinntao/Real-ESRGAN", + include_package_data=True, + packages=find_packages( + exclude=( + "options", + "datasets", + "experiments", + "results", + "tb_logger", + "wandb", + ) + ), + classifiers=[ + "Development Status :: 4 - Beta", + "License :: OSI Approved :: Apache Software License", + "Operating System :: OS Independent", + "Programming Language :: Python :: 3", + "Programming Language :: Python :: 3.7", + "Programming Language :: Python :: 3.8", + ], + license="BSD-3-Clause License", + setup_requires=["cython", "numpy"], + install_requires=get_requirements(), + zip_safe=False, + ) diff --git a/SuperResolutionAnimeDiffusion.zip b/SuperResolutionAnimeDiffusion.zip new file mode 100644 index 0000000000000000000000000000000000000000..c03f1b483cbe045b1f5b75730fe25a4f8ad308db --- /dev/null +++ b/SuperResolutionAnimeDiffusion.zip @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:ef0a17ab5723e783a679cab83a05411ab09bb04886a629a5181bb18df0175c76 +size 256633269 diff --git a/Waifu2x/.gitattributes b/Waifu2x/.gitattributes new file mode 100644 index 0000000000000000000000000000000000000000..c561131bf81410ed860f45c22def02477a6ea405 --- /dev/null +++ b/Waifu2x/.gitattributes @@ -0,0 +1 @@ +Readme_imgs/* linguist-documentation diff --git a/Waifu2x/.gitignore b/Waifu2x/.gitignore new file mode 100644 index 0000000000000000000000000000000000000000..73a4863b7daef8db1648ceeac2c23e83b048ff2b --- /dev/null +++ b/Waifu2x/.gitignore @@ -0,0 +1,4 @@ + +*.xml +*.iml +*.pyc diff --git a/Waifu2x/Common.py b/Waifu2x/Common.py new file mode 100644 index 0000000000000000000000000000000000000000..6d7f1981aad000b9e3016e87f5c34878577447a5 --- /dev/null +++ b/Waifu2x/Common.py @@ -0,0 +1,255 @@ +from contextlib import contextmanager +from math import sqrt, log + +import torch +import torch.nn as nn + + +# import warnings +# warnings.simplefilter('ignore') + + +class BaseModule(nn.Module): + def __init__(self): + self.act_fn = None + super(BaseModule, self).__init__() + + def selu_init_params(self): + for m in self.modules(): + if isinstance(m, nn.Conv2d) and m.weight.requires_grad: + m.weight.data.normal_(0.0, 1.0 / sqrt(m.weight.numel())) + if m.bias is not None: + m.bias.data.fill_(0) + elif isinstance(m, nn.BatchNorm2d) and m.weight.requires_grad: + m.weight.data.fill_(1) + m.bias.data.zero_() + + elif isinstance(m, nn.Linear) and m.weight.requires_grad: + m.weight.data.normal_(0, 1.0 / sqrt(m.weight.numel())) + m.bias.data.zero_() + + def initialize_weights_xavier_uniform(self): + for m in self.modules(): + if isinstance(m, nn.Conv2d) and m.weight.requires_grad: + # nn.init.kaiming_normal_(m.weight, mode='fan_out', nonlinearity='leaky_relu') + nn.init.xavier_uniform_(m.weight) + if m.bias is not None: + m.bias.data.zero_() + elif isinstance(m, nn.BatchNorm2d) and m.weight.requires_grad: + m.weight.data.fill_(1) + m.bias.data.zero_() + + def load_state_dict(self, state_dict, strict=True, self_state=False): + own_state = self_state if self_state else self.state_dict() + for name, param in state_dict.items(): + if name in own_state: + try: + own_state[name].copy_(param.data) + except Exception as e: + print("Parameter {} fails to load.".format(name)) + print("-----------------------------------------") + print(e) + else: + print("Parameter {} is not in the model. ".format(name)) + + @contextmanager + def set_activation_inplace(self): + if hasattr(self, "act_fn") and hasattr(self.act_fn, "inplace"): + # save memory + self.act_fn.inplace = True + yield + self.act_fn.inplace = False + else: + yield + + def total_parameters(self): + total = sum([i.numel() for i in self.parameters()]) + trainable = sum([i.numel() for i in self.parameters() if i.requires_grad]) + print( + "Total parameters : {}. Trainable parameters : {}".format(total, trainable) + ) + return total + + def forward(self, *x): + raise NotImplementedError + + +class ResidualFixBlock(BaseModule): + def __init__( + self, + in_channels, + out_channels, + kernel_size=3, + padding=1, + dilation=1, + groups=1, + activation=nn.SELU(), + conv=nn.Conv2d, + ): + super(ResidualFixBlock, self).__init__() + self.act_fn = activation + self.m = nn.Sequential( + conv( + in_channels, + out_channels, + kernel_size, + padding=padding, + dilation=dilation, + groups=groups, + ), + activation, + # conv(out_channels, out_channels, kernel_size, padding=(kernel_size - 1) // 2, dilation=1, groups=groups), + conv( + in_channels, + out_channels, + kernel_size, + padding=padding, + dilation=dilation, + groups=groups, + ), + ) + + def forward(self, x): + out = self.m(x) + return self.act_fn(out + x) + + +class ConvBlock(BaseModule): + def __init__( + self, + in_channels, + out_channels, + kernel_size=3, + padding=1, + dilation=1, + groups=1, + activation=nn.SELU(), + conv=nn.Conv2d, + ): + super(ConvBlock, self).__init__() + self.m = nn.Sequential( + conv( + in_channels, + out_channels, + kernel_size, + padding=padding, + dilation=dilation, + groups=groups, + ), + activation, + ) + + def forward(self, x): + return self.m(x) + + +class UpSampleBlock(BaseModule): + def __init__(self, channels, scale, activation, atrous_rate=1, conv=nn.Conv2d): + assert scale in [2, 4, 8], "Currently UpSampleBlock supports 2, 4, 8 scaling" + super(UpSampleBlock, self).__init__() + m = nn.Sequential( + conv( + channels, + 4 * channels, + kernel_size=3, + padding=atrous_rate, + dilation=atrous_rate, + ), + activation, + nn.PixelShuffle(2), + ) + self.m = nn.Sequential(*[m for _ in range(int(log(scale, 2)))]) + + def forward(self, x): + return self.m(x) + + +class SpatialChannelSqueezeExcitation(BaseModule): + # https://arxiv.org/abs/1709.01507 + # https://arxiv.org/pdf/1803.02579v1.pdf + def __init__(self, in_channel, reduction=16, activation=nn.ReLU()): + super(SpatialChannelSqueezeExcitation, self).__init__() + linear_nodes = max(in_channel // reduction, 4) # avoid only 1 node case + self.avg_pool = nn.AdaptiveAvgPool2d(1) + self.channel_excite = nn.Sequential( + # check the paper for the number 16 in reduction. It is selected by experiment. + nn.Linear(in_channel, linear_nodes), + activation, + nn.Linear(linear_nodes, in_channel), + nn.Sigmoid(), + ) + self.spatial_excite = nn.Sequential( + nn.Conv2d(in_channel, 1, kernel_size=1, stride=1, padding=0, bias=False), + nn.Sigmoid(), + ) + + def forward(self, x): + b, c, h, w = x.size() + # + channel = self.avg_pool(x).view(b, c) + # channel = F.avg_pool2d(x, kernel_size=(h,w)).view(b,c) # used for porting to other frameworks + cSE = self.channel_excite(channel).view(b, c, 1, 1) + x_cSE = torch.mul(x, cSE) + + # spatial + sSE = self.spatial_excite(x) + x_sSE = torch.mul(x, sSE) + # return x_sSE + return torch.add(x_cSE, x_sSE) + + +class PartialConv(nn.Module): + # reference: + # Image Inpainting for Irregular Holes Using Partial Convolutions + # http://masc.cs.gmu.edu/wiki/partialconv/show?time=2018-05-24+21%3A41%3A10 + # https://github.com/naoto0804/pytorch-inpainting-with-partial-conv/blob/master/net.py + # https://github.com/SeitaroShinagawa/chainer-partial_convolution_image_inpainting/blob/master/common/net.py + # partial based padding + # https: // github.com / NVIDIA / partialconv / blob / master / models / pd_resnet.py + def __init__( + self, + in_channels, + out_channels, + kernel_size, + stride=1, + padding=0, + dilation=1, + groups=1, + bias=True, + ): + + super(PartialConv, self).__init__() + self.feature_conv = nn.Conv2d( + in_channels, + out_channels, + kernel_size, + stride, + padding, + dilation, + groups, + bias, + ) + + self.mask_conv = nn.Conv2d( + 1, 1, kernel_size, stride, padding, dilation, groups, bias=False + ) + self.window_size = self.mask_conv.kernel_size[0] * self.mask_conv.kernel_size[1] + torch.nn.init.constant_(self.mask_conv.weight, 1.0) + + for param in self.mask_conv.parameters(): + param.requires_grad = False + + def forward(self, x): + output = self.feature_conv(x) + if self.feature_conv.bias is not None: + output_bias = self.feature_conv.bias.view(1, -1, 1, 1).expand_as(output) + else: + output_bias = torch.zeros_like(output, device=x.device) + + with torch.no_grad(): + ones = torch.ones(1, 1, x.size(2), x.size(3), device=x.device) + output_mask = self.mask_conv(ones) + output_mask = self.window_size / output_mask + output = (output - output_bias) * output_mask + output_bias + + return output diff --git a/Waifu2x/Dataloader.py b/Waifu2x/Dataloader.py new file mode 100644 index 0000000000000000000000000000000000000000..05a6d191de076299fa6bc9a571572f3cc05d279c --- /dev/null +++ b/Waifu2x/Dataloader.py @@ -0,0 +1,231 @@ +import glob +import io +import numpy as np +import re +import os +import random +from io import BytesIO +from uuid import uuid4 +import sqlite3 +import h5py +import torch +from PIL import Image +from torch.utils.data import Dataset +from torchvision.transforms import RandomCrop +from torchvision.transforms.functional import to_tensor + + +class ImageH5Data(Dataset): + def __init__(self, h5py_file, folder_name): + self.data = h5py.File(h5py_file, "r")[folder_name] + self.data_hr = self.data["train_hr"] + self.data_lr = self.data["train_lr"] + self.len_imgs = len(self.data_hr) + self.h5py_file = h5py_file + self.folder_name = folder_name + + def __len__(self): + # with h5py.File(self.h5py_file, 'r') as f: + # return len(f[self.folder_name]['train_lr']) + return self.len_imgs + + def __getitem__(self, index): + # with h5py.File(self.h5py_file, 'r') as f: + # data_lr = f[self.folder_name]['train_lr'][index] + # data_hr = f[self.folder_name]['train_lr'][index] + # + # return data_lr, data_hr + return self.data_lr[index], self.data_hr[index] + + +class ImageData(Dataset): + def __init__( + self, + img_folder, + patch_size=96, + shrink_size=2, + noise_level=1, + down_sample_method=None, + color_mod="RGB", + dummy_len=None, + ): + + self.img_folder = img_folder + all_img = glob.glob(self.img_folder + "/**", recursive=True) + self.img = list( + filter( + lambda x: x.endswith("png") or x.endswith("jpg") or x.endswith("jpeg"), + all_img, + ) + ) + self.total_img = len(self.img) + self.dummy_len = dummy_len if dummy_len is not None else self.total_img + self.random_cropper = RandomCrop(size=patch_size) + self.color_mod = color_mod + self.img_augmenter = ImageAugment(shrink_size, noise_level, down_sample_method) + + def get_img_patches(self, img_file): + img_pil = Image.open(img_file).convert("RGB") + img_patch = self.random_cropper(img_pil) + lr_hr_patches = self.img_augmenter.process(img_patch) + return lr_hr_patches + + def __len__(self): + return self.dummy_len # len(self.img) + + def __getitem__(self, index): + idx = random.choice(range(0, self.total_img)) + img = self.img[idx] + patch = self.get_img_patches(img) + if self.color_mod == "RGB": + lr_img = patch[0].convert("RGB") + hr_img = patch[1].convert("RGB") + elif self.color_mod == "YCbCr": + lr_img, _, _ = patch[0].convert("YCbCr").split() + hr_img, _, _ = patch[1].convert("YCbCr").split() + else: + raise KeyError("Either RGB or YCbCr") + return to_tensor(lr_img), to_tensor(hr_img) + + +class Image2Sqlite(ImageData): + def __getitem__(self, item): + img = self.img[item] + lr_hr_patch = self.get_img_patches(img) + if self.color_mod == "RGB": + lr_img = lr_hr_patch[0].convert("RGB") + hr_img = lr_hr_patch[1].convert("RGB") + elif self.color_mod == "YCbCr": + lr_img, _, _ = lr_hr_patch[0].convert("YCbCr").split() + hr_img, _, _ = lr_hr_patch[1].convert("YCbCr").split() + else: + raise KeyError("Either RGB or YCbCr") + lr_byte = self.convert_to_bytevalue(lr_img) + hr_byte = self.convert_to_bytevalue(hr_img) + return [lr_byte, hr_byte] + + @staticmethod + def convert_to_bytevalue(pil_img): + img_byte = io.BytesIO() + pil_img.save(img_byte, format="png") + return img_byte.getvalue() + + +class ImageDBData(Dataset): + def __init__( + self, + db_file, + db_table="images", + lr_col="lr_img", + hr_col="hr_img", + max_images=None, + ): + self.db_file = db_file + self.db_table = db_table + self.lr_col = lr_col + self.hr_col = hr_col + self.total_images = self.get_num_rows(max_images) + # self.lr_hr_images = self.get_all_images() + + def __len__(self): + return self.total_images + + # def get_all_images(self): + # with sqlite3.connect(self.db_file) as conn: + # cursor = conn.cursor() + # cursor.execute(f"SELECT * FROM {self.db_table} LIMIT {self.total_images}") + # return cursor.fetchall() + + def get_num_rows(self, max_images): + with sqlite3.connect(self.db_file) as conn: + cursor = conn.cursor() + cursor.execute(f"SELECT MAX(ROWID) FROM {self.db_table}") + db_rows = cursor.fetchone()[0] + if max_images: + return min(max_images, db_rows) + else: + return db_rows + + def __getitem__(self, item): + # lr, hr = self.lr_hr_images[item] + # lr = Image.open(io.BytesIO(lr)) + # hr = Image.open(io.BytesIO(hr)) + # return to_tensor(lr), to_tensor(hr) + # note sqlite rowid starts with 1 + with sqlite3.connect(self.db_file) as conn: + cursor = conn.cursor() + cursor.execute( + f"SELECT {self.lr_col}, {self.hr_col} FROM {self.db_table} WHERE ROWID={item + 1}" + ) + lr, hr = cursor.fetchone() + lr = Image.open(io.BytesIO(lr)).convert("RGB") + hr = Image.open(io.BytesIO(hr)).convert("RGB") + # lr = np.array(lr) # use scale [0, 255] instead of [0,1] + # hr = np.array(hr) + return to_tensor(lr), to_tensor(hr) + + +class ImagePatchData(Dataset): + def __init__(self, lr_folder, hr_folder): + self.lr_folder = lr_folder + self.hr_folder = hr_folder + self.lr_imgs = glob.glob(os.path.join(lr_folder, "**")) + self.total_imgs = len(self.lr_imgs) + + def __len__(self): + return self.total_imgs + + def __getitem__(self, item): + lr_file = self.lr_imgs[item] + hr_path = re.sub("lr", "hr", os.path.dirname(lr_file)) + filename = os.path.basename(lr_file) + hr_file = os.path.join(hr_path, filename) + return to_tensor(Image.open(lr_file)), to_tensor(Image.open(hr_file)) + + +class ImageAugment: + def __init__(self, shrink_size=2, noise_level=1, down_sample_method=None): + # noise_level (int): 0: no noise; 1: 75-95% quality; 2:50-75% + if noise_level == 0: + self.noise_level = [0, 0] + elif noise_level == 1: + self.noise_level = [5, 25] + elif noise_level == 2: + self.noise_level = [25, 50] + else: + raise KeyError("Noise level should be either 0, 1, 2") + self.shrink_size = shrink_size + self.down_sample_method = down_sample_method + + def shrink_img(self, hr_img): + + if self.down_sample_method is None: + resample_method = random.choice( + [Image.BILINEAR, Image.BICUBIC, Image.LANCZOS] + ) + else: + resample_method = self.down_sample_method + img_w, img_h = tuple(map(lambda x: int(x / self.shrink_size), hr_img.size)) + lr_img = hr_img.resize((img_w, img_h), resample_method) + return lr_img + + def add_jpeg_noise(self, hr_img): + quality = 100 - round(random.uniform(*self.noise_level)) + lr_img = BytesIO() + hr_img.save(lr_img, format="JPEG", quality=quality) + lr_img.seek(0) + lr_img = Image.open(lr_img) + return lr_img + + def process(self, hr_patch_pil): + lr_patch_pil = self.shrink_img(hr_patch_pil) + if self.noise_level[1] > 0: + lr_patch_pil = self.add_jpeg_noise(lr_patch_pil) + + return lr_patch_pil, hr_patch_pil + + def up_sample(self, img, resample): + width, height = img.size + return img.resize( + (self.shrink_size * width, self.shrink_size * height), resample=resample + ) diff --git a/Waifu2x/Img_to_Sqlite.py b/Waifu2x/Img_to_Sqlite.py new file mode 100644 index 0000000000000000000000000000000000000000..6f761e681e84433f4060bd2ec9abedddbc261381 --- /dev/null +++ b/Waifu2x/Img_to_Sqlite.py @@ -0,0 +1,123 @@ +""" +Split images into small patches and insert them into sqlite db. Reading and Inserting speeds are much better than +Ubuntu's (18.04) file system when the number of patches is larger than 20k. And it has smaller size than using h5 format + +Recommend to check or filter out small size patches as their content vary little. 128x128 seems better than 64x64. + + +""" +import sqlite3 +from torch.utils.data import DataLoader +from tqdm import trange +from Dataloader import Image2Sqlite + +conn = sqlite3.connect("dataset/image_yandere.db") +cursor = conn.cursor() + +with conn: + cursor.execute("PRAGMA SYNCHRONOUS = OFF") + +table_name = "train_images_size_128_noise_1_rgb" +lr_col = "lr_img" +hr_col = "hr_img" + +with conn: + conn.execute( + f"CREATE TABLE IF NOT EXISTS {table_name} ({lr_col} BLOB, {hr_col} BLOB)" + ) + +dat = Image2Sqlite( + img_folder="./dataset/yande.re_test_shrink", + patch_size=256, + shrink_size=2, + noise_level=1, + down_sample_method=None, + color_mod="RGB", + dummy_len=None, +) +print(f"Total images {len(dat)}") + +img_dat = DataLoader(dat, num_workers=6, batch_size=6, shuffle=True) + +num_batches = 20 +for i in trange(num_batches): + bulk = [] + for lrs, hrs in img_dat: + patches = [(lrs[i], hrs[i]) for i in range(len(lrs))] + # patches = [(lrs[i], hrs[i]) for i in range(len(lrs)) if len(lrs[i]) > 14000] + + bulk.extend(patches) + + bulk = [ + i for i in bulk if len(i[0]) > 15000 + ] # for 128x128, 14000 is fair. Around 20% of patches are filtered out + cursor.executemany( + f"INSERT INTO {table_name}({lr_col}, {hr_col}) VALUES (?,?)", bulk + ) + conn.commit() + +cursor.execute(f"select max(rowid) from {table_name}") +print(cursor.fetchall()) +conn.commit() +# +++++++++++++++++++++++++++++++++++++ +# Used for Create Test Database +# ------------------------------------- + +# cursor.execute(f"SELECT ROWID FROM {table_name} ORDER BY LENGTH({lr_col}) DESC LIMIT 400") +# rowdis = cursor.fetchall() +# rowdis = ",".join([str(i[0]) for i in rowdis]) +# +# cursor.execute(f"DELETE FROM {table_name} WHERE ROWID NOT IN ({rowdis})") +# conn.commit() +# cursor.execute("vacuum") +# +# cursor.execute(""" +# CREATE TABLE IF NOT EXISTS train_images_size_128_noise_1_rgb_small AS +# SELECT * +# FROM train_images_size_128_noise_1_rgb +# WHERE length(lr_img) < 14000; +# """) +# +# cursor.execute(""" +# DELETE +# FROM train_images_size_128_noise_1_rgb +# WHERE length(lr_img) < 14000; +# """) + +# reset index +cursor.execute("VACUUM") +conn.commit() + +# +++++++++++++++++++++++++++++++++++++ +# check image size +# ------------------------------------- +# + +from PIL import Image +import io + +cursor.execute( + f""" + select {hr_col} from {table_name} + ORDER BY LENGTH({hr_col}) desc + limit 100 +""" +) +# WHERE LENGTH({lr_col}) BETWEEN 14000 AND 16000 + +# small = cursor.fetchall() +# print(len(small)) +for idx, i in enumerate(cursor): + img = Image.open(io.BytesIO(i[0])) + img.save(f"dataset/check/{idx}.png") + +# +++++++++++++++++++++++++++++++++++++ +# Check Image Variance +# ------------------------------------- + +import pandas as pd +import matplotlib.pyplot as plt + +dat = pd.read_sql(f"SELECT length({lr_col}) from {table_name}", conn) +dat.hist(bins=20) +plt.show() diff --git a/Waifu2x/LICENSE b/Waifu2x/LICENSE new file mode 100644 index 0000000000000000000000000000000000000000..94a9ed024d3859793618152ea559a168bbcbb5e2 --- /dev/null +++ b/Waifu2x/LICENSE @@ -0,0 +1,674 @@ + GNU GENERAL PUBLIC LICENSE + Version 3, 29 June 2007 + + Copyright (C) 2007 Free Software Foundation, Inc. + Everyone is permitted to copy and distribute verbatim copies + of this license document, but changing it is not allowed. + + Preamble + + The GNU General Public License is a free, copyleft license for +software and other kinds of works. + + The licenses for most software and other practical works are designed +to take away your freedom to share and change the works. By contrast, +the GNU General Public License is intended to guarantee your freedom to +share and change all versions of a program--to make sure it remains free +software for all its users. We, the Free Software Foundation, use the +GNU General Public License for most of our software; it applies also to +any other work released this way by its authors. You can apply it to +your programs, too. + + When we speak of free software, we are referring to freedom, not +price. Our General Public Licenses are designed to make sure that you +have the freedom to distribute copies of free software (and charge for +them if you wish), that you receive source code or can get it if you +want it, that you can change the software or use pieces of it in new +free programs, and that you know you can do these things. + + To protect your rights, we need to prevent others from denying you +these rights or asking you to surrender the rights. Therefore, you have +certain responsibilities if you distribute copies of the software, or if +you modify it: responsibilities to respect the freedom of others. + + For example, if you distribute copies of such a program, whether +gratis or for a fee, you must pass on to the recipients the same +freedoms that you received. You must make sure that they, too, receive +or can get the source code. And you must show them these terms so they +know their rights. + + Developers that use the GNU GPL protect your rights with two steps: +(1) assert copyright on the software, and (2) offer you this License +giving you legal permission to copy, distribute and/or modify it. + + For the developers' and authors' protection, the GPL clearly explains +that there is no warranty for this free software. For both users' and +authors' sake, the GPL requires that modified versions be marked as +changed, so that their problems will not be attributed erroneously to +authors of previous versions. + + Some devices are designed to deny users access to install or run +modified versions of the software inside them, although the manufacturer +can do so. This is fundamentally incompatible with the aim of +protecting users' freedom to change the software. The systematic +pattern of such abuse occurs in the area of products for individuals to +use, which is precisely where it is most unacceptable. Therefore, we +have designed this version of the GPL to prohibit the practice for those +products. If such problems arise substantially in other domains, we +stand ready to extend this provision to those domains in future versions +of the GPL, as needed to protect the freedom of users. + + Finally, every program is threatened constantly by software patents. +States should not allow patents to restrict development and use of +software on general-purpose computers, but in those that do, we wish to +avoid the special danger that patents applied to a free program could +make it effectively proprietary. To prevent this, the GPL assures that +patents cannot be used to render the program non-free. + + The precise terms and conditions for copying, distribution and +modification follow. + + TERMS AND CONDITIONS + + 0. Definitions. + + "This License" refers to version 3 of the GNU General Public License. + + "Copyright" also means copyright-like laws that apply to other kinds of +works, such as semiconductor masks. + + "The Program" refers to any copyrightable work licensed under this +License. Each licensee is addressed as "you". "Licensees" and +"recipients" may be individuals or organizations. + + To "modify" a work means to copy from or adapt all or part of the work +in a fashion requiring copyright permission, other than the making of an +exact copy. The resulting work is called a "modified version" of the +earlier work or a work "based on" the earlier work. + + A "covered work" means either the unmodified Program or a work based +on the Program. + + To "propagate" a work means to do anything with it that, without +permission, would make you directly or secondarily liable for +infringement under applicable copyright law, except executing it on a +computer or modifying a private copy. Propagation includes copying, +distribution (with or without modification), making available to the +public, and in some countries other activities as well. + + To "convey" a work means any kind of propagation that enables other +parties to make or receive copies. Mere interaction with a user through +a computer network, with no transfer of a copy, is not conveying. + + An interactive user interface displays "Appropriate Legal Notices" +to the extent that it includes a convenient and prominently visible +feature that (1) displays an appropriate copyright notice, and (2) +tells the user that there is no warranty for the work (except to the +extent that warranties are provided), that licensees may convey the +work under this License, and how to view a copy of this License. If +the interface presents a list of user commands or options, such as a +menu, a prominent item in the list meets this criterion. + + 1. Source Code. + + The "source code" for a work means the preferred form of the work +for making modifications to it. "Object code" means any non-source +form of a work. + + A "Standard Interface" means an interface that either is an official +standard defined by a recognized standards body, or, in the case of +interfaces specified for a particular programming language, one that +is widely used among developers working in that language. + + The "System Libraries" of an executable work include anything, other +than the work as a whole, that (a) is included in the normal form of +packaging a Major Component, but which is not part of that Major +Component, and (b) serves only to enable use of the work with that +Major Component, or to implement a Standard Interface for which an +implementation is available to the public in source code form. A +"Major Component", in this context, means a major essential component +(kernel, window system, and so on) of the specific operating system +(if any) on which the executable work runs, or a compiler used to +produce the work, or an object code interpreter used to run it. + + The "Corresponding Source" for a work in object code form means all +the source code needed to generate, install, and (for an executable +work) run the object code and to modify the work, including scripts to +control those activities. However, it does not include the work's +System Libraries, or general-purpose tools or generally available free +programs which are used unmodified in performing those activities but +which are not part of the work. For example, Corresponding Source +includes interface definition files associated with source files for +the work, and the source code for shared libraries and dynamically +linked subprograms that the work is specifically designed to require, +such as by intimate data communication or control flow between those +subprograms and other parts of the work. + + The Corresponding Source need not include anything that users +can regenerate automatically from other parts of the Corresponding +Source. + + The Corresponding Source for a work in source code form is that +same work. + + 2. Basic Permissions. + + All rights granted under this License are granted for the term of +copyright on the Program, and are irrevocable provided the stated +conditions are met. This License explicitly affirms your unlimited +permission to run the unmodified Program. The output from running a +covered work is covered by this License only if the output, given its +content, constitutes a covered work. This License acknowledges your +rights of fair use or other equivalent, as provided by copyright law. + + You may make, run and propagate covered works that you do not +convey, without conditions so long as your license otherwise remains +in force. You may convey covered works to others for the sole purpose +of having them make modifications exclusively for you, or provide you +with facilities for running those works, provided that you comply with +the terms of this License in conveying all material for which you do +not control copyright. Those thus making or running the covered works +for you must do so exclusively on your behalf, under your direction +and control, on terms that prohibit them from making any copies of +your copyrighted material outside their relationship with you. + + Conveying under any other circumstances is permitted solely under +the conditions stated below. Sublicensing is not allowed; section 10 +makes it unnecessary. + + 3. Protecting Users' Legal Rights From Anti-Circumvention Law. + + No covered work shall be deemed part of an effective technological +measure under any applicable law fulfilling obligations under article +11 of the WIPO copyright treaty adopted on 20 December 1996, or +similar laws prohibiting or restricting circumvention of such +measures. + + When you convey a covered work, you waive any legal power to forbid +circumvention of technological measures to the extent such circumvention +is effected by exercising rights under this License with respect to +the covered work, and you disclaim any intention to limit operation or +modification of the work as a means of enforcing, against the work's +users, your or third parties' legal rights to forbid circumvention of +technological measures. + + 4. Conveying Verbatim Copies. + + You may convey verbatim copies of the Program's source code as you +receive it, in any medium, provided that you conspicuously and +appropriately publish on each copy an appropriate copyright notice; +keep intact all notices stating that this License and any +non-permissive terms added in accord with section 7 apply to the code; +keep intact all notices of the absence of any warranty; and give all +recipients a copy of this License along with the Program. + + You may charge any price or no price for each copy that you convey, +and you may offer support or warranty protection for a fee. + + 5. Conveying Modified Source Versions. + + You may convey a work based on the Program, or the modifications to +produce it from the Program, in the form of source code under the +terms of section 4, provided that you also meet all of these conditions: + + a) The work must carry prominent notices stating that you modified + it, and giving a relevant date. + + b) The work must carry prominent notices stating that it is + released under this License and any conditions added under section + 7. This requirement modifies the requirement in section 4 to + "keep intact all notices". + + c) You must license the entire work, as a whole, under this + License to anyone who comes into possession of a copy. This + License will therefore apply, along with any applicable section 7 + additional terms, to the whole of the work, and all its parts, + regardless of how they are packaged. This License gives no + permission to license the work in any other way, but it does not + invalidate such permission if you have separately received it. + + d) If the work has interactive user interfaces, each must display + Appropriate Legal Notices; however, if the Program has interactive + interfaces that do not display Appropriate Legal Notices, your + work need not make them do so. + + A compilation of a covered work with other separate and independent +works, which are not by their nature extensions of the covered work, +and which are not combined with it such as to form a larger program, +in or on a volume of a storage or distribution medium, is called an +"aggregate" if the compilation and its resulting copyright are not +used to limit the access or legal rights of the compilation's users +beyond what the individual works permit. Inclusion of a covered work +in an aggregate does not cause this License to apply to the other +parts of the aggregate. + + 6. Conveying Non-Source Forms. + + You may convey a covered work in object code form under the terms +of sections 4 and 5, provided that you also convey the +machine-readable Corresponding Source under the terms of this License, +in one of these ways: + + a) Convey the object code in, or embodied in, a physical product + (including a physical distribution medium), accompanied by the + Corresponding Source fixed on a durable physical medium + customarily used for software interchange. + + b) Convey the object code in, or embodied in, a physical product + (including a physical distribution medium), accompanied by a + written offer, valid for at least three years and valid for as + long as you offer spare parts or customer support for that product + model, to give anyone who possesses the object code either (1) a + copy of the Corresponding Source for all the software in the + product that is covered by this License, on a durable physical + medium customarily used for software interchange, for a price no + more than your reasonable cost of physically performing this + conveying of source, or (2) access to copy the + Corresponding Source from a network server at no charge. + + c) Convey individual copies of the object code with a copy of the + written offer to provide the Corresponding Source. This + alternative is allowed only occasionally and noncommercially, and + only if you received the object code with such an offer, in accord + with subsection 6b. + + d) Convey the object code by offering access from a designated + place (gratis or for a charge), and offer equivalent access to the + Corresponding Source in the same way through the same place at no + further charge. You need not require recipients to copy the + Corresponding Source along with the object code. If the place to + copy the object code is a network server, the Corresponding Source + may be on a different server (operated by you or a third party) + that supports equivalent copying facilities, provided you maintain + clear directions next to the object code saying where to find the + Corresponding Source. Regardless of what server hosts the + Corresponding Source, you remain obligated to ensure that it is + available for as long as needed to satisfy these requirements. + + e) Convey the object code using peer-to-peer transmission, provided + you inform other peers where the object code and Corresponding + Source of the work are being offered to the general public at no + charge under subsection 6d. + + A separable portion of the object code, whose source code is excluded +from the Corresponding Source as a System Library, need not be +included in conveying the object code work. + + A "User Product" is either (1) a "consumer product", which means any +tangible personal property which is normally used for personal, family, +or household purposes, or (2) anything designed or sold for incorporation +into a dwelling. In determining whether a product is a consumer product, +doubtful cases shall be resolved in favor of coverage. For a particular +product received by a particular user, "normally used" refers to a +typical or common use of that class of product, regardless of the status +of the particular user or of the way in which the particular user +actually uses, or expects or is expected to use, the product. A product +is a consumer product regardless of whether the product has substantial +commercial, industrial or non-consumer uses, unless such uses represent +the only significant mode of use of the product. + + "Installation Information" for a User Product means any methods, +procedures, authorization keys, or other information required to install +and execute modified versions of a covered work in that User Product from +a modified version of its Corresponding Source. The information must +suffice to ensure that the continued functioning of the modified object +code is in no case prevented or interfered with solely because +modification has been made. + + If you convey an object code work under this section in, or with, or +specifically for use in, a User Product, and the conveying occurs as +part of a transaction in which the right of possession and use of the +User Product is transferred to the recipient in perpetuity or for a +fixed term (regardless of how the transaction is characterized), the +Corresponding Source conveyed under this section must be accompanied +by the Installation Information. But this requirement does not apply +if neither you nor any third party retains the ability to install +modified object code on the User Product (for example, the work has +been installed in ROM). + + The requirement to provide Installation Information does not include a +requirement to continue to provide support service, warranty, or updates +for a work that has been modified or installed by the recipient, or for +the User Product in which it has been modified or installed. Access to a +network may be denied when the modification itself materially and +adversely affects the operation of the network or violates the rules and +protocols for communication across the network. + + Corresponding Source conveyed, and Installation Information provided, +in accord with this section must be in a format that is publicly +documented (and with an implementation available to the public in +source code form), and must require no special password or key for +unpacking, reading or copying. + + 7. Additional Terms. + + "Additional permissions" are terms that supplement the terms of this +License by making exceptions from one or more of its conditions. +Additional permissions that are applicable to the entire Program shall +be treated as though they were included in this License, to the extent +that they are valid under applicable law. If additional permissions +apply only to part of the Program, that part may be used separately +under those permissions, but the entire Program remains governed by +this License without regard to the additional permissions. + + When you convey a copy of a covered work, you may at your option +remove any additional permissions from that copy, or from any part of +it. (Additional permissions may be written to require their own +removal in certain cases when you modify the work.) You may place +additional permissions on material, added by you to a covered work, +for which you have or can give appropriate copyright permission. + + Notwithstanding any other provision of this License, for material you +add to a covered work, you may (if authorized by the copyright holders of +that material) supplement the terms of this License with terms: + + a) Disclaiming warranty or limiting liability differently from the + terms of sections 15 and 16 of this License; or + + b) Requiring preservation of specified reasonable legal notices or + author attributions in that material or in the Appropriate Legal + Notices displayed by works containing it; or + + c) Prohibiting misrepresentation of the origin of that material, or + requiring that modified versions of such material be marked in + reasonable ways as different from the original version; or + + d) Limiting the use for publicity purposes of names of licensors or + authors of the material; or + + e) Declining to grant rights under trademark law for use of some + trade names, trademarks, or service marks; or + + f) Requiring indemnification of licensors and authors of that + material by anyone who conveys the material (or modified versions of + it) with contractual assumptions of liability to the recipient, for + any liability that these contractual assumptions directly impose on + those licensors and authors. + + All other non-permissive additional terms are considered "further +restrictions" within the meaning of section 10. If the Program as you +received it, or any part of it, contains a notice stating that it is +governed by this License along with a term that is a further +restriction, you may remove that term. If a license document contains +a further restriction but permits relicensing or conveying under this +License, you may add to a covered work material governed by the terms +of that license document, provided that the further restriction does +not survive such relicensing or conveying. + + If you add terms to a covered work in accord with this section, you +must place, in the relevant source files, a statement of the +additional terms that apply to those files, or a notice indicating +where to find the applicable terms. + + Additional terms, permissive or non-permissive, may be stated in the +form of a separately written license, or stated as exceptions; +the above requirements apply either way. + + 8. Termination. + + You may not propagate or modify a covered work except as expressly +provided under this License. Any attempt otherwise to propagate or +modify it is void, and will automatically terminate your rights under +this License (including any patent licenses granted under the third +paragraph of section 11). + + However, if you cease all violation of this License, then your +license from a particular copyright holder is reinstated (a) +provisionally, unless and until the copyright holder explicitly and +finally terminates your license, and (b) permanently, if the copyright +holder fails to notify you of the violation by some reasonable means +prior to 60 days after the cessation. + + Moreover, your license from a particular copyright holder is +reinstated permanently if the copyright holder notifies you of the +violation by some reasonable means, this is the first time you have +received notice of violation of this License (for any work) from that +copyright holder, and you cure the violation prior to 30 days after +your receipt of the notice. + + Termination of your rights under this section does not terminate the +licenses of parties who have received copies or rights from you under +this License. If your rights have been terminated and not permanently +reinstated, you do not qualify to receive new licenses for the same +material under section 10. + + 9. Acceptance Not Required for Having Copies. + + You are not required to accept this License in order to receive or +run a copy of the Program. Ancillary propagation of a covered work +occurring solely as a consequence of using peer-to-peer transmission +to receive a copy likewise does not require acceptance. However, +nothing other than this License grants you permission to propagate or +modify any covered work. These actions infringe copyright if you do +not accept this License. Therefore, by modifying or propagating a +covered work, you indicate your acceptance of this License to do so. + + 10. Automatic Licensing of Downstream Recipients. + + Each time you convey a covered work, the recipient automatically +receives a license from the original licensors, to run, modify and +propagate that work, subject to this License. You are not responsible +for enforcing compliance by third parties with this License. + + An "entity transaction" is a transaction transferring control of an +organization, or substantially all assets of one, or subdividing an +organization, or merging organizations. If propagation of a covered +work results from an entity transaction, each party to that +transaction who receives a copy of the work also receives whatever +licenses to the work the party's predecessor in interest had or could +give under the previous paragraph, plus a right to possession of the +Corresponding Source of the work from the predecessor in interest, if +the predecessor has it or can get it with reasonable efforts. + + You may not impose any further restrictions on the exercise of the +rights granted or affirmed under this License. For example, you may +not impose a license fee, royalty, or other charge for exercise of +rights granted under this License, and you may not initiate litigation +(including a cross-claim or counterclaim in a lawsuit) alleging that +any patent claim is infringed by making, using, selling, offering for +sale, or importing the Program or any portion of it. + + 11. Patents. + + A "contributor" is a copyright holder who authorizes use under this +License of the Program or a work on which the Program is based. The +work thus licensed is called the contributor's "contributor version". + + A contributor's "essential patent claims" are all patent claims +owned or controlled by the contributor, whether already acquired or +hereafter acquired, that would be infringed by some manner, permitted +by this License, of making, using, or selling its contributor version, +but do not include claims that would be infringed only as a +consequence of further modification of the contributor version. For +purposes of this definition, "control" includes the right to grant +patent sublicenses in a manner consistent with the requirements of +this License. + + Each contributor grants you a non-exclusive, worldwide, royalty-free +patent license under the contributor's essential patent claims, to +make, use, sell, offer for sale, import and otherwise run, modify and +propagate the contents of its contributor version. + + In the following three paragraphs, a "patent license" is any express +agreement or commitment, however denominated, not to enforce a patent +(such as an express permission to practice a patent or covenant not to +sue for patent infringement). To "grant" such a patent license to a +party means to make such an agreement or commitment not to enforce a +patent against the party. + + If you convey a covered work, knowingly relying on a patent license, +and the Corresponding Source of the work is not available for anyone +to copy, free of charge and under the terms of this License, through a +publicly available network server or other readily accessible means, +then you must either (1) cause the Corresponding Source to be so +available, or (2) arrange to deprive yourself of the benefit of the +patent license for this particular work, or (3) arrange, in a manner +consistent with the requirements of this License, to extend the patent +license to downstream recipients. "Knowingly relying" means you have +actual knowledge that, but for the patent license, your conveying the +covered work in a country, or your recipient's use of the covered work +in a country, would infringe one or more identifiable patents in that +country that you have reason to believe are valid. + + If, pursuant to or in connection with a single transaction or +arrangement, you convey, or propagate by procuring conveyance of, a +covered work, and grant a patent license to some of the parties +receiving the covered work authorizing them to use, propagate, modify +or convey a specific copy of the covered work, then the patent license +you grant is automatically extended to all recipients of the covered +work and works based on it. + + A patent license is "discriminatory" if it does not include within +the scope of its coverage, prohibits the exercise of, or is +conditioned on the non-exercise of one or more of the rights that are +specifically granted under this License. You may not convey a covered +work if you are a party to an arrangement with a third party that is +in the business of distributing software, under which you make payment +to the third party based on the extent of your activity of conveying +the work, and under which the third party grants, to any of the +parties who would receive the covered work from you, a discriminatory +patent license (a) in connection with copies of the covered work +conveyed by you (or copies made from those copies), or (b) primarily +for and in connection with specific products or compilations that +contain the covered work, unless you entered into that arrangement, +or that patent license was granted, prior to 28 March 2007. + + Nothing in this License shall be construed as excluding or limiting +any implied license or other defenses to infringement that may +otherwise be available to you under applicable patent law. + + 12. No Surrender of Others' Freedom. + + If conditions are imposed on you (whether by court order, agreement or +otherwise) that contradict the conditions of this License, they do not +excuse you from the conditions of this License. If you cannot convey a +covered work so as to satisfy simultaneously your obligations under this +License and any other pertinent obligations, then as a consequence you may +not convey it at all. For example, if you agree to terms that obligate you +to collect a royalty for further conveying from those to whom you convey +the Program, the only way you could satisfy both those terms and this +License would be to refrain entirely from conveying the Program. + + 13. Use with the GNU Affero General Public License. + + Notwithstanding any other provision of this License, you have +permission to link or combine any covered work with a work licensed +under version 3 of the GNU Affero General Public License into a single +combined work, and to convey the resulting work. The terms of this +License will continue to apply to the part which is the covered work, +but the special requirements of the GNU Affero General Public License, +section 13, concerning interaction through a network will apply to the +combination as such. + + 14. Revised Versions of this License. + + The Free Software Foundation may publish revised and/or new versions of +the GNU General Public License from time to time. Such new versions will +be similar in spirit to the present version, but may differ in detail to +address new problems or concerns. + + Each version is given a distinguishing version number. If the +Program specifies that a certain numbered version of the GNU General +Public License "or any later version" applies to it, you have the +option of following the terms and conditions either of that numbered +version or of any later version published by the Free Software +Foundation. If the Program does not specify a version number of the +GNU General Public License, you may choose any version ever published +by the Free Software Foundation. + + If the Program specifies that a proxy can decide which future +versions of the GNU General Public License can be used, that proxy's +public statement of acceptance of a version permanently authorizes you +to choose that version for the Program. + + Later license versions may give you additional or different +permissions. However, no additional obligations are imposed on any +author or copyright holder as a result of your choosing to follow a +later version. + + 15. Disclaimer of Warranty. + + THERE IS NO WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY +APPLICABLE LAW. EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT +HOLDERS AND/OR OTHER PARTIES PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY +OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO, +THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR +PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE PROGRAM +IS WITH YOU. SHOULD THE PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF +ALL NECESSARY SERVICING, REPAIR OR CORRECTION. + + 16. Limitation of Liability. + + IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING +WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MODIFIES AND/OR CONVEYS +THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY +GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE +USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED TO LOSS OF +DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD +PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER PROGRAMS), +EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF +SUCH DAMAGES. + + 17. Interpretation of Sections 15 and 16. + + If the disclaimer of warranty and limitation of liability provided +above cannot be given local legal effect according to their terms, +reviewing courts shall apply local law that most closely approximates +an absolute waiver of all civil liability in connection with the +Program, unless a warranty or assumption of liability accompanies a +copy of the Program in return for a fee. + + END OF TERMS AND CONDITIONS + + How to Apply These Terms to Your New Programs + + If you develop a new program, and you want it to be of the greatest +possible use to the public, the best way to achieve this is to make it +free software which everyone can redistribute and change under these terms. + + To do so, attach the following notices to the program. It is safest +to attach them to the start of each source file to most effectively +state the exclusion of warranty; and each file should have at least +the "copyright" line and a pointer to where the full notice is found. + + + Copyright (C) + + This program is free software: you can redistribute it and/or modify + it under the terms of the GNU General Public License as published by + the Free Software Foundation, either version 3 of the License, or + (at your option) any later version. + + This program is distributed in the hope that it will be useful, + but WITHOUT ANY WARRANTY; without even the implied warranty of + MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + GNU General Public License for more details. + + You should have received a copy of the GNU General Public License + along with this program. If not, see . + +Also add information on how to contact you by electronic and paper mail. + + If the program does terminal interaction, make it output a short +notice like this when it starts in an interactive mode: + + Copyright (C) + This program comes with ABSOLUTELY NO WARRANTY; for details type `show w'. + This is free software, and you are welcome to redistribute it + under certain conditions; type `show c' for details. + +The hypothetical commands `show w' and `show c' should show the appropriate +parts of the General Public License. Of course, your program's commands +might be different; for a GUI interface, you would use an "about box". + + You should also get your employer (if you work as a programmer) or school, +if any, to sign a "copyright disclaimer" for the program, if necessary. +For more information on this, and how to apply and follow the GNU GPL, see +. + + The GNU General Public License does not permit incorporating your program +into proprietary programs. If your program is a subroutine library, you +may consider it more useful to permit linking proprietary applications with +the library. If this is what you want to do, use the GNU Lesser General +Public License instead of this License. But first, please read +. diff --git a/Waifu2x/Loss.py b/Waifu2x/Loss.py new file mode 100644 index 0000000000000000000000000000000000000000..647a4a2541af6584ece5c3744df2a84512f6ea58 --- /dev/null +++ b/Waifu2x/Loss.py @@ -0,0 +1,51 @@ +import torch +from torch import nn +from torch.nn.functional import _pointwise_loss + +rgb_weights = [0.29891 * 3, 0.58661 * 3, 0.11448 * 3] +# RGB have different weights +# https://github.com/nagadomi/waifu2x/blob/master/train.lua#L109 +use_cuda = torch.cuda.is_available() +FloatTensor = torch.cuda.FloatTensor if use_cuda else torch.FloatTensor +LongTensor = torch.cuda.LongTensor if use_cuda else torch.LongTensor +Tensor = FloatTensor + + +class WeightedHuberLoss(nn.SmoothL1Loss): + def __init__(self, weights=rgb_weights): + super(WeightedHuberLoss, self).__init__(size_average=True, reduce=True) + self.weights = torch.FloatTensor(weights).view(3, 1, 1) + + def forward(self, input_data, target): + diff = torch.abs(input_data - target) + z = torch.where(diff < 1, 0.5 * torch.pow(diff, 2), (diff - 0.5)) + out = z * self.weights.expand_as(diff) + return out.mean() + + +def weighted_mse_loss(input, target, weights): + out = (input - target) ** 2 + out = out * weights.expand_as(out) + loss = out.sum(0) # or sum over whatever dimensions + return loss / out.size(0) + + +class WeightedL1Loss(nn.SmoothL1Loss): + def __init__(self, weights=rgb_weights): + super(WeightedHuberLoss, self).__init__(size_average=True, reduce=True) + self.weights = torch.FloatTensor(weights).view(3, 1, 1) + + def forward(self, input_data, target): + return self.l1_loss( + input_data, target, size_average=self.size_average, reduce=self.reduce + ) + + def l1_loss(self, input_data, target, size_average=True, reduce=True): + return _pointwise_loss( + lambda a, b: torch.abs(a - b) * self.weights.expand_as(a), + torch._C._nn.l1_loss, + input_data, + target, + size_average, + reduce, + ) diff --git a/Waifu2x/Models.py b/Waifu2x/Models.py new file mode 100644 index 0000000000000000000000000000000000000000..8072a01ed3c242832a60160e60a03f025f198193 --- /dev/null +++ b/Waifu2x/Models.py @@ -0,0 +1,450 @@ +import json +from collections import OrderedDict +from math import exp + +from .Common import * + + +# +++++++++++++++++++++++++++++++++++++ +# FP16 Training +# ------------------------------------- +# Modified from Nvidia/Apex +# https://github.com/NVIDIA/apex/blob/master/apex/fp16_utils/fp16util.py + + +class tofp16(nn.Module): + def __init__(self): + super(tofp16, self).__init__() + + def forward(self, input): + if input.is_cuda: + return input.half() + else: # PyTorch 1.0 doesn't support fp16 in CPU + return input.float() + + +def BN_convert_float(module): + if isinstance(module, torch.nn.modules.batchnorm._BatchNorm): + module.float() + for child in module.children(): + BN_convert_float(child) + return module + + +def network_to_half(network): + return nn.Sequential(tofp16(), BN_convert_float(network.half())) + + +# warnings.simplefilter('ignore') + +# +++++++++++++++++++++++++++++++++++++ +# DCSCN +# ------------------------------------- + + +class DCSCN(BaseModule): + # https://github.com/jiny2001/dcscn-super-resolution + def __init__( + self, + color_channel=3, + up_scale=2, + feature_layers=12, + first_feature_filters=196, + last_feature_filters=48, + reconstruction_filters=128, + up_sampler_filters=32, + ): + super(DCSCN, self).__init__() + self.total_feature_channels = 0 + self.total_reconstruct_filters = 0 + self.upscale = up_scale + + self.act_fn = nn.SELU(inplace=False) + self.feature_block = self.make_feature_extraction_block( + color_channel, feature_layers, first_feature_filters, last_feature_filters + ) + + self.reconstruction_block = self.make_reconstruction_block( + reconstruction_filters + ) + self.up_sampler = self.make_upsampler(up_sampler_filters, color_channel) + self.selu_init_params() + + def selu_init_params(self): + for i in self.modules(): + if isinstance(i, nn.Conv2d): + i.weight.data.normal_(0.0, 1.0 / sqrt(i.weight.numel())) + if i.bias is not None: + i.bias.data.fill_(0) + + def conv_block(self, in_channel, out_channel, kernel_size): + m = OrderedDict( + [ + # ("Padding", nn.ReplicationPad2d((kernel_size - 1) // 2)), + ( + "Conv2d", + nn.Conv2d( + in_channel, + out_channel, + kernel_size=kernel_size, + padding=(kernel_size - 1) // 2, + ), + ), + ("Activation", self.act_fn), + ] + ) + + return nn.Sequential(m) + + def make_feature_extraction_block( + self, color_channel, num_layers, first_filters, last_filters + ): + # input layer + feature_block = [ + ("Feature 1", self.conv_block(color_channel, first_filters, 3)) + ] + # exponential decay + # rest layers + alpha_rate = log(first_filters / last_filters) / (num_layers - 1) + filter_nums = [ + round(first_filters * exp(-alpha_rate * i)) for i in range(num_layers) + ] + + self.total_feature_channels = sum(filter_nums) + + layer_filters = [ + [filter_nums[i], filter_nums[i + 1], 3] for i in range(num_layers - 1) + ] + + feature_block.extend( + [ + ("Feature {}".format(index + 2), self.conv_block(*x)) + for index, x in enumerate(layer_filters) + ] + ) + return nn.Sequential(OrderedDict(feature_block)) + + def make_reconstruction_block(self, num_filters): + B1 = self.conv_block(self.total_feature_channels, num_filters // 2, 1) + B2 = self.conv_block(num_filters // 2, num_filters, 3) + m = OrderedDict( + [ + ("A", self.conv_block(self.total_feature_channels, num_filters, 1)), + ("B", nn.Sequential(*[B1, B2])), + ] + ) + self.total_reconstruct_filters = num_filters * 2 + return nn.Sequential(m) + + def make_upsampler(self, out_channel, color_channel): + out = out_channel * self.upscale**2 + m = OrderedDict( + [ + ( + "Conv2d_block", + self.conv_block(self.total_reconstruct_filters, out, kernel_size=3), + ), + ("PixelShuffle", nn.PixelShuffle(self.upscale)), + ( + "Conv2d", + nn.Conv2d( + out_channel, color_channel, kernel_size=3, padding=1, bias=False + ), + ), + ] + ) + + return nn.Sequential(m) + + def forward(self, x): + # residual learning + lr, lr_up = x + feature = [] + for layer in self.feature_block.children(): + lr = layer(lr) + feature.append(lr) + feature = torch.cat(feature, dim=1) + + reconstruction = [ + layer(feature) for layer in self.reconstruction_block.children() + ] + reconstruction = torch.cat(reconstruction, dim=1) + + lr = self.up_sampler(reconstruction) + return lr + lr_up + + +# +++++++++++++++++++++++++++++++++++++ +# CARN +# ------------------------------------- + + +class CARN_Block(BaseModule): + def __init__( + self, + channels, + kernel_size=3, + padding=1, + dilation=1, + groups=1, + activation=nn.SELU(), + repeat=3, + SEBlock=False, + conv=nn.Conv2d, + single_conv_size=1, + single_conv_group=1, + ): + super(CARN_Block, self).__init__() + m = [] + for i in range(repeat): + m.append( + ResidualFixBlock( + channels, + channels, + kernel_size=kernel_size, + padding=padding, + dilation=dilation, + groups=groups, + activation=activation, + conv=conv, + ) + ) + if SEBlock: + m.append(SpatialChannelSqueezeExcitation(channels, reduction=channels)) + self.blocks = nn.Sequential(*m) + self.singles = nn.Sequential( + *[ + ConvBlock( + channels * (i + 2), + channels, + kernel_size=single_conv_size, + padding=(single_conv_size - 1) // 2, + groups=single_conv_group, + activation=activation, + conv=conv, + ) + for i in range(repeat) + ] + ) + + def forward(self, x): + c0 = x + for block, single in zip(self.blocks, self.singles): + b = block(x) + c0 = c = torch.cat([c0, b], dim=1) + x = single(c) + + return x + + +class CARN(BaseModule): + # Fast, Accurate, and Lightweight Super-Resolution with Cascading Residual Network + # https://github.com/nmhkahn/CARN-pytorch + def __init__( + self, + color_channels=3, + mid_channels=64, + scale=2, + activation=nn.SELU(), + num_blocks=3, + conv=nn.Conv2d, + ): + super(CARN, self).__init__() + + self.color_channels = color_channels + self.mid_channels = mid_channels + self.scale = scale + + self.entry_block = ConvBlock( + color_channels, + mid_channels, + kernel_size=3, + padding=1, + activation=activation, + conv=conv, + ) + self.blocks = nn.Sequential( + *[ + CARN_Block( + mid_channels, + kernel_size=3, + padding=1, + activation=activation, + conv=conv, + single_conv_size=1, + single_conv_group=1, + ) + for _ in range(num_blocks) + ] + ) + self.singles = nn.Sequential( + *[ + ConvBlock( + mid_channels * (i + 2), + mid_channels, + kernel_size=1, + padding=0, + activation=activation, + conv=conv, + ) + for i in range(num_blocks) + ] + ) + + self.upsampler = UpSampleBlock( + mid_channels, scale=scale, activation=activation, conv=conv + ) + self.exit_conv = conv(mid_channels, color_channels, kernel_size=3, padding=1) + + def forward(self, x): + x = self.entry_block(x) + c0 = x + for block, single in zip(self.blocks, self.singles): + b = block(x) + c0 = c = torch.cat([c0, b], dim=1) + x = single(c) + x = self.upsampler(x) + out = self.exit_conv(x) + return out + + +class CARN_V2(CARN): + def __init__( + self, + color_channels=3, + mid_channels=64, + scale=2, + activation=nn.LeakyReLU(0.1), + SEBlock=True, + conv=nn.Conv2d, + atrous=(1, 1, 1), + repeat_blocks=3, + single_conv_size=3, + single_conv_group=1, + ): + super(CARN_V2, self).__init__( + color_channels=color_channels, + mid_channels=mid_channels, + scale=scale, + activation=activation, + conv=conv, + ) + + num_blocks = len(atrous) + m = [] + for i in range(num_blocks): + m.append( + CARN_Block( + mid_channels, + kernel_size=3, + padding=1, + dilation=1, + activation=activation, + SEBlock=SEBlock, + conv=conv, + repeat=repeat_blocks, + single_conv_size=single_conv_size, + single_conv_group=single_conv_group, + ) + ) + + self.blocks = nn.Sequential(*m) + + self.singles = nn.Sequential( + *[ + ConvBlock( + mid_channels * (i + 2), + mid_channels, + kernel_size=single_conv_size, + padding=(single_conv_size - 1) // 2, + groups=single_conv_group, + activation=activation, + conv=conv, + ) + for i in range(num_blocks) + ] + ) + + def forward(self, x): + x = self.entry_block(x) + c0 = x + res = x + for block, single in zip(self.blocks, self.singles): + b = block(x) + c0 = c = torch.cat([c0, b], dim=1) + x = single(c) + x = x + res + x = self.upsampler(x) + out = self.exit_conv(x) + return out + + +# +++++++++++++++++++++++++++++++++++++ +# original Waifu2x model +# ------------------------------------- + + +class UpConv_7(BaseModule): + # https://github.com/nagadomi/waifu2x/blob/3c46906cb78895dbd5a25c3705994a1b2e873199/lib/srcnn.lua#L311 + def __init__(self): + super(UpConv_7, self).__init__() + self.act_fn = nn.LeakyReLU(0.1, inplace=False) + self.offset = 7 # because of 0 padding + from torch.nn import ZeroPad2d + + self.pad = ZeroPad2d(self.offset) + m = [ + nn.Conv2d(3, 16, 3, 1, 0), + self.act_fn, + nn.Conv2d(16, 32, 3, 1, 0), + self.act_fn, + nn.Conv2d(32, 64, 3, 1, 0), + self.act_fn, + nn.Conv2d(64, 128, 3, 1, 0), + self.act_fn, + nn.Conv2d(128, 128, 3, 1, 0), + self.act_fn, + nn.Conv2d(128, 256, 3, 1, 0), + self.act_fn, + # in_channels, out_channels, kernel_size, stride=1, padding=0, output_padding= + nn.ConvTranspose2d(256, 3, kernel_size=4, stride=2, padding=3, bias=False), + ] + self.Sequential = nn.Sequential(*m) + + def load_pre_train_weights(self, json_file): + with open(json_file) as f: + weights = json.load(f) + box = [] + for i in weights: + box.append(i["weight"]) + box.append(i["bias"]) + own_state = self.state_dict() + for index, (name, param) in enumerate(own_state.items()): + own_state[name].copy_(torch.FloatTensor(box[index])) + + def forward(self, x): + x = self.pad(x) + return self.Sequential.forward(x) + + +class Vgg_7(UpConv_7): + def __init__(self): + super(Vgg_7, self).__init__() + self.act_fn = nn.LeakyReLU(0.1, inplace=False) + self.offset = 7 + m = [ + nn.Conv2d(3, 32, 3, 1, 0), + self.act_fn, + nn.Conv2d(32, 32, 3, 1, 0), + self.act_fn, + nn.Conv2d(32, 64, 3, 1, 0), + self.act_fn, + nn.Conv2d(64, 64, 3, 1, 0), + self.act_fn, + nn.Conv2d(64, 128, 3, 1, 0), + self.act_fn, + nn.Conv2d(128, 128, 3, 1, 0), + self.act_fn, + nn.Conv2d(128, 3, 3, 1, 0), + ] + self.Sequential = nn.Sequential(*m) diff --git a/Waifu2x/Readme.md b/Waifu2x/Readme.md new file mode 100644 index 0000000000000000000000000000000000000000..bc528c3474faeff4784aecfc44c9fd8aeac092b6 --- /dev/null +++ b/Waifu2x/Readme.md @@ -0,0 +1,167 @@ +# Waifu2x + + Re-implementation on the original [waifu2x](https://github.com/nagadomi/waifu2x) in PyTorch with additional super resolution models. This repo is mainly used to explore interesting super resolution models. User-friendly tools may not be available now ><. + +## Dependencies +* Python 3x +* [PyTorch](https://pytorch.org/) >= 1 ( > 0.41 shall also work, but not guarantee) +* [Nvidia/Apex](https://github.com/NVIDIA/apex/) (used for mixed precision training, you may use the [python codes](https://github.com/NVIDIA/apex/tree/master/apex/fp16_utils) directly) + +Optinal: Nvidia GPU. Model inference (32 fp only) can run in cpu only. + +## What's New +* Add [CARN Model (Fast, Accurate, and Lightweight Super-Resolution with Cascading Residual Network)](https://github.com/nmhkahn/CARN-pytorch). Model Codes are adapted from the authors's [github repo](https://github.com/nmhkahn/CARN-pytorch). I add [Spatial Channel Squeeze Excitation](https://arxiv.org/abs/1709.01507) and swap all 1x1 convolution with 3x3 standard convolutions. The model is trained in fp 16 with Nvidia's [apex](https://github.com/NVIDIA/apex). Details and plots on model variant can be found in [docs/CARN](./docs/CARN) + +* Dilated Convolution seems less effective (if not make the model worse) in super resolution, though it brings some improvement in image segmentation, especially when dilated rate increases and then decreases. Further investigation is needed. + +## How to Use +Compare the input image and upscaled image +```python +from utils.prepare_images import * +from Models import * +from torchvision.utils import save_image +model_cran_v2 = CARN_V2(color_channels=3, mid_channels=64, conv=nn.Conv2d, + single_conv_size=3, single_conv_group=1, + scale=2, activation=nn.LeakyReLU(0.1), + SEBlock=True, repeat_blocks=3, atrous=(1, 1, 1)) + +model_cran_v2 = network_to_half(model_cran_v2) +checkpoint = "model_check_points/CRAN_V2/CARN_model_checkpoint.pt" +model_cran_v2.load_state_dict(torch.load(checkpoint, 'cpu')) +# if use GPU, then comment out the next line so it can use fp16. +model_cran_v2 = model_cran_v2.float() + +demo_img = "input_image.png" +img = Image.open(demo_img).convert("RGB") + +# origin +img_t = to_tensor(img).unsqueeze(0) + +# used to compare the origin +img = img.resize((img.size[0] // 2, img.size[1] // 2), Image.BICUBIC) + +# overlapping split +# if input image is too large, then split it into overlapped patches +# details can be found at [here](https://github.com/nagadomi/waifu2x/issues/238) +img_splitter = ImageSplitter(seg_size=64, scale_factor=2, boarder_pad_size=3) +img_patches = img_splitter.split_img_tensor(img, scale_method=None, img_pad=0) +with torch.no_grad(): + out = [model_cran_v2(i) for i in img_patches] +img_upscale = img_splitter.merge_img_tensor(out) + +final = torch.cat([img_t, img_upscale]) +save_image(final, 'out.png', nrow=2) +``` + + ## Training + + If possible, fp16 training is preferred because it is much faster with minimal quality decrease. + + Sample training script is available in `train.py`, but you may need to change some liens. + + ### Image Processing + Original images are all at least 3k x 3K. I downsample them by LANCZOS so that one side has at most 2048, then I randomly cut them into 256x256 patches as target and use 128x128 with jpeg noise as input images. All input patches have at least 14 kb, and they are stored in SQLite with BLOB format. SQlite seems to have [better performance](https://www.sqlite.org/intern-v-extern-blob.html) than file system for small objects. H5 file format may not be optimal because of its larger size. + + Although convolutions can take in any sizes of images, the content of image matters. For real life images, small patches may maintain color,brightness, etc variances in small regions, but for digital drawn images, colors are added in block areas. A small patch may end up showing entirely one color, and the model has little to learn. + + For example, the following two plots come from CARN and have the same settings, including initial parameters. Both training loss and ssim are lower for 64x64, but they perform worse in test time compared to 128x128. + + ![loss](docs/CARN/plots/128_vs_64_model_loss.png) + ![ssim](docs/CARN/plots/128_vs_64_model_ssim.png) + + +Downsampling methods are uniformly chosen among ```[PIL.Image.BILINEAR, PIL.Image.BICUBIC, PIL.Image.LANCZOS]``` , so different patches in the same image might be down-scaled in different ways. + +Image noise are from JPEG format only. They are added by re-encoding PNG images into PIL's JPEG data with various quality. Noise level 1 means quality ranges uniformly from [75, 95]; level 2 means quality ranges uniformly from [50, 75]. + + + ## Models + Models are tuned and modified with extra features. + + +* [DCSCN 12](https://github.com/jiny2001/dcscn-super-resolution) + +* [CRAN](https://github.com/nmhkahn/CARN-pytorch) + + #### From [Waifu2x](https://github.com/nagadomi/waifu2x) + * [Upconv7](https://github.com/nagadomi/waifu2x/blob/7d156917ae1113ab847dab15c75db7642231e7fa/lib/srcnn.lua#L360) + + * [Vgg_7](https://github.com/nagadomi/waifu2x/blob/7d156917ae1113ab847dab15c75db7642231e7fa/lib/srcnn.lua#L334) + + * [Cascaded Residual U-Net with SEBlock](https://github.com/nagadomi/waifu2x/blob/7d156917ae1113ab847dab15c75db7642231e7fa/lib/srcnn.lua#L514) (PyTorch codes are not available and under testing) + + #### Models Comparison + Images are from [Key: サマボケ(Summer Pocket)](http://key.visualarts.gr.jp/summer/). + + The left column is the original image, and the right column is bicubic, DCSCN, CRAN_V2 + +![img](docs/demo_bicubic_model_comparison.png) + + +![img](docs/demo_true_bicubic_dcscn_upconv.png) + + + + ##### Scores + The list will be updated after I add more models. + +Images are twitter icons (PNG) from [Key: サマボケ(Summer Pocket)](http://key.visualarts.gr.jp/summer/). They are cropped into non-overlapping 96x96 patches and down-scaled by 2. Then images are re-encoded into JPEG format with quality from [75, 95]. Scores are PSNR and MS-SSIM. + +| | Total Parameters | BICUBIC | Random* | +| :---: | :---: | :---: | :---: | +| CRAN V2| 2,149,607 | 34.0985 (0.9924) | 34.0509 (0.9922) | +| DCSCN 12 |1,889,974 | 31.5358 (0.9851) | 31.1457 (0.9834) | +| Upconv 7| 552,480| 31.4566 (0.9788) | 30.9492 (0.9772) | + +*uniformly select down scale methods from Image.BICUBIC, Image.BILINEAR, Image.LANCZOS. + + + + + + #### DCSCN +[Fast and Accurate Image Super Resolution by Deep CNN with Skip Connection and Network in Network](https://github.com/jiny2001/dcscn-super-resolution#fast-and-accurate-image-super-resolution-by-deep-cnn-with-skip-connection-and-network-in-network) + + DCSCN is very interesting as it has relatively quick forward computation, and both the shallow model (layerr 8) and deep model (layer 12) are quick to train. The settings are different from the paper. + + * I use exponential decay to decrease the number of feature filters in each layer. [Here](https://github.com/jiny2001/dcscn-super-resolution/blob/a868775930c6b36922897b0203468f3f1481e935/DCSCN.py#L204) is the original filter decay method. + + * I also increase the reconstruction filters from 48 to 128. + + * All activations are replaced by SELU. Dropout and weight decay are not added neither because they significantly increase the training time. + + * The loss function is changed from MSE to L1. + According to [Loss Functions for Image Restoration with Neural +Networks](https://www.google.com/url?sa=t&rct=j&q=&esrc=s&source=web&cd=4&cad=rja&uact=8&ved=0ahUKEwi7kuGt_7_bAhXrqVQKHRqhCcUQFghUMAM&url=http%3A%2F%2Fresearch.nvidia.com%2Fsites%2Fdefault%2Ffiles%2Fpubs%2F2017-03_Loss-Functions-for%2Fcomparison_tci.pdf&usg=AOvVaw1p0ndOKRH2ZaEsumO7d_bA), L1 seems to be more robust and converges faster than MSE. But the authors find the results from L1 and MSE are [similar](https://github.com/jiny2001/dcscn-super-resolution/issues/29). + + + I need to thank jiny2001 (one of the paper's author) to test the difference of SELU and PRELU. SELU seems more stable and has fewer parameters to train. It is a good drop in replacement + >layers=8, filters=96 and dataset=yang91+bsd200. + ![](docs/DCSCN_comparison/selu_prelu.png) + The details can be found in [here]( https://github.com/jiny2001/dcscn-super-resolution/issues/29). + + + + A pre-trained 12-layer model as well as model parameters are available. The model run time is around 3-5 times of Waifu2x. The output quality is usually visually indistinguishable, but its PSNR and SSIM are bit higher. Though, such comparison is not fair since the 12-layer model has around 1,889,974 parameters, 5 times more than waifu2x's Upconv_7 model. + + #### CARN + Channels are set to 64 across all blocks, so residual adds are very effective. Increase the channels to 128 lower the loss curve a little bit but doubles the total parameters from 0.9 Millions to 3 Millions. 32 Channels has much worse performance. Increasing the number of cascaded blocks from 3 to 5 doesn't lower the loss a lot. + + SE Blocks seems to have the most obvious improvement without increasing the computation a lot. Partial based padding seems have little effect if not decrease the quality. Atrous convolution is slower about 10%-20% than normal convolution in Pytorch 1.0, but there are no obvious improvement. + +Another more effective model is to add upscaled input image to the final convolution. A simple bilinear upscaled image seems sufficient. + +More examples on model configurations can be found in [docs/CARN folder](./docs/CARN/carn_plot_loss.md) + +![img](docs/CARN/plots/CARN_Compare.png) + +![img](docs/CARN/plots/CARN_Compare_Res_Add.png) + +### Waifu2x Original Models +Models can load waifu2x's pre-trained weights. The function ```forward_checkpoint``` sets the ```nn.LeakyReLU``` to compute data inplace. + +#### Upconv_7 +Original waifu2x's model. PyTorch's implementation with cpu only is around 5 times longer for large images. The output images have very close PSNR and SSIM scores compared to images generated from the [caffe version](https://github.com/lltcggie/waifu2x-caffe) , thought they are not identical. + +#### Vgg_7 +Not tested yet, but it is ready to use. diff --git a/Waifu2x/__init__.py b/Waifu2x/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..919c67429f059707b271b067f40783c04a42a5ac --- /dev/null +++ b/Waifu2x/__init__.py @@ -0,0 +1,9 @@ +# -*- coding: utf-8 -*- +# file: __init__.py +# time: 05/12/2022 +# author: yangheng +# github: https://github.com/yangheng95 +# huggingface: https://huggingface.co/yangheng +# google scholar: https://scholar.google.com/citations?user=NPq5a_0AAAAJ&hl=en +# Copyright (C) 2021. All Rights Reserved. +from .magnify import ImageMagnifier diff --git a/Waifu2x/magnify.py b/Waifu2x/magnify.py new file mode 100644 index 0000000000000000000000000000000000000000..96060b1e27355e15d8b432cec4b65f2ef6975c50 --- /dev/null +++ b/Waifu2x/magnify.py @@ -0,0 +1,99 @@ +# -*- coding: utf-8 -*- +# file: test.py +# time: 05/12/2022 +# author: yangheng +# github: https://github.com/yangheng95 +# huggingface: https://huggingface.co/yangheng +# google scholar: https://scholar.google.com/citations?user=NPq5a_0AAAAJ&hl=en +# Copyright (C) 2021. All Rights Reserved. +from pathlib import Path +from typing import Union + +import autocuda +import findfile +from pyabsa.utils.pyabsa_utils import fprint +from torchvision import transforms +from .utils.prepare_images import * +from .Models import * + + +class ImageMagnifier: + def __init__(self): + self.device = autocuda.auto_cuda() + self.model_cran_v2 = CARN_V2( + color_channels=3, + mid_channels=64, + conv=nn.Conv2d, + single_conv_size=3, + single_conv_group=1, + scale=2, + activation=nn.LeakyReLU(0.1), + SEBlock=True, + repeat_blocks=3, + atrous=(1, 1, 1), + ) + + self.model_cran_v2 = network_to_half(self.model_cran_v2) + self.checkpoint = findfile.find_cwd_file("CARN_model_checkpoint.pt") + self.model_cran_v2.load_state_dict( + torch.load(self.checkpoint, map_location="cpu") + ) + # if use GPU, then comment out the next line so it can use fp16. + self.model_cran_v2 = self.model_cran_v2.float().to(self.device) + self.model_cran_v2.to(self.device) + + def __image_scale(self, img, scale_factor: int = 2): + img_splitter = ImageSplitter( + seg_size=64, scale_factor=scale_factor, boarder_pad_size=3 + ) + img_patches = img_splitter.split_img_tensor(img, scale_method=None, img_pad=0) + with torch.no_grad(): + if self.device != "cpu": + with torch.cuda.amp.autocast(): + out = [self.model_cran_v2(i.to(self.device)) for i in img_patches] + else: + with torch.cpu.amp.autocast(): + out = [self.model_cran_v2(i) for i in img_patches] + img_upscale = img_splitter.merge_img_tensor(out) + + final = torch.cat([img_upscale]) + + return transforms.ToPILImage()(final[0]) + + def magnify(self, img, scale_factor: int = 2): + fprint("scale factor reset to:", scale_factor // 2 * 2) + _scale_factor = scale_factor + while _scale_factor // 2 > 0: + img = self.__image_scale(img, scale_factor=2) + _scale_factor = _scale_factor // 2 + return img + + def magnify_from_file( + self, img_path: Union[str, Path], scale_factor: int = 2, save_img: bool = True + ): + + if not os.path.exists(img_path): + raise FileNotFoundError("Path is not found.") + if os.path.isfile(img_path): + try: + img = Image.open(img_path) + img = self.magnify(img, scale_factor) + if save_img: + img.save(os.path.join(img_path)) + except Exception as e: + fprint(img_path, e) + fprint(img_path, "Done.") + + elif os.path.isdir(img_path): + for path in os.listdir(img_path): + try: + img = Image.open(os.path.join(img_path, path)) + img = self.magnify(img, scale_factor) + if save_img: + img.save(os.path.join(img_path, path)) + except Exception as e: + fprint(path, e) + continue + fprint(path, "Done.") + else: + raise TypeError("Path is not a file or directory.") diff --git a/Waifu2x/model_check_points/CRAN_V2/CARN_model_checkpoint.pt b/Waifu2x/model_check_points/CRAN_V2/CARN_model_checkpoint.pt new file mode 100644 index 0000000000000000000000000000000000000000..028dde9b4f952a24e9c86a78d9c8cc0ae185b51b --- /dev/null +++ b/Waifu2x/model_check_points/CRAN_V2/CARN_model_checkpoint.pt @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:3a0ef4fdea5b0b2a91b05b7a39fe63df3e27e1d18df477065e7f268a7feaaad2 +size 4329165 diff --git a/Waifu2x/model_check_points/CRAN_V2/ReadME.md b/Waifu2x/model_check_points/CRAN_V2/ReadME.md new file mode 100644 index 0000000000000000000000000000000000000000..e432a1c7bd5de45f086ba1fd6b06ca712a1d806b --- /dev/null +++ b/Waifu2x/model_check_points/CRAN_V2/ReadME.md @@ -0,0 +1,34 @@ +# Resume & Use Model Check Points + +This folder contains check points for models and their weights. They are generated from [PyTorch's pickle](https://pytorch.org/docs/master/notes/serialization.html). + +Model specifications are in each folder's ReadME. + +Pickle names with "model" contain the entire models, and they can be used as an freeze module by calling the "forward_checkpoint" function to generate images. + +Example: +```python +import torch +# No need to reconstruct the model +model = torch.load("./DCSCN/DCSCN_model_387epos_L12_noise_1.pt") +x = torch.randn((1,3,10,10)), torch.randn((1,3,20,20)) +out = model.forward_checkpoint(a) +``` + +Pickle names with "weights" are model weights, and they are named dictionaries. + +Example: +```python +model = DCSCN(*) # the setting must be the same to load check points weights. +model.load_state_dict(torch.load("./DCSCN/DCSCN_weights_387epos_L12_noise_1.pt")) +# then you can resume the model training +``` + +Model check poins in Upconv_7 and vgg_7 are from [waifu2x's repo](https://github.com/nagadomi/waifu2x/tree/master/models). To load weights into a model, please use ```load_pre_train_weights``` function. + +Example: +```python +model = UpConv_7() +model.load_pre_train_weights(json_file=...) +# then the model is ready to use +``` diff --git a/Waifu2x/model_check_points/ReadME.md b/Waifu2x/model_check_points/ReadME.md new file mode 100644 index 0000000000000000000000000000000000000000..e432a1c7bd5de45f086ba1fd6b06ca712a1d806b --- /dev/null +++ b/Waifu2x/model_check_points/ReadME.md @@ -0,0 +1,34 @@ +# Resume & Use Model Check Points + +This folder contains check points for models and their weights. They are generated from [PyTorch's pickle](https://pytorch.org/docs/master/notes/serialization.html). + +Model specifications are in each folder's ReadME. + +Pickle names with "model" contain the entire models, and they can be used as an freeze module by calling the "forward_checkpoint" function to generate images. + +Example: +```python +import torch +# No need to reconstruct the model +model = torch.load("./DCSCN/DCSCN_model_387epos_L12_noise_1.pt") +x = torch.randn((1,3,10,10)), torch.randn((1,3,20,20)) +out = model.forward_checkpoint(a) +``` + +Pickle names with "weights" are model weights, and they are named dictionaries. + +Example: +```python +model = DCSCN(*) # the setting must be the same to load check points weights. +model.load_state_dict(torch.load("./DCSCN/DCSCN_weights_387epos_L12_noise_1.pt")) +# then you can resume the model training +``` + +Model check poins in Upconv_7 and vgg_7 are from [waifu2x's repo](https://github.com/nagadomi/waifu2x/tree/master/models). To load weights into a model, please use ```load_pre_train_weights``` function. + +Example: +```python +model = UpConv_7() +model.load_pre_train_weights(json_file=...) +# then the model is ready to use +``` diff --git a/Waifu2x/train.py b/Waifu2x/train.py new file mode 100644 index 0000000000000000000000000000000000000000..e3887e16bc17d833ca578abb049929063f30d902 --- /dev/null +++ b/Waifu2x/train.py @@ -0,0 +1,204 @@ +from torch import optim +from torch.utils.data import DataLoader +from torchvision.utils import save_image +from tqdm import trange + +from Dataloader import * +from .utils import image_quality +from .utils.cls import CyclicLR +from .utils.prepare_images import * + +train_folder = "./dataset/train" +test_folder = "./dataset/test" + +img_dataset = ImageDBData( + db_file="dataset/images.db", + db_table="train_images_size_128_noise_1_rgb", + max_images=24, +) +img_data = DataLoader(img_dataset, batch_size=6, shuffle=True, num_workers=6) + +total_batch = len(img_data) +print(len(img_dataset)) + +test_dataset = ImageDBData( + db_file="dataset/test2.db", + db_table="test_images_size_128_noise_1_rgb", + max_images=None, +) +num_test = len(test_dataset) +test_data = DataLoader(test_dataset, batch_size=1, shuffle=False, num_workers=1) + +criteria = nn.L1Loss() + +model = CARN_V2( + color_channels=3, + mid_channels=64, + conv=nn.Conv2d, + single_conv_size=3, + single_conv_group=1, + scale=2, + activation=nn.LeakyReLU(0.1), + SEBlock=True, + repeat_blocks=3, + atrous=(1, 1, 1), +) + +model.total_parameters() + + +# model.initialize_weights_xavier_uniform() + +# fp16 training is available in GPU only +model = network_to_half(model) +model = model.cuda() +model.load_state_dict(torch.load("CARN_model_checkpoint.pt")) + +learning_rate = 1e-4 +weight_decay = 1e-6 +optimizer = optim.Adam( + model.parameters(), lr=learning_rate, weight_decay=weight_decay, amsgrad=True +) +# optimizer = optim.SGD(model.parameters(), momentum=0.9, nesterov=True, weight_decay=weight_decay, lr=learning_rate) + +# optimizer = FP16_Optimizer(optimizer, static_loss_scale=128.0, verbose=False) +# optimizer.load_state_dict(torch.load("CARN_adam_checkpoint.pt")) + +last_iter = -1 # torch.load("CARN_scheduler_last_iter") +scheduler = CyclicLR( + optimizer, + base_lr=1e-4, + max_lr=1e-4, + step_size=3 * total_batch, + mode="triangular", + last_batch_iteration=last_iter, +) +train_loss = [] +train_ssim = [] +train_psnr = [] + +test_loss = [] +test_ssim = [] +test_psnr = [] + +# train_loss = torch.load("train_loss.pt") +# train_ssim = torch.load("train_ssim.pt") +# train_psnr = torch.load("train_psnr.pt") +# +# test_loss = torch.load("test_loss.pt") +# test_ssim = torch.load("test_ssim.pt") +# test_psnr = torch.load("test_psnr.pt") + + +counter = 0 +iteration = 2 +ibar = trange( + iteration, + ascii=True, + maxinterval=1, + postfix={"avg_loss": 0, "train_ssim": 0, "test_ssim": 0}, +) +for i in ibar: + # batch_loss = [] + # insample_ssim = [] + # insample_psnr = [] + for index, batch in enumerate(img_data): + scheduler.batch_step() + lr_img, hr_img = batch + lr_img = lr_img.cuda().half() + hr_img = hr_img.cuda() + + # model.zero_grad() + optimizer.zero_grad() + outputs = model.forward(lr_img) + outputs = outputs.float() + loss = criteria(outputs, hr_img) + # loss.backward() + optimizer.backward(loss) + # nn.utils.clip_grad_norm_(model.parameters(), 5) + optimizer.step() + + counter += 1 + # train_loss.append(loss.item()) + + ssim = image_quality.msssim(outputs, hr_img).item() + psnr = image_quality.psnr(outputs, hr_img).item() + + ibar.set_postfix( + ratio=index / total_batch, + loss=loss.item(), + ssim=ssim, + batch=index, + psnr=psnr, + lr=scheduler.current_lr, + ) + train_loss.append(loss.item()) + train_ssim.append(ssim) + train_psnr.append(psnr) + + # +++++++++++++++++++++++++++++++++++++ + # save checkpoints by iterations + # ------------------------------------- + + if (counter + 1) % 500 == 0: + torch.save(model.state_dict(), "CARN_model_checkpoint.pt") + torch.save(optimizer.state_dict(), "CARN_adam_checkpoint.pt") + torch.save(train_loss, "train_loss.pt") + torch.save(train_ssim, "train_ssim.pt") + torch.save(train_psnr, "train_psnr.pt") + torch.save(scheduler.last_batch_iteration, "CARN_scheduler_last_iter.pt") + + # +++++++++++++++++++++++++++++++++++++ + # End of One Epoch + # ------------------------------------- + + # one_ite_loss = np.mean(batch_loss) + # one_ite_ssim = np.mean(insample_ssim) + # one_ite_psnr = np.mean(insample_psnr) + + # print(f"One iteration loss {one_ite_loss}, ssim {one_ite_ssim}, psnr {one_ite_psnr}") + # train_loss.append(one_ite_loss) + # train_ssim.append(one_ite_ssim) + # train_psnr.append(one_ite_psnr) + + torch.save(model.state_dict(), "CARN_model_checkpoint.pt") + # torch.save(scheduler, "CARN_scheduler_optim.pt") + torch.save(optimizer.state_dict(), "CARN_adam_checkpoint.pt") + torch.save(train_loss, "train_loss.pt") + torch.save(train_ssim, "train_ssim.pt") + torch.save(train_psnr, "train_psnr.pt") + # torch.save(scheduler.last_batch_iteration, "CARN_scheduler_last_iter.pt") + + # +++++++++++++++++++++++++++++++++++++ + # Test + # ------------------------------------- + + with torch.no_grad(): + ssim = [] + batch_loss = [] + psnr = [] + for index, test_batch in enumerate(test_data): + lr_img, hr_img = test_batch + lr_img = lr_img.cuda() + hr_img = hr_img.cuda() + + lr_img_up = model(lr_img) + lr_img_up = lr_img_up.float() + loss = criteria(lr_img_up, hr_img) + + save_image([lr_img_up[0], hr_img[0]], f"check_test_imgs/{index}.png") + batch_loss.append(loss.item()) + ssim.append(image_quality.msssim(lr_img_up, hr_img).item()) + psnr.append(image_quality.psnr(lr_img_up, hr_img).item()) + + test_ssim.append(np.mean(ssim)) + test_loss.append(np.mean(batch_loss)) + test_psnr.append(np.mean(psnr)) + + torch.save(test_loss, "test_loss.pt") + torch.save(test_ssim, "test_ssim.pt") + torch.save(test_psnr, "test_psnr.pt") + +# import subprocess + +# subprocess.call(["shutdown", "/s"]) diff --git a/Waifu2x/utils/Img_to_H5.py b/Waifu2x/utils/Img_to_H5.py new file mode 100644 index 0000000000000000000000000000000000000000..fde0a149ddd3caad82226f4ed24a37916008b8db --- /dev/null +++ b/Waifu2x/utils/Img_to_H5.py @@ -0,0 +1,57 @@ +import glob + +import h5py +from PIL import Image +from torchvision.transforms import RandomCrop +from torchvision.transforms.functional import to_tensor +from tqdm import tqdm + +from Dataloader import ImageAugment + +patch_size = 128 +shrink_size = 2 +noise_level = 1 +patches_per_img = 20 +images = glob.glob("dataset/train/*") + +database = h5py.File("train_images.hdf5", "w") + +dat_group = database.create_group("shrink_2_noise_level_1_downsample_random_rgb") +# del database['shrink_2_noise_level_1_downsample_random'] +storage_lr = dat_group.create_dataset( + "train_lr", + shape=( + patches_per_img * len(images), + 3, + patch_size // shrink_size, + patch_size // shrink_size, + ), + dtype="float32", + # compression='lzf', +) +storage_hr = dat_group.create_dataset( + "train_hr", + shape=(patches_per_img * len(images), 3, patch_size, patch_size), + # compression='lzf', + dtype="float32", +) + +random_cropper = RandomCrop(size=patch_size) +img_augmenter = ImageAugment(shrink_size, noise_level, down_sample_method=None) + + +def get_img_patches(img_pil): + img_patch = random_cropper(img_pil) + lr_hr_patches = img_augmenter.process(img_patch) + return lr_hr_patches + + +counter = 0 +for img in tqdm(images): + img_pil = Image.open(img).convert("RGB") + for i in range(patches_per_img): + patch = get_img_patches(img_pil) + storage_lr[counter] = to_tensor(patch[0].convert("RGB")).numpy() + storage_hr[counter] = to_tensor(patch[1].convert("RGB")).numpy() + counter += 1 +database.close() diff --git a/Waifu2x/utils/__init__.py b/Waifu2x/utils/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..fb1623a14865e1d1b1e79275a3d5595642f92d9b --- /dev/null +++ b/Waifu2x/utils/__init__.py @@ -0,0 +1,8 @@ +# -*- coding: utf-8 -*- +# file: __init__.py +# time: 05/12/2022 +# author: yangheng +# github: https://github.com/yangheng95 +# huggingface: https://huggingface.co/yangheng +# google scholar: https://scholar.google.com/citations?user=NPq5a_0AAAAJ&hl=en +# Copyright (C) 2021. All Rights Reserved. diff --git a/Waifu2x/utils/cls.py b/Waifu2x/utils/cls.py new file mode 100644 index 0000000000000000000000000000000000000000..ed9ca9bd4d78341d622acb0bd469339be81530e2 --- /dev/null +++ b/Waifu2x/utils/cls.py @@ -0,0 +1,171 @@ +# This code is copied from https://github.com/thomasjpfan/pytorch/blob/401ec389db2c9d2978917a6e4d1101b20340d7e7/torch/optim/lr_scheduler.py + + +# This code is under review at PyTorch and is to be merged eventually to make CLR available to all. +# Tested with pytorch 0.2.0 + +import numpy as np + + +class CyclicLR(object): + """Sets the learning rate of each parameter group according to + cyclical learning rate policy (CLR). The policy cycles the learning + rate between two boundaries with a constant frequency, as detailed in + the paper `Cyclical Learning Rates for Training Neural Networks`_. + The distance between the two boundaries can be scaled on a per-iteration + or per-cycle basis. + Cyclical learning rate policy changes the learning rate after every batch. + `batch_step` should be called after a batch has been used for training. + To resume training, save `last_batch_iteration` and use it to instantiate `CycleLR`. + This class has three built-in policies, as put forth in the paper: + "triangular": + A basic triangular cycle w/ no amplitude scaling. + "triangular2": + A basic triangular cycle that scales initial amplitude by half each cycle. + "exp_range": + A cycle that scales initial amplitude by gamma**(cycle iterations) at each + cycle iteration. + This implementation was adapted from the github repo: `bckenstler/CLR`_ + Args: + optimizer (Optimizer): Wrapped optimizer. + base_lr (float or list): Initial learning rate which is the + lower boundary in the cycle for eachparam groups. + Default: 0.001 + max_lr (float or list): Upper boundaries in the cycle for + each parameter group. Functionally, + it defines the cycle amplitude (max_lr - base_lr). + The lr at any cycle is the sum of base_lr + and some scaling of the amplitude; therefore + max_lr may not actually be reached depending on + scaling function. Default: 0.006 + step_size (int): Number of training iterations per + half cycle. Authors suggest setting step_size + 2-8 x training iterations in epoch. Default: 2000 + mode (str): One of {triangular, triangular2, exp_range}. + Values correspond to policies detailed above. + If scale_fn is not None, this argument is ignored. + Default: 'triangular' + gamma (float): Constant in 'exp_range' scaling function: + gamma**(cycle iterations) + Default: 1.0 + scale_fn (function): Custom scaling policy defined by a single + argument lambda function, where + 0 <= scale_fn(x) <= 1 for all x >= 0. + mode paramater is ignored + Default: None + scale_mode (str): {'cycle', 'iterations'}. + Defines whether scale_fn is evaluated on + cycle number or cycle iterations (training + iterations since start of cycle). + Default: 'cycle' + last_batch_iteration (int): The index of the last batch. Default: -1 + Example: + >>> optimizer = torch.optim.SGD(model.parameters(), lr=0.1, momentum=0.9) + >>> scheduler = torch.optim.CyclicLR(optimizer) + >>> data_loader = torch.utils.data.DataLoader(...) + >>> for epoch in range(10): + >>> for batch in data_loader: + >>> scheduler.batch_step() + >>> train_batch(...) + .. _Cyclical Learning Rates for Training Neural Networks: https://arxiv.org/abs/1506.01186 + .. _bckenstler/CLR: https://github.com/bckenstler/CLR + """ + + def __init__( + self, + optimizer, + base_lr=1e-3, + max_lr=6e-3, + step_size=2000, + mode="triangular", + gamma=1.0, + scale_fn=None, + scale_mode="cycle", + last_batch_iteration=-1, + ): + + # if not isinstance(optimizer, Optimizer): + # raise TypeError('{} is not an Optimizer'.format( + # type(optimizer).__name__)) + self.optimizer = optimizer + + if isinstance(base_lr, list) or isinstance(base_lr, tuple): + if len(base_lr) != len(optimizer.param_groups): + raise ValueError( + "expected {} base_lr, got {}".format( + len(optimizer.param_groups), len(base_lr) + ) + ) + self.base_lrs = list(base_lr) + else: + self.base_lrs = [base_lr] * len(optimizer.param_groups) + + if isinstance(max_lr, list) or isinstance(max_lr, tuple): + if len(max_lr) != len(optimizer.param_groups): + raise ValueError( + "expected {} max_lr, got {}".format( + len(optimizer.param_groups), len(max_lr) + ) + ) + self.max_lrs = list(max_lr) + else: + self.max_lrs = [max_lr] * len(optimizer.param_groups) + + self.step_size = step_size + + if mode not in ["triangular", "triangular2", "exp_range"] and scale_fn is None: + raise ValueError("mode is invalid and scale_fn is None") + + self.mode = mode + self.gamma = gamma + self.current_lr = None + + if scale_fn is None: + if self.mode == "triangular": + self.scale_fn = self._triangular_scale_fn + self.scale_mode = "cycle" + elif self.mode == "triangular2": + self.scale_fn = self._triangular2_scale_fn + self.scale_mode = "cycle" + elif self.mode == "exp_range": + self.scale_fn = self._exp_range_scale_fn + self.scale_mode = "iterations" + else: + self.scale_fn = scale_fn + self.scale_mode = scale_mode + + self.batch_step(last_batch_iteration + 1) + self.last_batch_iteration = last_batch_iteration + + def batch_step(self, batch_iteration=None): + if batch_iteration is None: + batch_iteration = self.last_batch_iteration + 1 + self.last_batch_iteration = batch_iteration + for param_group, lr in zip(self.optimizer.param_groups, self.get_lr()): + param_group["lr"] = lr + self.current_lr = lr + + def _triangular_scale_fn(self, x): + return 1.0 + + def _triangular2_scale_fn(self, x): + return 1 / (2.0 ** (x - 1)) + + def _exp_range_scale_fn(self, x): + return self.gamma ** (x) + + def get_lr(self): + step_size = float(self.step_size) + cycle = np.floor(1 + self.last_batch_iteration / (2 * step_size)) + x = np.abs(self.last_batch_iteration / step_size - 2 * cycle + 1) + + lrs = [] + param_lrs = zip(self.optimizer.param_groups, self.base_lrs, self.max_lrs) + for param_group, base_lr, max_lr in param_lrs: + base_height = (max_lr - base_lr) * np.maximum(0, (1 - x)) + if self.scale_mode == "cycle": + lr = base_lr + base_height * self.scale_fn(cycle) + else: + lr = base_lr + base_height * self.scale_fn(self.last_batch_iteration) + lrs.append(lr) + return lrs diff --git a/Waifu2x/utils/image_quality.py b/Waifu2x/utils/image_quality.py new file mode 100644 index 0000000000000000000000000000000000000000..c7bf0e51cac541f1872e1bc82ff359c3b2b2fdaa --- /dev/null +++ b/Waifu2x/utils/image_quality.py @@ -0,0 +1,191 @@ +# Pytorch Multi-Scale Structural Similarity Index (SSIM) +# This code is written by jorge-pessoa (https://github.com/jorge-pessoa/pytorch-msssim) +# MIT licence +import math +from math import exp + +import torch +import torch.nn.functional as F +from torch.autograd import Variable + + +# +++++++++++++++++++++++++++++++++++++ +# SSIM +# ------------------------------------- + + +def gaussian(window_size, sigma): + gauss = torch.Tensor( + [ + exp(-((x - window_size // 2) ** 2) / float(2 * sigma**2)) + for x in range(window_size) + ] + ) + return gauss / gauss.sum() + + +def create_window(window_size, channel): + _1D_window = gaussian(window_size, 1.5).unsqueeze(1) + _2D_window = _1D_window.mm(_1D_window.t()).float().unsqueeze(0).unsqueeze(0) + window = Variable( + _2D_window.expand(channel, 1, window_size, window_size).contiguous() + ) + return window + + +def _ssim(img1, img2, window, window_size, channel, size_average=True, full=False): + padd = 0 + + mu1 = F.conv2d(img1, window, padding=padd, groups=channel) + mu2 = F.conv2d(img2, window, padding=padd, groups=channel) + + mu1_sq = mu1.pow(2) + mu2_sq = mu2.pow(2) + mu1_mu2 = mu1 * mu2 + + sigma1_sq = F.conv2d(img1 * img1, window, padding=padd, groups=channel) - mu1_sq + sigma2_sq = F.conv2d(img2 * img2, window, padding=padd, groups=channel) - mu2_sq + sigma12 = F.conv2d(img1 * img2, window, padding=padd, groups=channel) - mu1_mu2 + + C1 = 0.01**2 + C2 = 0.03**2 + + ssim_map = ((2 * mu1_mu2 + C1) * (2 * sigma12 + C2)) / ( + (mu1_sq + mu2_sq + C1) * (sigma1_sq + sigma2_sq + C2) + ) + + v1 = 2.0 * sigma12 + C2 + v2 = sigma1_sq + sigma2_sq + C2 + cs = torch.mean(v1 / v2) + + if size_average: + ret = ssim_map.mean() + else: + ret = ssim_map.mean(1).mean(1).mean(1) + + if full: + return ret, cs + return ret + + +class SSIM(torch.nn.Module): + def __init__(self, window_size=11, size_average=True): + super(SSIM, self).__init__() + self.window_size = window_size + self.size_average = size_average + self.channel = 1 + self.window = create_window(window_size, self.channel) + + def forward(self, img1, img2): + (_, channel, _, _) = img1.size() + + if channel == self.channel and self.window.data.type() == img1.data.type(): + window = self.window + else: + window = create_window(self.window_size, channel) + + if img1.is_cuda: + window = window.cuda(img1.get_device()) + window = window.type_as(img1) + + self.window = window + self.channel = channel + + return _ssim(img1, img2, window, self.window_size, channel, self.size_average) + + +def ssim(img1, img2, window_size=11, size_average=True, full=False): + (_, channel, height, width) = img1.size() + + real_size = min(window_size, height, width) + window = create_window(real_size, channel) + + if img1.is_cuda: + window = window.cuda(img1.get_device()) + window = window.type_as(img1) + + return _ssim(img1, img2, window, real_size, channel, size_average, full=full) + + +def msssim(img1, img2, window_size=11, size_average=True): + # TODO: fix NAN results + if img1.size() != img2.size(): + raise RuntimeError( + "Input images must have the same shape (%s vs. %s)." + % (img1.size(), img2.size()) + ) + if len(img1.size()) != 4: + raise RuntimeError( + "Input images must have four dimensions, not %d" % len(img1.size()) + ) + + weights = torch.tensor([0.0448, 0.2856, 0.3001, 0.2363, 0.1333], dtype=img1.dtype) + if img1.is_cuda: + weights = weights.cuda(img1.get_device()) + + levels = weights.size()[0] + mssim = [] + mcs = [] + for _ in range(levels): + sim, cs = ssim( + img1, img2, window_size=window_size, size_average=size_average, full=True + ) + mssim.append(sim) + mcs.append(cs) + + img1 = F.avg_pool2d(img1, (2, 2)) + img2 = F.avg_pool2d(img2, (2, 2)) + + mssim = torch.stack(mssim) + mcs = torch.stack(mcs) + return torch.prod(mcs[0 : levels - 1] ** weights[0 : levels - 1]) * ( + mssim[levels - 1] ** weights[levels - 1] + ) + + +class MSSSIM(torch.nn.Module): + def __init__(self, window_size=11, size_average=True, channel=3): + super(MSSSIM, self).__init__() + self.window_size = window_size + self.size_average = size_average + self.channel = channel + + def forward(self, img1, img2): + # TODO: store window between calls if possible + return msssim( + img1, img2, window_size=self.window_size, size_average=self.size_average + ) + + +def calc_psnr(sr, hr, scale=0, benchmark=False): + # adapt from EDSR: https://github.com/thstkdgus35/EDSR-PyTorch + diff = (sr - hr).data + if benchmark: + shave = scale + if diff.size(1) > 1: + convert = diff.new(1, 3, 1, 1) + convert[0, 0, 0, 0] = 65.738 + convert[0, 1, 0, 0] = 129.057 + convert[0, 2, 0, 0] = 25.064 + diff.mul_(convert).div_(256) + diff = diff.sum(dim=1, keepdim=True) + else: + shave = scale + 6 + + valid = diff[:, :, shave:-shave, shave:-shave] + mse = valid.pow(2).mean() + + return -10 * math.log10(mse) + + +# +++++++++++++++++++++++++++++++++++++ +# PSNR +# ------------------------------------- +from torch import nn + + +def psnr(predict, target): + with torch.no_grad(): + criteria = nn.MSELoss() + mse = criteria(predict, target) + return -10 * torch.log10(mse) diff --git a/Waifu2x/utils/prepare_images.py b/Waifu2x/utils/prepare_images.py new file mode 100644 index 0000000000000000000000000000000000000000..701e894ee828b704be3d0c73400b0326b26a697f --- /dev/null +++ b/Waifu2x/utils/prepare_images.py @@ -0,0 +1,143 @@ +import copy +import glob +import os +from multiprocessing.dummy import Pool as ThreadPool + +from PIL import Image +from torchvision.transforms.functional import to_tensor + +from ..Models import * + + +class ImageSplitter: + # key points: + # Boarder padding and over-lapping img splitting to avoid the instability of edge value + # Thanks Waifu2x's autorh nagadomi for suggestions (https://github.com/nagadomi/waifu2x/issues/238) + + def __init__(self, seg_size=48, scale_factor=2, boarder_pad_size=3): + self.seg_size = seg_size + self.scale_factor = scale_factor + self.pad_size = boarder_pad_size + self.height = 0 + self.width = 0 + self.upsampler = nn.Upsample(scale_factor=scale_factor, mode="bilinear") + + def split_img_tensor(self, pil_img, scale_method=Image.BILINEAR, img_pad=0): + # resize image and convert them into tensor + img_tensor = to_tensor(pil_img).unsqueeze(0) + img_tensor = nn.ReplicationPad2d(self.pad_size)(img_tensor) + batch, channel, height, width = img_tensor.size() + self.height = height + self.width = width + + if scale_method is not None: + img_up = pil_img.resize( + (2 * pil_img.size[0], 2 * pil_img.size[1]), scale_method + ) + img_up = to_tensor(img_up).unsqueeze(0) + img_up = nn.ReplicationPad2d(self.pad_size * self.scale_factor)(img_up) + + patch_box = [] + # avoid the residual part is smaller than the padded size + if ( + height % self.seg_size < self.pad_size + or width % self.seg_size < self.pad_size + ): + self.seg_size += self.scale_factor * self.pad_size + + # split image into over-lapping pieces + for i in range(self.pad_size, height, self.seg_size): + for j in range(self.pad_size, width, self.seg_size): + part = img_tensor[ + :, + :, + (i - self.pad_size) : min( + i + self.pad_size + self.seg_size, height + ), + (j - self.pad_size) : min(j + self.pad_size + self.seg_size, width), + ] + if img_pad > 0: + part = nn.ZeroPad2d(img_pad)(part) + if scale_method is not None: + # part_up = self.upsampler(part) + part_up = img_up[ + :, + :, + self.scale_factor + * (i - self.pad_size) : min( + i + self.pad_size + self.seg_size, height + ) + * self.scale_factor, + self.scale_factor + * (j - self.pad_size) : min( + j + self.pad_size + self.seg_size, width + ) + * self.scale_factor, + ] + + patch_box.append((part, part_up)) + else: + patch_box.append(part) + return patch_box + + def merge_img_tensor(self, list_img_tensor): + out = torch.zeros( + (1, 3, self.height * self.scale_factor, self.width * self.scale_factor) + ) + img_tensors = copy.copy(list_img_tensor) + rem = self.pad_size * 2 + + pad_size = self.scale_factor * self.pad_size + seg_size = self.scale_factor * self.seg_size + height = self.scale_factor * self.height + width = self.scale_factor * self.width + for i in range(pad_size, height, seg_size): + for j in range(pad_size, width, seg_size): + part = img_tensors.pop(0) + part = part[:, :, rem:-rem, rem:-rem] + # might have error + if len(part.size()) > 3: + _, _, p_h, p_w = part.size() + out[:, :, i : i + p_h, j : j + p_w] = part + # out[:,:, + # self.scale_factor*i:self.scale_factor*i+p_h, + # self.scale_factor*j:self.scale_factor*j+p_w] = part + out = out[:, :, rem:-rem, rem:-rem] + return out + + +def load_single_image( + img_file, + up_scale=False, + up_scale_factor=2, + up_scale_method=Image.BILINEAR, + zero_padding=False, +): + img = Image.open(img_file).convert("RGB") + out = to_tensor(img).unsqueeze(0) + if zero_padding: + out = nn.ZeroPad2d(zero_padding)(out) + if up_scale: + size = tuple(map(lambda x: x * up_scale_factor, img.size)) + img_up = img.resize(size, up_scale_method) + img_up = to_tensor(img_up).unsqueeze(0) + out = (out, img_up) + + return out + + +def standardize_img_format(img_folder): + def process(img_file): + img_path = os.path.dirname(img_file) + img_name, _ = os.path.basename(img_file).split(".") + out = os.path.join(img_path, img_name + ".JPEG") + os.rename(img_file, out) + + list_imgs = [] + for i in ["png", "jpeg", "jpg"]: + list_imgs.extend(glob.glob(img_folder + "**/*." + i, recursive=True)) + print("Found {} images.".format(len(list_imgs))) + pool = ThreadPool(4) + pool.map(process, list_imgs) + pool.close() + pool.join() diff --git a/api.py b/api.py new file mode 100644 index 0000000000000000000000000000000000000000..08317b4eba5c62ae17646f121c0f0758b2592917 --- /dev/null +++ b/api.py @@ -0,0 +1,35 @@ +# -*- coding: utf-8 -*- +# file: api.py.py +# time: 20:37 2022/12/6 +# author: yangheng +# github: https://github.com/yangheng95 +# huggingface: https://huggingface.co/yangheng +# google scholar: https://scholar.google.com/citations?user=NPq5a_0AAAAJ&hl=en +# Copyright (C) 2021. All Rights Reserved. +import requests +from PIL import Image +from io import BytesIO + +response = requests.post( + "https://yangheng-super-resolution-anime-diffusion.hf.space/run/generate", + json={ + "data": [ + "anything v3", + "girl,lovely,cute,beautiful eyes,cumulonimbus clouds,sky,detailed fingers,pants,red hair,blue eyes,flower meadow,Elif", + 7.5, + 15, + 512, + 512, + 0, + "data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAAEAAAABCAYAAAAfFcSJAAAACklEQVR4nGMAAQAABQABDQottAAAAABJRU5ErkJggg==", + 0.5, + "", + 2, + ] + }, + timeout=3000, +) + +img = Image.open(BytesIO(response.content)) +img.show() +img.save("test_api.png") diff --git a/app.py b/app.py new file mode 100644 index 0000000000000000000000000000000000000000..1c732340756e7706fe399c68d6908469fe489fcb --- /dev/null +++ b/app.py @@ -0,0 +1,601 @@ +import os +import random +import zipfile +import findfile +import PIL.Image +import autocuda +from pyabsa.utils.pyabsa_utils import fprint + +try: + for z_file in findfile.find_cwd_files(and_key=['.zip'], + exclude_key=['.ignore', 'git', 'SuperResolutionAnimeDiffusion'], + recursive=10): + fprint(f"Extracting {z_file}...") + with zipfile.ZipFile(z_file, 'r') as zip_ref: + zip_ref.extractall(os.path.dirname(z_file)) +except Exception as e: + os.system('unzip random_examples.zip') + +from diffusers import ( + AutoencoderKL, + UNet2DConditionModel, + StableDiffusionPipeline, + StableDiffusionImg2ImgPipeline, + DPMSolverMultistepScheduler, +) +import gradio as gr +import torch +from PIL import Image +import utils +import datetime +import time +import psutil +from Waifu2x.magnify import ImageMagnifier +from RealESRGANv030.interface import realEsrgan + +magnifier = ImageMagnifier() + +start_time = time.time() +is_colab = utils.is_google_colab() + +CUDA_VISIBLE_DEVICES = "" +device = autocuda.auto_cuda() + +dtype = torch.float16 if device != "cpu" else torch.float32 + + + +class Model: + def __init__(self, name, path="", prefix=""): + self.name = name + self.path = path + self.prefix = prefix + self.pipe_t2i = None + self.pipe_i2i = None + + +models = [ + # Model("anything v3", "Linaqruf/anything-v3.0", "anything v3 style"), + Model("anything v5", "stablediffusionapi/anything-v5", "anything v5 style"), +] +# Model("Spider-Verse", "nitrosocke/spider-verse-diffusion", "spiderverse style "), +# Model("Balloon Art", "Fictiverse/Stable_Diffusion_BalloonArt_Model", "BalloonArt "), +# Model("Elden Ring", "nitrosocke/elden-ring-diffusion", "elden ring style "), +# Model("Tron Legacy", "dallinmackay/Tron-Legacy-diffusion", "trnlgcy ") +# Model("Pokémon", "lambdalabs/sd-pokemon-diffusers", ""), +# Model("Pony Diffusion", "AstraliteHeart/pony-diffusion", ""), +# Model("Robo Diffusion", "nousr/robo-diffusion", ""), + +scheduler = DPMSolverMultistepScheduler( + beta_start=0.00085, + beta_end=0.012, + beta_schedule="scaled_linear", + num_train_timesteps=1000, + trained_betas=None, + predict_epsilon=True, + thresholding=False, + algorithm_type="dpmsolver++", + solver_type="midpoint", + solver_order=2, + # lower_order_final=True, +) + +custom_model = None +if is_colab: + models.insert(0, Model("Custom model")) + custom_model = models[0] + +last_mode = "txt2img" +current_model = models[1] if is_colab else models[0] +current_model_path = current_model.path + +if is_colab: + pipe = StableDiffusionPipeline.from_pretrained( + current_model.path, + torch_dtype=dtype, + scheduler=scheduler, + safety_checker=lambda images, clip_input: (images, False), + ) + +else: # download all models + print(f"{datetime.datetime.now()} Downloading vae...") + vae = AutoencoderKL.from_pretrained( + current_model.path, subfolder="vae", torch_dtype=dtype + ) + for model in models: + try: + print(f"{datetime.datetime.now()} Downloading {model.name} model...") + unet = UNet2DConditionModel.from_pretrained( + model.path, subfolder="unet", torch_dtype=dtype + ) + model.pipe_t2i = StableDiffusionPipeline.from_pretrained( + model.path, + unet=unet, + vae=vae, + torch_dtype=dtype, + scheduler=scheduler, + safety_checker=None, + ) + model.pipe_i2i = StableDiffusionImg2ImgPipeline.from_pretrained( + model.path, + unet=unet, + vae=vae, + torch_dtype=dtype, + scheduler=scheduler, + safety_checker=None, + ) + except Exception as e: + print( + f"{datetime.datetime.now()} Failed to load model " + + model.name + + ": " + + str(e) + ) + models.remove(model) + pipe = models[0].pipe_t2i + +# model.pipe_i2i = torch.compile(model.pipe_i2i) +# model.pipe_t2i = torch.compile(model.pipe_t2i) +if torch.cuda.is_available(): + pipe = pipe.to(device) + + +# device = "GPU 🔥" if torch.cuda.is_available() else "CPU 🥶" + + +def error_str(error, title="Error"): + return ( + f"""#### {title} + {error}""" + if error + else "" + ) + + +def custom_model_changed(path): + models[0].path = path + global current_model + current_model = models[0] + + +def on_model_change(model_name): + prefix = ( + 'Enter prompt. "' + + next((m.prefix for m in models if m.name == model_name), None) + + '" is prefixed automatically' + if model_name != models[0].name + else "Don't forget to use the custom model prefix in the prompt!" + ) + + return ( + gr.update(visible=model_name == models[0].name), + gr.update(placeholder=prefix), + ) + + +def inference( + model_name, + prompt, + guidance, + steps, + width=512, + height=512, + seed=0, + img=None, + strength=0.5, + neg_prompt="", + scale="ESRGAN4x", + scale_factor=2, +): + fprint(psutil.virtual_memory()) # print memory usage + + fprint(f"Prompt: {prompt}") + global current_model + for model in models: + if model.name == model_name: + current_model = model + model_path = current_model.path + + generator = torch.Generator(device).manual_seed(seed) if seed != 0 else None + + try: + if img is not None: + return ( + img_to_img( + model_path, + prompt, + neg_prompt, + img, + strength, + guidance, + steps, + width, + height, + generator, + scale, + scale_factor, + ), + None, + ) + else: + return ( + txt_to_img( + model_path, + prompt, + neg_prompt, + guidance, + steps, + width, + height, + generator, + scale, + scale_factor, + ), + None, + ) + except Exception as e: + return None, error_str(e) + # if img is not None: + # return img_to_img(model_path, prompt, neg_prompt, img, strength, guidance, steps, width, height, + # generator, scale, scale_factor), None + # else: + # return txt_to_img(model_path, prompt, neg_prompt, guidance, steps, width, height, generator, scale, scale_factor), None + + +def txt_to_img( + model_path, + prompt, + neg_prompt, + guidance, + steps, + width, + height, + generator, + scale, + scale_factor, +): + print(f"{datetime.datetime.now()} txt_to_img, model: {current_model.name}") + + global last_mode + global pipe + global current_model_path + if model_path != current_model_path or last_mode != "txt2img": + current_model_path = model_path + + if is_colab or current_model == custom_model: + pipe = StableDiffusionPipeline.from_pretrained( + current_model_path, + torch_dtype=dtype, + scheduler=scheduler, + safety_checker=lambda images, clip_input: (images, False), + ) + else: + # pipe = pipe.to("cpu") + pipe = current_model.pipe_t2i + + if torch.cuda.is_available(): + pipe = pipe.to(device) + last_mode = "txt2img" + + prompt = current_model.prefix + prompt + result = pipe( + prompt, + negative_prompt=neg_prompt, + # num_images_per_prompt=n_images, + num_inference_steps=int(steps), + guidance_scale=guidance, + width=width, + height=height, + generator=generator, + ) + + # result.images[0] = magnifier.magnify(result.images[0], scale_factor=scale_factor) + # enhance resolution + if scale_factor > 1: + if scale == "ESRGAN4x": + fp32 = True if device == "cpu" else False + result.images[0] = realEsrgan( + input_dir=result.images[0], + suffix="", + output_dir="imgs", + fp32=fp32, + outscale=scale_factor, + )[0] + else: + result.images[0] = magnifier.magnify( + result.images[0], scale_factor=scale_factor + ) + # save image + result.images[0].save( + "imgs/result-{}.png".format(datetime.datetime.now().strftime("%Y%m%d-%H%M%S")) + ) + return replace_nsfw_images(result) + + +def img_to_img( + model_path, + prompt, + neg_prompt, + img, + strength, + guidance, + steps, + width, + height, + generator, + scale, + scale_factor, +): + fprint(f"{datetime.datetime.now()} img_to_img, model: {model_path}") + + global last_mode + global pipe + global current_model_path + if model_path != current_model_path or last_mode != "img2img": + current_model_path = model_path + + if is_colab or current_model == custom_model: + pipe = StableDiffusionImg2ImgPipeline.from_pretrained( + current_model_path, + torch_dtype=dtype, + scheduler=scheduler, + safety_checker=lambda images, clip_input: (images, False), + ) + else: + # pipe = pipe.to("cpu") + pipe = current_model.pipe_i2i + + if torch.cuda.is_available(): + pipe = pipe.to(device) + last_mode = "img2img" + + prompt = current_model.prefix + prompt + ratio = min(height / img.height, width / img.width) + img = img.resize((int(img.width * ratio), int(img.height * ratio)), Image.LANCZOS) + result = pipe( + prompt, + negative_prompt=neg_prompt, + # num_images_per_prompt=n_images, + image=img, + num_inference_steps=int(steps), + strength=strength, + guidance_scale=guidance, + # width=width, + # height=height, + generator=generator, + ) + if scale_factor > 1: + if scale == "ESRGAN4x": + fp32 = True if device == "cpu" else False + result.images[0] = realEsrgan( + input_dir=result.images[0], + suffix="", + output_dir="imgs", + fp32=fp32, + outscale=scale_factor, + )[0] + else: + result.images[0] = magnifier.magnify( + result.images[0], scale_factor=scale_factor + ) + # save image + result.images[0].save( + "imgs/result-{}.png".format(datetime.datetime.now().strftime("%Y%m%d-%H%M%S")) + ) + return replace_nsfw_images(result) + + +def replace_nsfw_images(results): + if is_colab: + return results.images[0] + if hasattr(results, "nsfw_content_detected") and results.nsfw_content_detected: + for i in range(len(results.images)): + if results.nsfw_content_detected[i]: + results.images[i] = Image.open("nsfw.png") + return results.images[0] + + +css = """.finetuned-diffusion-div div{display:inline-flex;align-items:center;gap:.8rem;font-size:1.75rem}.finetuned-diffusion-div div h1{font-weight:900;margin-bottom:7px}.finetuned-diffusion-div p{margin-bottom:10px;font-size:94%}a{text-decoration:underline}.tabs{margin-top:0;margin-bottom:0}#gallery{min-height:20rem} +""" +with gr.Blocks(css=css) as demo: + if not os.path.exists("imgs"): + os.mkdir("imgs") + + gr.Markdown("# Super Resolution Anime Diffusion") + gr.Markdown( + "## Author: [yangheng95](https://github.com/yangheng95) Github:[Github](https://github.com/yangheng95/stable-diffusion-webui)" + ) + gr.Markdown( + "### This demo is running on a CPU, so it will take at least 20 minutes. " + "If you have a GPU, you can clone from [Github](https://github.com/yangheng95/SuperResolutionAnimeDiffusion) and run it locally." + ) + gr.Markdown( + "### FYI: to generate a 512*512 image and magnify 4x, it only takes 5~8 seconds on a RTX 2080 GPU" + ) + gr.Markdown( + "### You can duplicate this demo on HuggingFace Spaces, click [here](https://huggingface.co/spaces/yangheng/Super-Resolution-Anime-Diffusion?duplicate=true)" + ) + + with gr.Row(): + with gr.Column(scale=55): + with gr.Group(): + gr.Markdown("Text to image") + + model_name = gr.Dropdown( + label="Model", + choices=[m.name for m in models], + value=current_model.name, + ) + + with gr.Box(visible=False) as custom_model_group: + custom_model_path = gr.Textbox( + label="Custom model path", + placeholder="Path to model, e.g. nitrosocke/Arcane-Diffusion", + interactive=True, + ) + gr.HTML( + "
Custom models have to be downloaded first, so give it some time.
" + ) + + with gr.Row(): + prompt = gr.Textbox( + label="Prompt", + show_label=False, + max_lines=2, + placeholder="Enter prompt. Style applied automatically", + ).style(container=False) + with gr.Row(): + generate = gr.Button(value="Generate") + + with gr.Row(): + with gr.Group(): + neg_prompt = gr.Textbox( + label="Negative prompt", + value="bad result, worst, random, invalid, inaccurate, imperfect, blurry, deformed," + " disfigured, mutation, mutated, ugly, out of focus, bad anatomy, text, error," + " extra digit, fewer digits, worst quality, low quality, normal quality, noise, " + "jpeg artifact, compression artifact, signature, watermark, username, logo, " + "low resolution, worst resolution, bad resolution, normal resolution, bad detail," + " bad details, bad lighting, bad shadow, bad shading, bad background," + " worst background.", + ) + + image_out = gr.Image(height="auto", width="auto") + error_output = gr.Markdown() + + with gr.Row(): + gr.Markdown( + "# Random Image Generation Preview (512*768)x4 magnified" + ) + for f_img in findfile.find_cwd_files(".png", recursive=2): + with gr.Row(): + image = gr.Image(height=512, value=PIL.Image.open(f_img)) + # gallery = gr.Gallery( + # label="Generated images", show_label=False, elem_id="gallery" + # ).style(grid=[1], height="auto") + + with gr.Column(scale=45): + with gr.Group(): + gr.Markdown("Image to Image") + + with gr.Row(): + with gr.Group(): + image = gr.Image( + label="Image", height=256, tool="editor", type="pil" + ) + strength = gr.Slider( + label="Transformation strength", + minimum=0, + maximum=1, + step=0.01, + value=0.5, + ) + + with gr.Row(): + with gr.Group(): + # n_images = gr.Slider(label="Images", value=1, minimum=1, maximum=4, step=1) + + with gr.Row(): + guidance = gr.Slider( + label="Guidance scale", value=7.5, maximum=15 + ) + steps = gr.Slider( + label="Steps", value=15, minimum=2, maximum=75, step=1 + ) + + with gr.Row(): + width = gr.Slider( + label="Width", + value=512, + minimum=64, + maximum=1024, + step=8, + ) + height = gr.Slider( + label="Height", + value=768, + minimum=64, + maximum=1024, + step=8, + ) + with gr.Row(): + scale = gr.Radio( + label="Scale", + choices=["Waifu2x", "ESRGAN4x"], + value="Waifu2x", + ) + with gr.Row(): + scale_factor = gr.Slider( + 1, + 8, + label="Scale factor (to magnify image) (1, 2, 4, 8)", + value=1, + step=1, + ) + + seed = gr.Slider( + 0, 2147483647, label="Seed (0 = random)", value=0, step=1 + ) + + if is_colab: + model_name.change( + on_model_change, + inputs=model_name, + outputs=[custom_model_group, prompt], + queue=False, + ) + custom_model_path.change( + custom_model_changed, inputs=custom_model_path, outputs=None + ) + # n_images.change(lambda n: gr.Gallery().style(grid=[2 if n > 1 else 1], height="auto"), inputs=n_images, outputs=gallery) + + gr.Markdown( + "### based on [Anything V5]" + ) + + inputs = [ + model_name, + prompt, + guidance, + steps, + width, + height, + seed, + image, + strength, + neg_prompt, + scale, + scale_factor, + ] + outputs = [image_out, error_output] + prompt.submit(inference, inputs=inputs, outputs=outputs) + generate.click(inference, inputs=inputs, outputs=outputs, api_name="generate") + + prompt_keys = [ + "girl", + "lovely", + "cute", + "beautiful eyes", + "cumulonimbus clouds", + random.choice(["dress"]), + random.choice(["white hair"]), + random.choice(["blue eyes"]), + random.choice(["flower meadow"]), + random.choice(["Elif", "Angel"]), + ] + prompt.value = ",".join(prompt_keys) + ex = gr.Examples( + [ + [models[0].name, prompt.value, 7.5, 15], + ], + inputs=[model_name, prompt, guidance, steps, seed], + outputs=outputs, + fn=inference, + cache_examples=False, + ) + +print(f"Space built in {time.time() - start_time:.2f} seconds") + +if not is_colab: + demo.queue(concurrency_count=2) +demo.launch(debug=is_colab, enable_queue=True, share=is_colab) \ No newline at end of file diff --git a/image_scale.py b/image_scale.py new file mode 100644 index 0000000000000000000000000000000000000000..88261f3cb3cad56a3b5c7b72b4a04aba2ad42299 --- /dev/null +++ b/image_scale.py @@ -0,0 +1,23 @@ +# -*- coding: utf-8 -*- +# file: image_scale.py +# time: 06/12/2022 +# author: yangheng +# github: https://github.com/yangheng95 +# huggingface: https://huggingface.co/yangheng +# google scholar: https://scholar.google.com/citations?user=NPq5a_0AAAAJ&hl=en +# Copyright (C) 2021. All Rights Reserved. +import os + +import findfile +import tqdm + +from Waifu2x import ImageMagnifier + +magnifier = ImageMagnifier() +if __name__ == "__main__": + # path = os.getcwd() + # for f in findfile.find_cwd_files(or_key=[".jpg", ".png"]): + for f in tqdm.tqdm( + findfile.find_files(r"C:\Users\chuan\OneDrive\imgs", or_key=[".jpg", ".png"]) + ): + img = magnifier.magnify_from_file(f, scale_factor=2) diff --git a/inference.py b/inference.py new file mode 100644 index 0000000000000000000000000000000000000000..25b887c92a1ac1af8d62a7a2d19d522dc75f48da --- /dev/null +++ b/inference.py @@ -0,0 +1,407 @@ +import os +import random + +import autocuda +from pyabsa.utils.pyabsa_utils import fprint + +from diffusers import ( + AutoencoderKL, + UNet2DConditionModel, + StableDiffusionPipeline, + StableDiffusionImg2ImgPipeline, + DPMSolverMultistepScheduler, +) +import gradio as gr +import torch +from PIL import Image +import utils +import datetime +import time +import psutil + +from Waifu2x.magnify import ImageMagnifier + +start_time = time.time() +is_colab = utils.is_google_colab() + +device = autocuda.auto_cuda() + +magnifier = ImageMagnifier() + + +class Model: + def __init__(self, name, path="", prefix=""): + self.name = name + self.path = path + self.prefix = prefix + self.pipe_t2i = None + self.pipe_i2i = None + + +models = [ + # Model("anything v3", "anything-v3.0", "anything v3 style"), + Model("anything v3", "Linaqruf/anything-v3.0", "anything v3 style"), +] +# Model("Spider-Verse", "nitrosocke/spider-verse-diffusion", "spiderverse style "), +# Model("Balloon Art", "Fictiverse/Stable_Diffusion_BalloonArt_Model", "BalloonArt "), +# Model("Elden Ring", "nitrosocke/elden-ring-diffusion", "elden ring style "), +# Model("Tron Legacy", "dallinmackay/Tron-Legacy-diffusion", "trnlgcy ") +# Model("Pokémon", "lambdalabs/sd-pokemon-diffusers", ""), +# Model("Pony Diffusion", "AstraliteHeart/pony-diffusion", ""), +# Model("Robo Diffusion", "nousr/robo-diffusion", ""), + +scheduler = DPMSolverMultistepScheduler( + beta_start=0.00085, + beta_end=0.012, + beta_schedule="scaled_linear", + num_train_timesteps=1000, + trained_betas=None, + predict_epsilon=True, + thresholding=False, + algorithm_type="dpmsolver++", + solver_type="midpoint", + lower_order_final=True, +) + +custom_model = None +if is_colab: + models.insert(0, Model("Custom model")) + custom_model = models[0] + +last_mode = "txt2img" +current_model = models[1] if is_colab else models[0] +current_model_path = current_model.path + +if is_colab: + pipe = StableDiffusionPipeline.from_pretrained( + current_model.path, + torch_dtype=torch.float16, + scheduler=scheduler, + safety_checker=lambda images, clip_input: (images, False), + ) + +else: # download all models + print(f"{datetime.datetime.now()} Downloading vae...") + vae = AutoencoderKL.from_pretrained( + current_model.path, subfolder="vae", torch_dtype=torch.float16 + ) + for model in models: + try: + print(f"{datetime.datetime.now()} Downloading {model.name} model...") + unet = UNet2DConditionModel.from_pretrained( + model.path, subfolder="unet", torch_dtype=torch.float16 + ) + model.pipe_t2i = StableDiffusionPipeline.from_pretrained( + model.path, + unet=unet, + vae=vae, + torch_dtype=torch.float16, + scheduler=scheduler, + ) + model.pipe_i2i = StableDiffusionImg2ImgPipeline.from_pretrained( + model.path, + unet=unet, + vae=vae, + torch_dtype=torch.float16, + scheduler=scheduler, + ) + except Exception as e: + print( + f"{datetime.datetime.now()} Failed to load model " + + model.name + + ": " + + str(e) + ) + models.remove(model) + pipe = models[0].pipe_t2i + +if torch.cuda.is_available(): + pipe = pipe.to(device) + +device = "GPU 🔥" if torch.cuda.is_available() else "CPU 🥶" + + +def error_str(error, title="Error"): + return ( + f"""#### {title} + {error}""" + if error + else "" + ) + + +def custom_model_changed(path): + models[0].path = path + global current_model + current_model = models[0] + + +def on_model_change(model_name): + prefix = ( + 'Enter prompt. "' + + next((m.prefix for m in models if m.name == model_name), None) + + '" is prefixed automatically' + if model_name != models[0].name + else "Don't forget to use the custom model prefix in the prompt!" + ) + + return gr.update(visible=model_name == models[0].name), gr.update( + placeholder=prefix + ) + + +def inference( + model_name, + prompt, + guidance, + steps, + width=512, + height=512, + seed=0, + img=None, + strength=0.5, + neg_prompt="", +): + print(psutil.virtual_memory()) # print memory usage + + global current_model + for model in models: + if model.name == model_name: + current_model = model + model_path = current_model.path + + generator = torch.Generator("cuda").manual_seed(seed) if seed != 0 else None + + try: + if img is not None: + return ( + img_to_img( + model_path, + prompt, + neg_prompt, + img, + strength, + guidance, + steps, + width, + height, + generator, + ), + None, + ) + else: + return ( + txt_to_img( + model_path, + prompt, + neg_prompt, + guidance, + steps, + width, + height, + generator, + ), + None, + ) + except Exception as e: + fprint(e) + return None, error_str(e) + + +def txt_to_img( + model_path, prompt, neg_prompt, guidance, steps, width, height, generator +): + print(f"{datetime.datetime.now()} txt_to_img, model: {current_model.name}") + + global last_mode + global pipe + global current_model_path + if model_path != current_model_path or last_mode != "txt2img": + current_model_path = model_path + + if is_colab or current_model == custom_model: + pipe = StableDiffusionPipeline.from_pretrained( + current_model_path, + torch_dtype=torch.float16, + scheduler=scheduler, + safety_checker=lambda images, clip_input: (images, False), + ) + else: + pipe = pipe.to("cpu") + pipe = current_model.pipe_t2i + + if torch.cuda.is_available(): + pipe = pipe.to(device) + last_mode = "txt2img" + + prompt = current_model.prefix + prompt + result = pipe( + prompt, + negative_prompt=neg_prompt, + # num_images_per_prompt=n_images, + num_inference_steps=int(steps), + guidance_scale=guidance, + width=width, + height=height, + generator=generator, + ) + result.images[0] = magnifier.magnify(result.images[0]) + result.images[0] = magnifier.magnify(result.images[0]) + + # save image + result.images[0].save( + "{}/{}.{}.{}.{}.{}.{}.{}.{}.png".format( + saved_path, + datetime.datetime.now().strftime("%Y%m%d-%H%M%S"), + model_name, + prompt, + guidance, + steps, + width, + height, + seed, + ) + ) + return replace_nsfw_images(result) + + +def img_to_img( + model_path, + prompt, + neg_prompt, + img, + strength, + guidance, + steps, + width, + height, + generator, +): + print(f"{datetime.datetime.now()} img_to_img, model: {model_path}") + + global last_mode + global pipe + global current_model_path + if model_path != current_model_path or last_mode != "img2img": + current_model_path = model_path + + if is_colab or current_model == custom_model: + pipe = StableDiffusionImg2ImgPipeline.from_pretrained( + current_model_path, + torch_dtype=torch.float16, + scheduler=scheduler, + safety_checker=lambda images, clip_input: (images, False), + ) + else: + pipe = pipe.to("cpu") + pipe = current_model.pipe_i2i + + if torch.cuda.is_available(): + pipe = pipe.to(device) + last_mode = "img2img" + + prompt = current_model.prefix + prompt + ratio = min(height / img.height, width / img.width) + img = img.resize((int(img.width * ratio), int(img.height * ratio)), Image.LANCZOS) + result = pipe( + prompt, + negative_prompt=neg_prompt, + # num_images_per_prompt=n_images, + init_image=img, + num_inference_steps=int(steps), + strength=strength, + guidance_scale=guidance, + width=width, + height=height, + generator=generator, + ) + result.images[0] = magnifier.magnify(result.images[0]) + result.images[0] = magnifier.magnify(result.images[0]) + + # save image + result.images[0].save( + "{}/{}.{}.{}.{}.{}.{}.{}.{}.png".format( + saved_path, + datetime.datetime.now().strftime("%Y%m%d-%H%M%S"), + model_name, + prompt, + guidance, + steps, + width, + height, + seed, + ) + ) + return replace_nsfw_images(result) + + +def replace_nsfw_images(results): + if is_colab: + return results.images[0] + + for i in range(len(results.images)): + if results.nsfw_content_detected[i]: + results.images[i] = Image.open("nsfw.png") + return results.images[0] + + +if __name__ == "__main__": + # inference("DALL-E", "a dog", 0, 1000, 512, 512, 0, None, 0.5, "") + model_name = "anything v3" + saved_path = r"imgs" + if not os.path.exists(saved_path): + os.mkdir(saved_path) + n = 0 + while True: + prompt_keys = [ + "beautiful eyes", + "cumulonimbus clouds", + "sky", + "detailed fingers", + random.choice( + [ + "white hair", + "red hair", + "blonde hair", + "black hair", + "green hair", + ] + ), + random.choice( + [ + "blue eyes", + "green eyes", + "red eyes", + "black eyes", + "yellow eyes", + ] + ), + random.choice(["flower meadow", "garden", "city", "river", "beach"]), + random.choice(["Elif", "Angel"]), + ] + guidance = 7.5 + steps = 25 + # width = 1024 + # height = 1024 + # width = 768 + # height = 1024 + width = 512 + height = 888 + seed = 0 + img = None + strength = 0.5 + neg_prompt = "" + inference( + model_name, + ".".join(prompt_keys), + guidance, + steps, + width=width, + height=height, + seed=seed, + img=img, + strength=strength, + neg_prompt=neg_prompt, + ) + n += 1 + fprint(n) diff --git a/protogen.py b/protogen.py new file mode 100644 index 0000000000000000000000000000000000000000..0f3dd33d03b439c9bfd0ef132f49879c7481aa33 --- /dev/null +++ b/protogen.py @@ -0,0 +1,53 @@ +# -*- coding: utf-8 -*- +# file: protogen.py +# time: 14:27 2023/1/9 +# author: yangheng +# github: https://github.com/yangheng95 +# huggingface: https://huggingface.co/yangheng +# google scholar: https://scholar.google.com/citations?user=NPq5a_0AAAAJ&hl=en +# Copyright (C) 2021. All Rights Reserved. + +from diffusers import StableDiffusionPipeline, DPMSolverMultistepScheduler +import torch +import random + +prompt_keys = [ + "naked", + "loli", + "teen", + "squat", + "big nipples", + "hairy pussy", + "pee", + "beautiful eyes", + # 'dress', 'wind', 'fingers', 'hands', + # random.choice(['Sinon', 'saber', ]), + # random.choice(['white dress', 'red dress', 'blonde dress', 'black dress', 'green dress', ]), + # random.choice(['white bra', 'red bra', 'black bra',]), + "lovely", + "details", + # random.choice(['white hair', 'red hair', 'blonde hair', 'black hair', 'green hair', ]), + random.choice(["white hair"]), + random.choice(["blue eyes", "red eyes", "black eyes"]), + random.choice(["flower meadow", "garden"]), +] +prompt = ",".join(prompt_keys) +model_id = "darkstorm2150/Protogen_x3.4_Official_Release" +pipe = StableDiffusionPipeline.from_pretrained( + model_id, torch_dtype=torch.float16, safety_checker=None +) +pipe.scheduler = DPMSolverMultistepScheduler.from_config(pipe.scheduler.config) +pipe = pipe.to("cuda") + +guidance = 7.5 +width = 768 +height = 512 +image = pipe( + prompt, + num_inference_steps=25, + guidance_scale=guidance, + width=width, + height=height, +).images[0] + +image.save("./result.jpg") diff --git a/random_examples.zip b/random_examples.zip new file mode 100644 index 0000000000000000000000000000000000000000..4a9c495abe18f80df1c9be1efacf348944575407 --- /dev/null +++ b/random_examples.zip @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:0d38130425c106b715732609413675a33cd3eb551fe7eb7789ca87b5210d9f55 +size 8051179 diff --git a/requirements.txt b/requirements.txt new file mode 100644 index 0000000000000000000000000000000000000000..136d55ba4597c49c4f1a599950a480ecf6a1eb13 --- /dev/null +++ b/requirements.txt @@ -0,0 +1,20 @@ +--extra-index-url https://download.pytorch.org/whl/cu113 +torch +torchvision +autocuda +findfile +pyabsa +diffusers==0.10.0 +scipy +git+https://github.com/huggingface/transformers.git +ftfy +accelerate +psutil +basicsr>=1.4.2 +facexlib>=0.2.5 +gfpgan>=1.3.5 +numpy +opencv-python +Pillow +tqdm +realesrgan diff --git a/utils.py b/utils.py new file mode 100644 index 0000000000000000000000000000000000000000..740ced9943143c7a56a16273044e60d6ab3e9728 --- /dev/null +++ b/utils.py @@ -0,0 +1,7 @@ +def is_google_colab(): + try: + import google.colab + + return True + except: + return False