HariLogicgo commited on
Commit
7a955d9
·
1 Parent(s): 6bbf973

test 1 error debug

Browse files
This view is limited to 50 files because it contains too many changes.   See raw diff
Files changed (50) hide show
  1. CodeFormer/.gitignore +131 -0
  2. CodeFormer/README.md +167 -0
  3. CodeFormer/docs/history_changelog.md +15 -0
  4. CodeFormer/docs/train.md +37 -0
  5. CodeFormer/docs/train_CN.md +37 -0
  6. CodeFormer/facelib/detection/__init__.py +100 -0
  7. CodeFormer/facelib/detection/align_trans.py +219 -0
  8. CodeFormer/facelib/detection/matlab_cp2tform.py +317 -0
  9. CodeFormer/facelib/detection/retinaface/retinaface.py +372 -0
  10. CodeFormer/facelib/detection/retinaface/retinaface_net.py +196 -0
  11. CodeFormer/facelib/detection/retinaface/retinaface_utils.py +421 -0
  12. CodeFormer/facelib/detection/yolov5face/__init__.py +0 -0
  13. CodeFormer/facelib/detection/yolov5face/face_detector.py +141 -0
  14. CodeFormer/facelib/detection/yolov5face/models/__init__.py +0 -0
  15. CodeFormer/facelib/detection/yolov5face/models/common.py +299 -0
  16. CodeFormer/facelib/detection/yolov5face/models/experimental.py +45 -0
  17. CodeFormer/facelib/detection/yolov5face/models/yolo.py +235 -0
  18. CodeFormer/facelib/detection/yolov5face/models/yolov5l.yaml +47 -0
  19. CodeFormer/facelib/detection/yolov5face/models/yolov5n.yaml +45 -0
  20. CodeFormer/facelib/detection/yolov5face/utils/__init__.py +0 -0
  21. CodeFormer/facelib/detection/yolov5face/utils/autoanchor.py +12 -0
  22. CodeFormer/facelib/detection/yolov5face/utils/datasets.py +35 -0
  23. CodeFormer/facelib/detection/yolov5face/utils/extract_ckpt.py +5 -0
  24. CodeFormer/facelib/detection/yolov5face/utils/general.py +271 -0
  25. CodeFormer/facelib/detection/yolov5face/utils/torch_utils.py +40 -0
  26. CodeFormer/facelib/parsing/__init__.py +23 -0
  27. CodeFormer/facelib/parsing/bisenet.py +140 -0
  28. CodeFormer/facelib/parsing/parsenet.py +194 -0
  29. CodeFormer/facelib/parsing/resnet.py +69 -0
  30. CodeFormer/facelib/utils/__init__.py +7 -0
  31. CodeFormer/facelib/utils/face_restoration_helper.py +525 -0
  32. CodeFormer/facelib/utils/face_utils.py +248 -0
  33. CodeFormer/facelib/utils/misc.py +202 -0
  34. CodeFormer/inference_codeformer.py +281 -0
  35. CodeFormer/inference_colorization.py +86 -0
  36. CodeFormer/inference_inpainting.py +91 -0
  37. CodeFormer/options/CodeFormer_colorization.yml +145 -0
  38. CodeFormer/options/CodeFormer_inpainting.yml +159 -0
  39. CodeFormer/options/CodeFormer_stage2.yml +145 -0
  40. CodeFormer/options/CodeFormer_stage3.yml +171 -0
  41. CodeFormer/options/VQGAN_512_ds32_nearest_stage1.yml +136 -0
  42. CodeFormer/requirements.txt +19 -0
  43. CodeFormer/scripts/crop_align_face.py +205 -0
  44. CodeFormer/scripts/download_pretrained_models.py +52 -0
  45. CodeFormer/scripts/download_pretrained_models_from_gdrive.py +60 -0
  46. CodeFormer/scripts/generate_latent_gt.py +67 -0
  47. CodeFormer/scripts/inference_vqgan.py +59 -0
  48. CodeFormer/web-demos/hugging_face/app.py +283 -0
  49. CodeFormer/web-demos/replicate/cog.yaml +30 -0
  50. CodeFormer/web-demos/replicate/predict.py +191 -0
CodeFormer/.gitignore ADDED
@@ -0,0 +1,131 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ .vscode
2
+
3
+ # ignored files
4
+ version.py
5
+
6
+ # ignored files with suffix
7
+ *.html
8
+ # *.png
9
+ # *.jpeg
10
+ # *.jpg
11
+ *.pt
12
+ *.gif
13
+ *.pth
14
+ *.dat
15
+ *.zip
16
+
17
+ # template
18
+
19
+ # Byte-compiled / optimized / DLL files
20
+ __pycache__/
21
+ *.py[cod]
22
+ *$py.class
23
+
24
+ # C extensions
25
+ *.so
26
+
27
+ # Distribution / packaging
28
+ .Python
29
+ build/
30
+ develop-eggs/
31
+ dist/
32
+ downloads/
33
+ eggs/
34
+ .eggs/
35
+ lib/
36
+ lib64/
37
+ parts/
38
+ sdist/
39
+ var/
40
+ wheels/
41
+ *.egg-info/
42
+ .installed.cfg
43
+ *.egg
44
+ MANIFEST
45
+
46
+ # PyInstaller
47
+ # Usually these files are written by a python script from a template
48
+ # before PyInstaller builds the exe, so as to inject date/other infos into it.
49
+ *.manifest
50
+ *.spec
51
+
52
+ # Installer logs
53
+ pip-log.txt
54
+ pip-delete-this-directory.txt
55
+
56
+ # Unit test / coverage reports
57
+ htmlcov/
58
+ .tox/
59
+ .coverage
60
+ .coverage.*
61
+ .cache
62
+ nosetests.xml
63
+ coverage.xml
64
+ *.cover
65
+ .hypothesis/
66
+ .pytest_cache/
67
+
68
+ # Translations
69
+ *.mo
70
+ *.pot
71
+
72
+ # Django stuff:
73
+ *.log
74
+ local_settings.py
75
+ db.sqlite3
76
+
77
+ # Flask stuff:
78
+ instance/
79
+ .webassets-cache
80
+
81
+ # Scrapy stuff:
82
+ .scrapy
83
+
84
+ # Sphinx documentation
85
+ docs/_build/
86
+
87
+ # PyBuilder
88
+ target/
89
+
90
+ # Jupyter Notebook
91
+ .ipynb_checkpoints
92
+
93
+ # pyenv
94
+ .python-version
95
+
96
+ # celery beat schedule file
97
+ celerybeat-schedule
98
+
99
+ # SageMath parsed files
100
+ *.sage.py
101
+
102
+ # Environments
103
+ .env
104
+ .venv
105
+ env/
106
+ venv/
107
+ ENV/
108
+ env.bak/
109
+ venv.bak/
110
+
111
+ # Spyder project settings
112
+ .spyderproject
113
+ .spyproject
114
+
115
+ # Rope project settings
116
+ .ropeproject
117
+
118
+ # mkdocs documentation
119
+ /site
120
+
121
+ # mypy
122
+ .mypy_cache/
123
+
124
+ # project
125
+ results/
126
+ experiments/
127
+ tb_logger/
128
+ run.sh
129
+ *debug*
130
+ *_old*
131
+
CodeFormer/README.md ADDED
@@ -0,0 +1,167 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ <p align="center">
2
+ <img src="assets/CodeFormer_logo.png" height=110>
3
+ </p>
4
+
5
+ ## Towards Robust Blind Face Restoration with Codebook Lookup Transformer (NeurIPS 2022)
6
+
7
+ [Paper](https://arxiv.org/abs/2206.11253) | [Project Page](https://shangchenzhou.com/projects/CodeFormer/) | [Video](https://youtu.be/d3VDpkXlueI)
8
+
9
+
10
+ <a href="https://colab.research.google.com/drive/1m52PNveE4PBhYrecj34cnpEeiHcC5LTb?usp=sharing"><img src="https://colab.research.google.com/assets/colab-badge.svg" alt="google colab logo"></a> [![Hugging Face](https://img.shields.io/badge/Demo-%F0%9F%A4%97%20Hugging%20Face-blue)](https://huggingface.co/spaces/sczhou/CodeFormer) [![Replicate](https://img.shields.io/badge/Demo-%F0%9F%9A%80%20Replicate-blue)](https://replicate.com/sczhou/codeformer) [![OpenXLab](https://img.shields.io/badge/Demo-%F0%9F%90%BC%20OpenXLab-blue)](https://openxlab.org.cn/apps/detail/ShangchenZhou/CodeFormer) ![Visitors](https://api.infinitescript.com/badgen/count?name=sczhou/CodeFormer&ltext=Visitors)
11
+
12
+
13
+ [Shangchen Zhou](https://shangchenzhou.com/), [Kelvin C.K. Chan](https://ckkelvinchan.github.io/), [Chongyi Li](https://li-chongyi.github.io/), [Chen Change Loy](https://www.mmlab-ntu.com/person/ccloy/)
14
+
15
+ S-Lab, Nanyang Technological University
16
+
17
+ <img src="assets/network.jpg" width="800px"/>
18
+
19
+
20
+ :star: If CodeFormer is helpful to your images or projects, please help star this repo. Thanks! :hugs:
21
+
22
+
23
+ ### Update
24
+ - **2023.07.20**: Integrated to :panda_face: [OpenXLab](https://openxlab.org.cn/apps). Try out online demo! [![OpenXLab](https://img.shields.io/badge/Demo-%F0%9F%90%BC%20OpenXLab-blue)](https://openxlab.org.cn/apps/detail/ShangchenZhou/CodeFormer)
25
+ - **2023.04.19**: :whale: Training codes and config files are public available now.
26
+ - **2023.04.09**: Add features of inpainting and colorization for cropped and aligned face images.
27
+ - **2023.02.10**: Include `dlib` as a new face detector option, it produces more accurate face identity.
28
+ - **2022.10.05**: Support video input `--input_path [YOUR_VIDEO.mp4]`. Try it to enhance your videos! :clapper:
29
+ - **2022.09.14**: Integrated to :hugs: [Hugging Face](https://huggingface.co/spaces). Try out online demo! [![Hugging Face](https://img.shields.io/badge/Demo-%F0%9F%A4%97%20Hugging%20Face-blue)](https://huggingface.co/spaces/sczhou/CodeFormer)
30
+ - **2022.09.09**: Integrated to :rocket: [Replicate](https://replicate.com/explore). Try out online demo! [![Replicate](https://img.shields.io/badge/Demo-%F0%9F%9A%80%20Replicate-blue)](https://replicate.com/sczhou/codeformer)
31
+ - [**More**](docs/history_changelog.md)
32
+
33
+ ### TODO
34
+ - [x] Add training code and config files
35
+ - [x] Add checkpoint and script for face inpainting
36
+ - [x] Add checkpoint and script for face colorization
37
+ - [x] ~~Add background image enhancement~~
38
+
39
+ #### :panda_face: Try Enhancing Old Photos / Fixing AI-arts
40
+ [<img src="assets/imgsli_1.jpg" height="226px"/>](https://imgsli.com/MTI3NTE2) [<img src="assets/imgsli_2.jpg" height="226px"/>](https://imgsli.com/MTI3NTE1) [<img src="assets/imgsli_3.jpg" height="226px"/>](https://imgsli.com/MTI3NTIw)
41
+
42
+ #### Face Restoration
43
+
44
+ <img src="assets/restoration_result1.png" width="400px"/> <img src="assets/restoration_result2.png" width="400px"/>
45
+ <img src="assets/restoration_result3.png" width="400px"/> <img src="assets/restoration_result4.png" width="400px"/>
46
+
47
+ #### Face Color Enhancement and Restoration
48
+
49
+ <img src="assets/color_enhancement_result1.png" width="400px"/> <img src="assets/color_enhancement_result2.png" width="400px"/>
50
+
51
+ #### Face Inpainting
52
+
53
+ <img src="assets/inpainting_result1.png" width="400px"/> <img src="assets/inpainting_result2.png" width="400px"/>
54
+
55
+
56
+
57
+ ### Dependencies and Installation
58
+
59
+ - Pytorch >= 1.7.1
60
+ - CUDA >= 10.1
61
+ - Other required packages in `requirements.txt`
62
+ ```
63
+ # git clone this repository
64
+ git clone https://github.com/sczhou/CodeFormer
65
+ cd CodeFormer
66
+
67
+ # create new anaconda env
68
+ conda create -n codeformer python=3.8 -y
69
+ conda activate codeformer
70
+
71
+ # install python dependencies
72
+ pip3 install -r requirements.txt
73
+ python basicsr/setup.py develop
74
+ conda install -c conda-forge dlib (only for face detection or cropping with dlib)
75
+ ```
76
+ <!-- conda install -c conda-forge dlib -->
77
+
78
+ ### Quick Inference
79
+
80
+ #### Download Pre-trained Models:
81
+ Download the facelib and dlib pretrained models from [[Releases](https://github.com/sczhou/CodeFormer/releases/tag/v0.1.0) | [Google Drive](https://drive.google.com/drive/folders/1b_3qwrzY_kTQh0-SnBoGBgOrJ_PLZSKm?usp=sharing) | [OneDrive](https://entuedu-my.sharepoint.com/:f:/g/personal/s200094_e_ntu_edu_sg/EvDxR7FcAbZMp_MA9ouq7aQB8XTppMb3-T0uGZ_2anI2mg?e=DXsJFo)] to the `weights/facelib` folder. You can manually download the pretrained models OR download by running the following command:
82
+ ```
83
+ python scripts/download_pretrained_models.py facelib
84
+ python scripts/download_pretrained_models.py dlib (only for dlib face detector)
85
+ ```
86
+
87
+ Download the CodeFormer pretrained models from [[Releases](https://github.com/sczhou/CodeFormer/releases/tag/v0.1.0) | [Google Drive](https://drive.google.com/drive/folders/1CNNByjHDFt0b95q54yMVp6Ifo5iuU6QS?usp=sharing) | [OneDrive](https://entuedu-my.sharepoint.com/:f:/g/personal/s200094_e_ntu_edu_sg/EoKFj4wo8cdIn2-TY2IV6CYBhZ0pIG4kUOeHdPR_A5nlbg?e=AO8UN9)] to the `weights/CodeFormer` folder. You can manually download the pretrained models OR download by running the following command:
88
+ ```
89
+ python scripts/download_pretrained_models.py CodeFormer
90
+ ```
91
+
92
+ #### Prepare Testing Data:
93
+ You can put the testing images in the `inputs/TestWhole` folder. If you would like to test on cropped and aligned faces, you can put them in the `inputs/cropped_faces` folder. You can get the cropped and aligned faces by running the following command:
94
+ ```
95
+ # you may need to install dlib via: conda install -c conda-forge dlib
96
+ python scripts/crop_align_face.py -i [input folder] -o [output folder]
97
+ ```
98
+
99
+
100
+ #### Testing:
101
+ [Note] If you want to compare CodeFormer in your paper, please run the following command indicating `--has_aligned` (for cropped and aligned face), as the command for the whole image will involve a process of face-background fusion that may damage hair texture on the boundary, which leads to unfair comparison.
102
+
103
+ Fidelity weight *w* lays in [0, 1]. Generally, smaller *w* tends to produce a higher-quality result, while larger *w* yields a higher-fidelity result. The results will be saved in the `results` folder.
104
+
105
+
106
+ 🧑🏻 Face Restoration (cropped and aligned face)
107
+ ```
108
+ # For cropped and aligned faces (512x512)
109
+ python inference_codeformer.py -w 0.5 --has_aligned --input_path [image folder]|[image path]
110
+ ```
111
+
112
+ :framed_picture: Whole Image Enhancement
113
+ ```
114
+ # For whole image
115
+ # Add '--bg_upsampler realesrgan' to enhance the background regions with Real-ESRGAN
116
+ # Add '--face_upsample' to further upsample restorated face with Real-ESRGAN
117
+ python inference_codeformer.py -w 0.7 --input_path [image folder]|[image path]
118
+ ```
119
+
120
+ :clapper: Video Enhancement
121
+ ```
122
+ # For Windows/Mac users, please install ffmpeg first
123
+ conda install -c conda-forge ffmpeg
124
+ ```
125
+ ```
126
+ # For video clips
127
+ # Video path should end with '.mp4'|'.mov'|'.avi'
128
+ python inference_codeformer.py --bg_upsampler realesrgan --face_upsample -w 1.0 --input_path [video path]
129
+ ```
130
+
131
+ 🌈 Face Colorization (cropped and aligned face)
132
+ ```
133
+ # For cropped and aligned faces (512x512)
134
+ # Colorize black and white or faded photo
135
+ python inference_colorization.py --input_path [image folder]|[image path]
136
+ ```
137
+
138
+ 🎨 Face Inpainting (cropped and aligned face)
139
+ ```
140
+ # For cropped and aligned faces (512x512)
141
+ # Inputs could be masked by white brush using an image editing app (e.g., Photoshop)
142
+ # (check out the examples in inputs/masked_faces)
143
+ python inference_inpainting.py --input_path [image folder]|[image path]
144
+ ```
145
+ ### Training:
146
+ The training commands can be found in the documents: [English](docs/train.md) **|** [简体中文](docs/train_CN.md).
147
+
148
+ ### Citation
149
+ If our work is useful for your research, please consider citing:
150
+
151
+ @inproceedings{zhou2022codeformer,
152
+ author = {Zhou, Shangchen and Chan, Kelvin C.K. and Li, Chongyi and Loy, Chen Change},
153
+ title = {Towards Robust Blind Face Restoration with Codebook Lookup TransFormer},
154
+ booktitle = {NeurIPS},
155
+ year = {2022}
156
+ }
157
+
158
+ ### License
159
+
160
+ This project is licensed under <a rel="license" href="https://github.com/sczhou/CodeFormer/blob/master/LICENSE">NTU S-Lab License 1.0</a>. Redistribution and use should follow this license.
161
+
162
+ ### Acknowledgement
163
+
164
+ This project is based on [BasicSR](https://github.com/XPixelGroup/BasicSR). Some codes are brought from [Unleashing Transformers](https://github.com/samb-t/unleashing-transformers), [YOLOv5-face](https://github.com/deepcam-cn/yolov5-face), and [FaceXLib](https://github.com/xinntao/facexlib). We also adopt [Real-ESRGAN](https://github.com/xinntao/Real-ESRGAN) to support background image enhancement. Thanks for their awesome works.
165
+
166
+ ### Contact
167
+ If you have any questions, please feel free to reach me out at `[email protected]`.
CodeFormer/docs/history_changelog.md ADDED
@@ -0,0 +1,15 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # History of Changelog
2
+
3
+ - **2023.04.19**: :whale: Training codes and config files are public available now.
4
+ - **2023.04.09**: Add features of inpainting and colorization for cropped face images.
5
+ - **2023.02.10**: Include `dlib` as a new face detector option, it produces more accurate face identity.
6
+ - **2022.10.05**: Support video input `--input_path [YOUR_VIDEO.mp4]`. Try it to enhance your videos! :clapper:
7
+ - **2022.09.14**: Integrated to :hugs: [Hugging Face](https://huggingface.co/spaces). Try out online demo! [![Hugging Face](https://img.shields.io/badge/Demo-%F0%9F%A4%97%20Hugging%20Face-blue)](https://huggingface.co/spaces/sczhou/CodeFormer)
8
+ - **2022.09.09**: Integrated to :rocket: [Replicate](https://replicate.com/explore). Try out online demo! [![Replicate](https://img.shields.io/badge/Demo-%F0%9F%9A%80%20Replicate-blue)](https://replicate.com/sczhou/codeformer)
9
+ - **2022.09.04**: Add face upsampling `--face_upsample` for high-resolution AI-created face enhancement.
10
+ - **2022.08.23**: Some modifications on face detection and fusion for better AI-created face enhancement.
11
+ - **2022.08.07**: Integrate [Real-ESRGAN](https://github.com/xinntao/Real-ESRGAN) to support background image enhancement.
12
+ - **2022.07.29**: Integrate new face detectors of `['RetinaFace'(default), 'YOLOv5']`.
13
+ - **2022.07.17**: Add Colab demo of CodeFormer. <a href="https://colab.research.google.com/drive/1m52PNveE4PBhYrecj34cnpEeiHcC5LTb?usp=sharing"><img src="https://colab.research.google.com/assets/colab-badge.svg" alt="google colab logo"></a>
14
+ - **2022.07.16**: Release inference code for face restoration. :blush:
15
+ - **2022.06.21**: This repo is created.
CodeFormer/docs/train.md ADDED
@@ -0,0 +1,37 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # :milky_way: Training Procedures
2
+ [English](train.md) **|** [简体中文](train_CN.md)
3
+ ## Preparing Dataset
4
+
5
+ - Download training dataset: [FFHQ](https://github.com/NVlabs/ffhq-dataset)
6
+
7
+ ---
8
+
9
+ ## Training
10
+ ```
11
+ For PyTorch versions >= 1.10, please replace `python -m torch.distributed.launch` in the commands below with `torchrun`.
12
+ ```
13
+
14
+ ### 👾 Stage I - VQGAN
15
+ - Training VQGAN:
16
+ > python -m torch.distributed.launch --nproc_per_node=gpu_num --master_port=4321 basicsr/train.py -opt options/VQGAN_512_ds32_nearest_stage1.yml --launcher pytorch
17
+
18
+ - After VQGAN training, you can pre-calculate code sequence for the training dataset to speed up the later training stages:
19
+ > python scripts/generate_latent_gt.py
20
+
21
+ - If you don't require training your own VQGAN, you can find pre-trained VQGAN (`vqgan_code1024.pth`) and the corresponding code sequence (`latent_gt_code1024.pth`) in the folder of Releases v0.1.0: https://github.com/sczhou/CodeFormer/releases/tag/v0.1.0
22
+
23
+ ### 🚀 Stage II - CodeFormer (w=0)
24
+ - Training Code Sequence Prediction Module:
25
+ > python -m torch.distributed.launch --nproc_per_node=gpu_num --master_port=4322 basicsr/train.py -opt options/CodeFormer_stage2.yml --launcher pytorch
26
+
27
+ - Pre-trained CodeFormer of stage II (`codeformer_stage2.pth`) can be found in the folder of Releases v0.1.0: https://github.com/sczhou/CodeFormer/releases/tag/v0.1.0
28
+
29
+ ### 🛸 Stage III - CodeFormer (w=1)
30
+ - Training Controllable Module:
31
+ > python -m torch.distributed.launch --nproc_per_node=gpu_num --master_port=4323 basicsr/train.py -opt options/CodeFormer_stage3.yml --launcher pytorch
32
+
33
+ - Pre-trained CodeFormer (`codeformer.pth`) can be found in the folder of Releases v0.1.0: https://github.com/sczhou/CodeFormer/releases/tag/v0.1.0
34
+
35
+ ---
36
+
37
+ :whale: The project was built using the framework [BasicSR](https://github.com/XPixelGroup/BasicSR). For detailed information on training, resuming, and other related topics, please refer to the documentation: https://github.com/XPixelGroup/BasicSR/blob/master/docs/TrainTest.md
CodeFormer/docs/train_CN.md ADDED
@@ -0,0 +1,37 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # :milky_way: 训练文档
2
+ [English](train.md) **|** [简体中文](train_CN.md)
3
+
4
+ ## 准备数据集
5
+ - 下载训练数据集: [FFHQ](https://github.com/NVlabs/ffhq-dataset)
6
+
7
+ ---
8
+
9
+ ## 训练
10
+ ```
11
+ 对于PyTorch版本 >= 1.10, 请将下面命令中的`python -m torch.distributed.launch`替换为`torchrun`.
12
+ ```
13
+
14
+ ### 👾 阶段 I - VQGAN
15
+ - 训练VQGAN:
16
+ > python -m torch.distributed.launch --nproc_per_node=gpu_num --master_port=4321 basicsr/train.py -opt options/VQGAN_512_ds32_nearest_stage1.yml --launcher pytorch
17
+
18
+ - 训练完VQGAN后,可以通过下面代码预先获得训练数据集的密码本序列,从而加速后面阶段的训练过程:
19
+ > python scripts/generate_latent_gt.py
20
+
21
+ - 如果你不需要训练自己的VQGAN,可以在Release v0.1.0文档中找到预训练的VQGAN (`vqgan_code1024.pth`)和对应的密码本序列 (`latent_gt_code1024.pth`): https://github.com/sczhou/CodeFormer/releases/tag/v0.1.0
22
+
23
+ ### 🚀 阶段 II - CodeFormer (w=0)
24
+ - 训练密码本训练预测模块:
25
+ > python -m torch.distributed.launch --nproc_per_node=gpu_num --master_port=4322 basicsr/train.py -opt options/CodeFormer_stage2.yml --launcher pytorch
26
+
27
+ - 预训练CodeFormer第二阶段模型 (`codeformer_stage2.pth`)可以在Releases v0.1.0文档里下载: https://github.com/sczhou/CodeFormer/releases/tag/v0.1.0
28
+
29
+ ### 🛸 阶段 III - CodeFormer (w=1)
30
+ - 训练可调模块:
31
+ > python -m torch.distributed.launch --nproc_per_node=gpu_num --master_port=4323 basicsr/train.py -opt options/CodeFormer_stage3.yml --launcher pytorch
32
+
33
+ - 预训练CodeFormer模型 (`codeformer.pth`)可以在Releases v0.1.0文档里下载: https://github.com/sczhou/CodeFormer/releases/tag/v0.1.0
34
+
35
+ ---
36
+
37
+ :whale: 该项目是基于[BasicSR](https://github.com/XPixelGroup/BasicSR)框架搭建,有关训练、Resume等详细介绍可以查看文档: https://github.com/XPixelGroup/BasicSR/blob/master/docs/TrainTest_CN.md
CodeFormer/facelib/detection/__init__.py ADDED
@@ -0,0 +1,100 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import os
2
+ import torch
3
+ from torch import nn
4
+ from copy import deepcopy
5
+
6
+ from facelib.utils import load_file_from_url
7
+ from facelib.utils import download_pretrained_models
8
+ from facelib.detection.yolov5face.models.common import Conv
9
+
10
+ from .retinaface.retinaface import RetinaFace
11
+ from .yolov5face.face_detector import YoloDetector
12
+
13
+
14
+ def init_detection_model(model_name, half=False, device='cuda'):
15
+ if 'retinaface' in model_name:
16
+ model = init_retinaface_model(model_name, half, device)
17
+ elif 'YOLOv5' in model_name:
18
+ model = init_yolov5face_model(model_name, device)
19
+ else:
20
+ raise NotImplementedError(f'{model_name} is not implemented.')
21
+
22
+ return model
23
+
24
+
25
+ def init_retinaface_model(model_name, half=False, device='cuda'):
26
+ if model_name == 'retinaface_resnet50':
27
+ model = RetinaFace(network_name='resnet50', half=half)
28
+ model_url = 'https://github.com/sczhou/CodeFormer/releases/download/v0.1.0/detection_Resnet50_Final.pth'
29
+ elif model_name == 'retinaface_mobile0.25':
30
+ model = RetinaFace(network_name='mobile0.25', half=half)
31
+ model_url = 'https://github.com/sczhou/CodeFormer/releases/download/v0.1.0/detection_mobilenet0.25_Final.pth'
32
+ else:
33
+ raise NotImplementedError(f'{model_name} is not implemented.')
34
+
35
+ model_path = load_file_from_url(url=model_url, model_dir='weights/facelib', progress=True, file_name=None)
36
+ load_net = torch.load(model_path, map_location=lambda storage, loc: storage)
37
+ # remove unnecessary 'module.'
38
+ for k, v in deepcopy(load_net).items():
39
+ if k.startswith('module.'):
40
+ load_net[k[7:]] = v
41
+ load_net.pop(k)
42
+ model.load_state_dict(load_net, strict=True)
43
+ model.eval()
44
+ model = model.to(device)
45
+
46
+ return model
47
+
48
+
49
+ def init_yolov5face_model(model_name, device='cuda'):
50
+ if model_name == 'YOLOv5l':
51
+ model = YoloDetector(config_name='facelib/detection/yolov5face/models/yolov5l.yaml', device=device)
52
+ model_url = 'https://github.com/sczhou/CodeFormer/releases/download/v0.1.0/yolov5l-face.pth'
53
+ elif model_name == 'YOLOv5n':
54
+ model = YoloDetector(config_name='facelib/detection/yolov5face/models/yolov5n.yaml', device=device)
55
+ model_url = 'https://github.com/sczhou/CodeFormer/releases/download/v0.1.0/yolov5n-face.pth'
56
+ else:
57
+ raise NotImplementedError(f'{model_name} is not implemented.')
58
+
59
+ model_path = load_file_from_url(url=model_url, model_dir='weights/facelib', progress=True, file_name=None)
60
+ load_net = torch.load(model_path, map_location=lambda storage, loc: storage)
61
+ model.detector.load_state_dict(load_net, strict=True)
62
+ model.detector.eval()
63
+ model.detector = model.detector.to(device).float()
64
+
65
+ for m in model.detector.modules():
66
+ if type(m) in [nn.Hardswish, nn.LeakyReLU, nn.ReLU, nn.ReLU6, nn.SiLU]:
67
+ m.inplace = True # pytorch 1.7.0 compatibility
68
+ elif isinstance(m, Conv):
69
+ m._non_persistent_buffers_set = set() # pytorch 1.6.0 compatibility
70
+
71
+ return model
72
+
73
+
74
+ # Download from Google Drive
75
+ # def init_yolov5face_model(model_name, device='cuda'):
76
+ # if model_name == 'YOLOv5l':
77
+ # model = YoloDetector(config_name='facelib/detection/yolov5face/models/yolov5l.yaml', device=device)
78
+ # f_id = {'yolov5l-face.pth': '131578zMA6B2x8VQHyHfa6GEPtulMCNzV'}
79
+ # elif model_name == 'YOLOv5n':
80
+ # model = YoloDetector(config_name='facelib/detection/yolov5face/models/yolov5n.yaml', device=device)
81
+ # f_id = {'yolov5n-face.pth': '1fhcpFvWZqghpGXjYPIne2sw1Fy4yhw6o'}
82
+ # else:
83
+ # raise NotImplementedError(f'{model_name} is not implemented.')
84
+
85
+ # model_path = os.path.join('weights/facelib', list(f_id.keys())[0])
86
+ # if not os.path.exists(model_path):
87
+ # download_pretrained_models(file_ids=f_id, save_path_root='weights/facelib')
88
+
89
+ # load_net = torch.load(model_path, map_location=lambda storage, loc: storage)
90
+ # model.detector.load_state_dict(load_net, strict=True)
91
+ # model.detector.eval()
92
+ # model.detector = model.detector.to(device).float()
93
+
94
+ # for m in model.detector.modules():
95
+ # if type(m) in [nn.Hardswish, nn.LeakyReLU, nn.ReLU, nn.ReLU6, nn.SiLU]:
96
+ # m.inplace = True # pytorch 1.7.0 compatibility
97
+ # elif isinstance(m, Conv):
98
+ # m._non_persistent_buffers_set = set() # pytorch 1.6.0 compatibility
99
+
100
+ # return model
CodeFormer/facelib/detection/align_trans.py ADDED
@@ -0,0 +1,219 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import cv2
2
+ import numpy as np
3
+
4
+ from .matlab_cp2tform import get_similarity_transform_for_cv2
5
+
6
+ # reference facial points, a list of coordinates (x,y)
7
+ REFERENCE_FACIAL_POINTS = [[30.29459953, 51.69630051], [65.53179932, 51.50139999], [48.02519989, 71.73660278],
8
+ [33.54930115, 92.3655014], [62.72990036, 92.20410156]]
9
+
10
+ DEFAULT_CROP_SIZE = (96, 112)
11
+
12
+
13
+ class FaceWarpException(Exception):
14
+
15
+ def __str__(self):
16
+ return 'In File {}:{}'.format(__file__, super.__str__(self))
17
+
18
+
19
+ def get_reference_facial_points(output_size=None, inner_padding_factor=0.0, outer_padding=(0, 0), default_square=False):
20
+ """
21
+ Function:
22
+ ----------
23
+ get reference 5 key points according to crop settings:
24
+ 0. Set default crop_size:
25
+ if default_square:
26
+ crop_size = (112, 112)
27
+ else:
28
+ crop_size = (96, 112)
29
+ 1. Pad the crop_size by inner_padding_factor in each side;
30
+ 2. Resize crop_size into (output_size - outer_padding*2),
31
+ pad into output_size with outer_padding;
32
+ 3. Output reference_5point;
33
+ Parameters:
34
+ ----------
35
+ @output_size: (w, h) or None
36
+ size of aligned face image
37
+ @inner_padding_factor: (w_factor, h_factor)
38
+ padding factor for inner (w, h)
39
+ @outer_padding: (w_pad, h_pad)
40
+ each row is a pair of coordinates (x, y)
41
+ @default_square: True or False
42
+ if True:
43
+ default crop_size = (112, 112)
44
+ else:
45
+ default crop_size = (96, 112);
46
+ !!! make sure, if output_size is not None:
47
+ (output_size - outer_padding)
48
+ = some_scale * (default crop_size * (1.0 +
49
+ inner_padding_factor))
50
+ Returns:
51
+ ----------
52
+ @reference_5point: 5x2 np.array
53
+ each row is a pair of transformed coordinates (x, y)
54
+ """
55
+
56
+ tmp_5pts = np.array(REFERENCE_FACIAL_POINTS)
57
+ tmp_crop_size = np.array(DEFAULT_CROP_SIZE)
58
+
59
+ # 0) make the inner region a square
60
+ if default_square:
61
+ size_diff = max(tmp_crop_size) - tmp_crop_size
62
+ tmp_5pts += size_diff / 2
63
+ tmp_crop_size += size_diff
64
+
65
+ if (output_size and output_size[0] == tmp_crop_size[0] and output_size[1] == tmp_crop_size[1]):
66
+
67
+ return tmp_5pts
68
+
69
+ if (inner_padding_factor == 0 and outer_padding == (0, 0)):
70
+ if output_size is None:
71
+ return tmp_5pts
72
+ else:
73
+ raise FaceWarpException('No paddings to do, output_size must be None or {}'.format(tmp_crop_size))
74
+
75
+ # check output size
76
+ if not (0 <= inner_padding_factor <= 1.0):
77
+ raise FaceWarpException('Not (0 <= inner_padding_factor <= 1.0)')
78
+
79
+ if ((inner_padding_factor > 0 or outer_padding[0] > 0 or outer_padding[1] > 0) and output_size is None):
80
+ output_size = tmp_crop_size * \
81
+ (1 + inner_padding_factor * 2).astype(np.int32)
82
+ output_size += np.array(outer_padding)
83
+ if not (outer_padding[0] < output_size[0] and outer_padding[1] < output_size[1]):
84
+ raise FaceWarpException('Not (outer_padding[0] < output_size[0] and outer_padding[1] < output_size[1])')
85
+
86
+ # 1) pad the inner region according inner_padding_factor
87
+ if inner_padding_factor > 0:
88
+ size_diff = tmp_crop_size * inner_padding_factor * 2
89
+ tmp_5pts += size_diff / 2
90
+ tmp_crop_size += np.round(size_diff).astype(np.int32)
91
+
92
+ # 2) resize the padded inner region
93
+ size_bf_outer_pad = np.array(output_size) - np.array(outer_padding) * 2
94
+
95
+ if size_bf_outer_pad[0] * tmp_crop_size[1] != size_bf_outer_pad[1] * tmp_crop_size[0]:
96
+ raise FaceWarpException('Must have (output_size - outer_padding)'
97
+ '= some_scale * (crop_size * (1.0 + inner_padding_factor)')
98
+
99
+ scale_factor = size_bf_outer_pad[0].astype(np.float32) / tmp_crop_size[0]
100
+ tmp_5pts = tmp_5pts * scale_factor
101
+ # size_diff = tmp_crop_size * (scale_factor - min(scale_factor))
102
+ # tmp_5pts = tmp_5pts + size_diff / 2
103
+ tmp_crop_size = size_bf_outer_pad
104
+
105
+ # 3) add outer_padding to make output_size
106
+ reference_5point = tmp_5pts + np.array(outer_padding)
107
+ tmp_crop_size = output_size
108
+
109
+ return reference_5point
110
+
111
+
112
+ def get_affine_transform_matrix(src_pts, dst_pts):
113
+ """
114
+ Function:
115
+ ----------
116
+ get affine transform matrix 'tfm' from src_pts to dst_pts
117
+ Parameters:
118
+ ----------
119
+ @src_pts: Kx2 np.array
120
+ source points matrix, each row is a pair of coordinates (x, y)
121
+ @dst_pts: Kx2 np.array
122
+ destination points matrix, each row is a pair of coordinates (x, y)
123
+ Returns:
124
+ ----------
125
+ @tfm: 2x3 np.array
126
+ transform matrix from src_pts to dst_pts
127
+ """
128
+
129
+ tfm = np.float32([[1, 0, 0], [0, 1, 0]])
130
+ n_pts = src_pts.shape[0]
131
+ ones = np.ones((n_pts, 1), src_pts.dtype)
132
+ src_pts_ = np.hstack([src_pts, ones])
133
+ dst_pts_ = np.hstack([dst_pts, ones])
134
+
135
+ A, res, rank, s = np.linalg.lstsq(src_pts_, dst_pts_)
136
+
137
+ if rank == 3:
138
+ tfm = np.float32([[A[0, 0], A[1, 0], A[2, 0]], [A[0, 1], A[1, 1], A[2, 1]]])
139
+ elif rank == 2:
140
+ tfm = np.float32([[A[0, 0], A[1, 0], 0], [A[0, 1], A[1, 1], 0]])
141
+
142
+ return tfm
143
+
144
+
145
+ def warp_and_crop_face(src_img, facial_pts, reference_pts=None, crop_size=(96, 112), align_type='smilarity'):
146
+ """
147
+ Function:
148
+ ----------
149
+ apply affine transform 'trans' to uv
150
+ Parameters:
151
+ ----------
152
+ @src_img: 3x3 np.array
153
+ input image
154
+ @facial_pts: could be
155
+ 1)a list of K coordinates (x,y)
156
+ or
157
+ 2) Kx2 or 2xK np.array
158
+ each row or col is a pair of coordinates (x, y)
159
+ @reference_pts: could be
160
+ 1) a list of K coordinates (x,y)
161
+ or
162
+ 2) Kx2 or 2xK np.array
163
+ each row or col is a pair of coordinates (x, y)
164
+ or
165
+ 3) None
166
+ if None, use default reference facial points
167
+ @crop_size: (w, h)
168
+ output face image size
169
+ @align_type: transform type, could be one of
170
+ 1) 'similarity': use similarity transform
171
+ 2) 'cv2_affine': use the first 3 points to do affine transform,
172
+ by calling cv2.getAffineTransform()
173
+ 3) 'affine': use all points to do affine transform
174
+ Returns:
175
+ ----------
176
+ @face_img: output face image with size (w, h) = @crop_size
177
+ """
178
+
179
+ if reference_pts is None:
180
+ if crop_size[0] == 96 and crop_size[1] == 112:
181
+ reference_pts = REFERENCE_FACIAL_POINTS
182
+ else:
183
+ default_square = False
184
+ inner_padding_factor = 0
185
+ outer_padding = (0, 0)
186
+ output_size = crop_size
187
+
188
+ reference_pts = get_reference_facial_points(output_size, inner_padding_factor, outer_padding,
189
+ default_square)
190
+
191
+ ref_pts = np.float32(reference_pts)
192
+ ref_pts_shp = ref_pts.shape
193
+ if max(ref_pts_shp) < 3 or min(ref_pts_shp) != 2:
194
+ raise FaceWarpException('reference_pts.shape must be (K,2) or (2,K) and K>2')
195
+
196
+ if ref_pts_shp[0] == 2:
197
+ ref_pts = ref_pts.T
198
+
199
+ src_pts = np.float32(facial_pts)
200
+ src_pts_shp = src_pts.shape
201
+ if max(src_pts_shp) < 3 or min(src_pts_shp) != 2:
202
+ raise FaceWarpException('facial_pts.shape must be (K,2) or (2,K) and K>2')
203
+
204
+ if src_pts_shp[0] == 2:
205
+ src_pts = src_pts.T
206
+
207
+ if src_pts.shape != ref_pts.shape:
208
+ raise FaceWarpException('facial_pts and reference_pts must have the same shape')
209
+
210
+ if align_type == 'cv2_affine':
211
+ tfm = cv2.getAffineTransform(src_pts[0:3], ref_pts[0:3])
212
+ elif align_type == 'affine':
213
+ tfm = get_affine_transform_matrix(src_pts, ref_pts)
214
+ else:
215
+ tfm = get_similarity_transform_for_cv2(src_pts, ref_pts)
216
+
217
+ face_img = cv2.warpAffine(src_img, tfm, (crop_size[0], crop_size[1]))
218
+
219
+ return face_img
CodeFormer/facelib/detection/matlab_cp2tform.py ADDED
@@ -0,0 +1,317 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import numpy as np
2
+ from numpy.linalg import inv, lstsq
3
+ from numpy.linalg import matrix_rank as rank
4
+ from numpy.linalg import norm
5
+
6
+
7
+ class MatlabCp2tormException(Exception):
8
+
9
+ def __str__(self):
10
+ return 'In File {}:{}'.format(__file__, super.__str__(self))
11
+
12
+
13
+ def tformfwd(trans, uv):
14
+ """
15
+ Function:
16
+ ----------
17
+ apply affine transform 'trans' to uv
18
+
19
+ Parameters:
20
+ ----------
21
+ @trans: 3x3 np.array
22
+ transform matrix
23
+ @uv: Kx2 np.array
24
+ each row is a pair of coordinates (x, y)
25
+
26
+ Returns:
27
+ ----------
28
+ @xy: Kx2 np.array
29
+ each row is a pair of transformed coordinates (x, y)
30
+ """
31
+ uv = np.hstack((uv, np.ones((uv.shape[0], 1))))
32
+ xy = np.dot(uv, trans)
33
+ xy = xy[:, 0:-1]
34
+ return xy
35
+
36
+
37
+ def tforminv(trans, uv):
38
+ """
39
+ Function:
40
+ ----------
41
+ apply the inverse of affine transform 'trans' to uv
42
+
43
+ Parameters:
44
+ ----------
45
+ @trans: 3x3 np.array
46
+ transform matrix
47
+ @uv: Kx2 np.array
48
+ each row is a pair of coordinates (x, y)
49
+
50
+ Returns:
51
+ ----------
52
+ @xy: Kx2 np.array
53
+ each row is a pair of inverse-transformed coordinates (x, y)
54
+ """
55
+ Tinv = inv(trans)
56
+ xy = tformfwd(Tinv, uv)
57
+ return xy
58
+
59
+
60
+ def findNonreflectiveSimilarity(uv, xy, options=None):
61
+ options = {'K': 2}
62
+
63
+ K = options['K']
64
+ M = xy.shape[0]
65
+ x = xy[:, 0].reshape((-1, 1)) # use reshape to keep a column vector
66
+ y = xy[:, 1].reshape((-1, 1)) # use reshape to keep a column vector
67
+
68
+ tmp1 = np.hstack((x, y, np.ones((M, 1)), np.zeros((M, 1))))
69
+ tmp2 = np.hstack((y, -x, np.zeros((M, 1)), np.ones((M, 1))))
70
+ X = np.vstack((tmp1, tmp2))
71
+
72
+ u = uv[:, 0].reshape((-1, 1)) # use reshape to keep a column vector
73
+ v = uv[:, 1].reshape((-1, 1)) # use reshape to keep a column vector
74
+ U = np.vstack((u, v))
75
+
76
+ # We know that X * r = U
77
+ if rank(X) >= 2 * K:
78
+ r, _, _, _ = lstsq(X, U, rcond=-1)
79
+ r = np.squeeze(r)
80
+ else:
81
+ raise Exception('cp2tform:twoUniquePointsReq')
82
+ sc = r[0]
83
+ ss = r[1]
84
+ tx = r[2]
85
+ ty = r[3]
86
+
87
+ Tinv = np.array([[sc, -ss, 0], [ss, sc, 0], [tx, ty, 1]])
88
+ T = inv(Tinv)
89
+ T[:, 2] = np.array([0, 0, 1])
90
+
91
+ return T, Tinv
92
+
93
+
94
+ def findSimilarity(uv, xy, options=None):
95
+ options = {'K': 2}
96
+
97
+ # uv = np.array(uv)
98
+ # xy = np.array(xy)
99
+
100
+ # Solve for trans1
101
+ trans1, trans1_inv = findNonreflectiveSimilarity(uv, xy, options)
102
+
103
+ # Solve for trans2
104
+
105
+ # manually reflect the xy data across the Y-axis
106
+ xyR = xy
107
+ xyR[:, 0] = -1 * xyR[:, 0]
108
+
109
+ trans2r, trans2r_inv = findNonreflectiveSimilarity(uv, xyR, options)
110
+
111
+ # manually reflect the tform to undo the reflection done on xyR
112
+ TreflectY = np.array([[-1, 0, 0], [0, 1, 0], [0, 0, 1]])
113
+
114
+ trans2 = np.dot(trans2r, TreflectY)
115
+
116
+ # Figure out if trans1 or trans2 is better
117
+ xy1 = tformfwd(trans1, uv)
118
+ norm1 = norm(xy1 - xy)
119
+
120
+ xy2 = tformfwd(trans2, uv)
121
+ norm2 = norm(xy2 - xy)
122
+
123
+ if norm1 <= norm2:
124
+ return trans1, trans1_inv
125
+ else:
126
+ trans2_inv = inv(trans2)
127
+ return trans2, trans2_inv
128
+
129
+
130
+ def get_similarity_transform(src_pts, dst_pts, reflective=True):
131
+ """
132
+ Function:
133
+ ----------
134
+ Find Similarity Transform Matrix 'trans':
135
+ u = src_pts[:, 0]
136
+ v = src_pts[:, 1]
137
+ x = dst_pts[:, 0]
138
+ y = dst_pts[:, 1]
139
+ [x, y, 1] = [u, v, 1] * trans
140
+
141
+ Parameters:
142
+ ----------
143
+ @src_pts: Kx2 np.array
144
+ source points, each row is a pair of coordinates (x, y)
145
+ @dst_pts: Kx2 np.array
146
+ destination points, each row is a pair of transformed
147
+ coordinates (x, y)
148
+ @reflective: True or False
149
+ if True:
150
+ use reflective similarity transform
151
+ else:
152
+ use non-reflective similarity transform
153
+
154
+ Returns:
155
+ ----------
156
+ @trans: 3x3 np.array
157
+ transform matrix from uv to xy
158
+ trans_inv: 3x3 np.array
159
+ inverse of trans, transform matrix from xy to uv
160
+ """
161
+
162
+ if reflective:
163
+ trans, trans_inv = findSimilarity(src_pts, dst_pts)
164
+ else:
165
+ trans, trans_inv = findNonreflectiveSimilarity(src_pts, dst_pts)
166
+
167
+ return trans, trans_inv
168
+
169
+
170
+ def cvt_tform_mat_for_cv2(trans):
171
+ """
172
+ Function:
173
+ ----------
174
+ Convert Transform Matrix 'trans' into 'cv2_trans' which could be
175
+ directly used by cv2.warpAffine():
176
+ u = src_pts[:, 0]
177
+ v = src_pts[:, 1]
178
+ x = dst_pts[:, 0]
179
+ y = dst_pts[:, 1]
180
+ [x, y].T = cv_trans * [u, v, 1].T
181
+
182
+ Parameters:
183
+ ----------
184
+ @trans: 3x3 np.array
185
+ transform matrix from uv to xy
186
+
187
+ Returns:
188
+ ----------
189
+ @cv2_trans: 2x3 np.array
190
+ transform matrix from src_pts to dst_pts, could be directly used
191
+ for cv2.warpAffine()
192
+ """
193
+ cv2_trans = trans[:, 0:2].T
194
+
195
+ return cv2_trans
196
+
197
+
198
+ def get_similarity_transform_for_cv2(src_pts, dst_pts, reflective=True):
199
+ """
200
+ Function:
201
+ ----------
202
+ Find Similarity Transform Matrix 'cv2_trans' which could be
203
+ directly used by cv2.warpAffine():
204
+ u = src_pts[:, 0]
205
+ v = src_pts[:, 1]
206
+ x = dst_pts[:, 0]
207
+ y = dst_pts[:, 1]
208
+ [x, y].T = cv_trans * [u, v, 1].T
209
+
210
+ Parameters:
211
+ ----------
212
+ @src_pts: Kx2 np.array
213
+ source points, each row is a pair of coordinates (x, y)
214
+ @dst_pts: Kx2 np.array
215
+ destination points, each row is a pair of transformed
216
+ coordinates (x, y)
217
+ reflective: True or False
218
+ if True:
219
+ use reflective similarity transform
220
+ else:
221
+ use non-reflective similarity transform
222
+
223
+ Returns:
224
+ ----------
225
+ @cv2_trans: 2x3 np.array
226
+ transform matrix from src_pts to dst_pts, could be directly used
227
+ for cv2.warpAffine()
228
+ """
229
+ trans, trans_inv = get_similarity_transform(src_pts, dst_pts, reflective)
230
+ cv2_trans = cvt_tform_mat_for_cv2(trans)
231
+
232
+ return cv2_trans
233
+
234
+
235
+ if __name__ == '__main__':
236
+ """
237
+ u = [0, 6, -2]
238
+ v = [0, 3, 5]
239
+ x = [-1, 0, 4]
240
+ y = [-1, -10, 4]
241
+
242
+ # In Matlab, run:
243
+ #
244
+ # uv = [u'; v'];
245
+ # xy = [x'; y'];
246
+ # tform_sim=cp2tform(uv,xy,'similarity');
247
+ #
248
+ # trans = tform_sim.tdata.T
249
+ # ans =
250
+ # -0.0764 -1.6190 0
251
+ # 1.6190 -0.0764 0
252
+ # -3.2156 0.0290 1.0000
253
+ # trans_inv = tform_sim.tdata.Tinv
254
+ # ans =
255
+ #
256
+ # -0.0291 0.6163 0
257
+ # -0.6163 -0.0291 0
258
+ # -0.0756 1.9826 1.0000
259
+ # xy_m=tformfwd(tform_sim, u,v)
260
+ #
261
+ # xy_m =
262
+ #
263
+ # -3.2156 0.0290
264
+ # 1.1833 -9.9143
265
+ # 5.0323 2.8853
266
+ # uv_m=tforminv(tform_sim, x,y)
267
+ #
268
+ # uv_m =
269
+ #
270
+ # 0.5698 1.3953
271
+ # 6.0872 2.2733
272
+ # -2.6570 4.3314
273
+ """
274
+ u = [0, 6, -2]
275
+ v = [0, 3, 5]
276
+ x = [-1, 0, 4]
277
+ y = [-1, -10, 4]
278
+
279
+ uv = np.array((u, v)).T
280
+ xy = np.array((x, y)).T
281
+
282
+ print('\n--->uv:')
283
+ print(uv)
284
+ print('\n--->xy:')
285
+ print(xy)
286
+
287
+ trans, trans_inv = get_similarity_transform(uv, xy)
288
+
289
+ print('\n--->trans matrix:')
290
+ print(trans)
291
+
292
+ print('\n--->trans_inv matrix:')
293
+ print(trans_inv)
294
+
295
+ print('\n---> apply transform to uv')
296
+ print('\nxy_m = uv_augmented * trans')
297
+ uv_aug = np.hstack((uv, np.ones((uv.shape[0], 1))))
298
+ xy_m = np.dot(uv_aug, trans)
299
+ print(xy_m)
300
+
301
+ print('\nxy_m = tformfwd(trans, uv)')
302
+ xy_m = tformfwd(trans, uv)
303
+ print(xy_m)
304
+
305
+ print('\n---> apply inverse transform to xy')
306
+ print('\nuv_m = xy_augmented * trans_inv')
307
+ xy_aug = np.hstack((xy, np.ones((xy.shape[0], 1))))
308
+ uv_m = np.dot(xy_aug, trans_inv)
309
+ print(uv_m)
310
+
311
+ print('\nuv_m = tformfwd(trans_inv, xy)')
312
+ uv_m = tformfwd(trans_inv, xy)
313
+ print(uv_m)
314
+
315
+ uv_m = tforminv(trans, xy)
316
+ print('\nuv_m = tforminv(trans, xy)')
317
+ print(uv_m)
CodeFormer/facelib/detection/retinaface/retinaface.py ADDED
@@ -0,0 +1,372 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import cv2
2
+ import numpy as np
3
+ import torch
4
+ import torch.nn as nn
5
+ import torch.nn.functional as F
6
+ from PIL import Image
7
+ from torchvision.models._utils import IntermediateLayerGetter as IntermediateLayerGetter
8
+
9
+ from facelib.detection.align_trans import get_reference_facial_points, warp_and_crop_face
10
+ from facelib.detection.retinaface.retinaface_net import FPN, SSH, MobileNetV1, make_bbox_head, make_class_head, make_landmark_head
11
+ from facelib.detection.retinaface.retinaface_utils import (PriorBox, batched_decode, batched_decode_landm, decode, decode_landm,
12
+ py_cpu_nms)
13
+
14
+ from basicsr.utils.misc import get_device
15
+ # device = torch.device('cuda' if torch.cuda.is_available() else 'cpu')
16
+ device = get_device()
17
+
18
+
19
+ def generate_config(network_name):
20
+
21
+ cfg_mnet = {
22
+ 'name': 'mobilenet0.25',
23
+ 'min_sizes': [[16, 32], [64, 128], [256, 512]],
24
+ 'steps': [8, 16, 32],
25
+ 'variance': [0.1, 0.2],
26
+ 'clip': False,
27
+ 'loc_weight': 2.0,
28
+ 'gpu_train': True,
29
+ 'batch_size': 32,
30
+ 'ngpu': 1,
31
+ 'epoch': 250,
32
+ 'decay1': 190,
33
+ 'decay2': 220,
34
+ 'image_size': 640,
35
+ 'return_layers': {
36
+ 'stage1': 1,
37
+ 'stage2': 2,
38
+ 'stage3': 3
39
+ },
40
+ 'in_channel': 32,
41
+ 'out_channel': 64
42
+ }
43
+
44
+ cfg_re50 = {
45
+ 'name': 'Resnet50',
46
+ 'min_sizes': [[16, 32], [64, 128], [256, 512]],
47
+ 'steps': [8, 16, 32],
48
+ 'variance': [0.1, 0.2],
49
+ 'clip': False,
50
+ 'loc_weight': 2.0,
51
+ 'gpu_train': True,
52
+ 'batch_size': 24,
53
+ 'ngpu': 4,
54
+ 'epoch': 100,
55
+ 'decay1': 70,
56
+ 'decay2': 90,
57
+ 'image_size': 840,
58
+ 'return_layers': {
59
+ 'layer2': 1,
60
+ 'layer3': 2,
61
+ 'layer4': 3
62
+ },
63
+ 'in_channel': 256,
64
+ 'out_channel': 256
65
+ }
66
+
67
+ if network_name == 'mobile0.25':
68
+ return cfg_mnet
69
+ elif network_name == 'resnet50':
70
+ return cfg_re50
71
+ else:
72
+ raise NotImplementedError(f'network_name={network_name}')
73
+
74
+
75
+ class RetinaFace(nn.Module):
76
+
77
+ def __init__(self, network_name='resnet50', half=False, phase='test'):
78
+ super(RetinaFace, self).__init__()
79
+ self.half_inference = half
80
+ cfg = generate_config(network_name)
81
+ self.backbone = cfg['name']
82
+
83
+ self.model_name = f'retinaface_{network_name}'
84
+ self.cfg = cfg
85
+ self.phase = phase
86
+ self.target_size, self.max_size = 1600, 2150
87
+ self.resize, self.scale, self.scale1 = 1., None, None
88
+ self.mean_tensor = torch.tensor([[[[104.]], [[117.]], [[123.]]]]).to(device)
89
+ self.reference = get_reference_facial_points(default_square=True)
90
+ # Build network.
91
+ backbone = None
92
+ if cfg['name'] == 'mobilenet0.25':
93
+ backbone = MobileNetV1()
94
+ self.body = IntermediateLayerGetter(backbone, cfg['return_layers'])
95
+ elif cfg['name'] == 'Resnet50':
96
+ import torchvision.models as models
97
+ backbone = models.resnet50(pretrained=False)
98
+ self.body = IntermediateLayerGetter(backbone, cfg['return_layers'])
99
+
100
+ in_channels_stage2 = cfg['in_channel']
101
+ in_channels_list = [
102
+ in_channels_stage2 * 2,
103
+ in_channels_stage2 * 4,
104
+ in_channels_stage2 * 8,
105
+ ]
106
+
107
+ out_channels = cfg['out_channel']
108
+ self.fpn = FPN(in_channels_list, out_channels)
109
+ self.ssh1 = SSH(out_channels, out_channels)
110
+ self.ssh2 = SSH(out_channels, out_channels)
111
+ self.ssh3 = SSH(out_channels, out_channels)
112
+
113
+ self.ClassHead = make_class_head(fpn_num=3, inchannels=cfg['out_channel'])
114
+ self.BboxHead = make_bbox_head(fpn_num=3, inchannels=cfg['out_channel'])
115
+ self.LandmarkHead = make_landmark_head(fpn_num=3, inchannels=cfg['out_channel'])
116
+
117
+ self.to(device)
118
+ self.eval()
119
+ if self.half_inference:
120
+ self.half()
121
+
122
+ def forward(self, inputs):
123
+ out = self.body(inputs)
124
+
125
+ if self.backbone == 'mobilenet0.25' or self.backbone == 'Resnet50':
126
+ out = list(out.values())
127
+ # FPN
128
+ fpn = self.fpn(out)
129
+
130
+ # SSH
131
+ feature1 = self.ssh1(fpn[0])
132
+ feature2 = self.ssh2(fpn[1])
133
+ feature3 = self.ssh3(fpn[2])
134
+ features = [feature1, feature2, feature3]
135
+
136
+ bbox_regressions = torch.cat([self.BboxHead[i](feature) for i, feature in enumerate(features)], dim=1)
137
+ classifications = torch.cat([self.ClassHead[i](feature) for i, feature in enumerate(features)], dim=1)
138
+ tmp = [self.LandmarkHead[i](feature) for i, feature in enumerate(features)]
139
+ ldm_regressions = (torch.cat(tmp, dim=1))
140
+
141
+ if self.phase == 'train':
142
+ output = (bbox_regressions, classifications, ldm_regressions)
143
+ else:
144
+ output = (bbox_regressions, F.softmax(classifications, dim=-1), ldm_regressions)
145
+ return output
146
+
147
+ def __detect_faces(self, inputs):
148
+ # get scale
149
+ height, width = inputs.shape[2:]
150
+ self.scale = torch.tensor([width, height, width, height], dtype=torch.float32).to(device)
151
+ tmp = [width, height, width, height, width, height, width, height, width, height]
152
+ self.scale1 = torch.tensor(tmp, dtype=torch.float32).to(device)
153
+
154
+ # forawrd
155
+ inputs = inputs.to(device)
156
+ if self.half_inference:
157
+ inputs = inputs.half()
158
+ loc, conf, landmarks = self(inputs)
159
+
160
+ # get priorbox
161
+ priorbox = PriorBox(self.cfg, image_size=inputs.shape[2:])
162
+ priors = priorbox.forward().to(device)
163
+
164
+ return loc, conf, landmarks, priors
165
+
166
+ # single image detection
167
+ def transform(self, image, use_origin_size):
168
+ # convert to opencv format
169
+ if isinstance(image, Image.Image):
170
+ image = cv2.cvtColor(np.asarray(image), cv2.COLOR_RGB2BGR)
171
+ image = image.astype(np.float32)
172
+
173
+ # testing scale
174
+ im_size_min = np.min(image.shape[0:2])
175
+ im_size_max = np.max(image.shape[0:2])
176
+ resize = float(self.target_size) / float(im_size_min)
177
+
178
+ # prevent bigger axis from being more than max_size
179
+ if np.round(resize * im_size_max) > self.max_size:
180
+ resize = float(self.max_size) / float(im_size_max)
181
+ resize = 1 if use_origin_size else resize
182
+
183
+ # resize
184
+ if resize != 1:
185
+ image = cv2.resize(image, None, None, fx=resize, fy=resize, interpolation=cv2.INTER_LINEAR)
186
+
187
+ # convert to torch.tensor format
188
+ # image -= (104, 117, 123)
189
+ image = image.transpose(2, 0, 1)
190
+ image = torch.from_numpy(image).unsqueeze(0)
191
+
192
+ return image, resize
193
+
194
+ def detect_faces(
195
+ self,
196
+ image,
197
+ conf_threshold=0.8,
198
+ nms_threshold=0.4,
199
+ use_origin_size=True,
200
+ ):
201
+ """
202
+ Params:
203
+ imgs: BGR image
204
+ """
205
+ image, self.resize = self.transform(image, use_origin_size)
206
+ image = image.to(device)
207
+ if self.half_inference:
208
+ image = image.half()
209
+ image = image - self.mean_tensor
210
+
211
+ loc, conf, landmarks, priors = self.__detect_faces(image)
212
+
213
+ boxes = decode(loc.data.squeeze(0), priors.data, self.cfg['variance'])
214
+ boxes = boxes * self.scale / self.resize
215
+ boxes = boxes.cpu().numpy()
216
+
217
+ scores = conf.squeeze(0).data.cpu().numpy()[:, 1]
218
+
219
+ landmarks = decode_landm(landmarks.squeeze(0), priors, self.cfg['variance'])
220
+ landmarks = landmarks * self.scale1 / self.resize
221
+ landmarks = landmarks.cpu().numpy()
222
+
223
+ # ignore low scores
224
+ inds = np.where(scores > conf_threshold)[0]
225
+ boxes, landmarks, scores = boxes[inds], landmarks[inds], scores[inds]
226
+
227
+ # sort
228
+ order = scores.argsort()[::-1]
229
+ boxes, landmarks, scores = boxes[order], landmarks[order], scores[order]
230
+
231
+ # do NMS
232
+ bounding_boxes = np.hstack((boxes, scores[:, np.newaxis])).astype(np.float32, copy=False)
233
+ keep = py_cpu_nms(bounding_boxes, nms_threshold)
234
+ bounding_boxes, landmarks = bounding_boxes[keep, :], landmarks[keep]
235
+ # self.t['forward_pass'].toc()
236
+ # print(self.t['forward_pass'].average_time)
237
+ # import sys
238
+ # sys.stdout.flush()
239
+ return np.concatenate((bounding_boxes, landmarks), axis=1)
240
+
241
+ def __align_multi(self, image, boxes, landmarks, limit=None):
242
+
243
+ if len(boxes) < 1:
244
+ return [], []
245
+
246
+ if limit:
247
+ boxes = boxes[:limit]
248
+ landmarks = landmarks[:limit]
249
+
250
+ faces = []
251
+ for landmark in landmarks:
252
+ facial5points = [[landmark[2 * j], landmark[2 * j + 1]] for j in range(5)]
253
+
254
+ warped_face = warp_and_crop_face(np.array(image), facial5points, self.reference, crop_size=(112, 112))
255
+ faces.append(warped_face)
256
+
257
+ return np.concatenate((boxes, landmarks), axis=1), faces
258
+
259
+ def align_multi(self, img, conf_threshold=0.8, limit=None):
260
+
261
+ rlt = self.detect_faces(img, conf_threshold=conf_threshold)
262
+ boxes, landmarks = rlt[:, 0:5], rlt[:, 5:]
263
+
264
+ return self.__align_multi(img, boxes, landmarks, limit)
265
+
266
+ # batched detection
267
+ def batched_transform(self, frames, use_origin_size):
268
+ """
269
+ Arguments:
270
+ frames: a list of PIL.Image, or torch.Tensor(shape=[n, h, w, c],
271
+ type=np.float32, BGR format).
272
+ use_origin_size: whether to use origin size.
273
+ """
274
+ from_PIL = True if isinstance(frames[0], Image.Image) else False
275
+
276
+ # convert to opencv format
277
+ if from_PIL:
278
+ frames = [cv2.cvtColor(np.asarray(frame), cv2.COLOR_RGB2BGR) for frame in frames]
279
+ frames = np.asarray(frames, dtype=np.float32)
280
+
281
+ # testing scale
282
+ im_size_min = np.min(frames[0].shape[0:2])
283
+ im_size_max = np.max(frames[0].shape[0:2])
284
+ resize = float(self.target_size) / float(im_size_min)
285
+
286
+ # prevent bigger axis from being more than max_size
287
+ if np.round(resize * im_size_max) > self.max_size:
288
+ resize = float(self.max_size) / float(im_size_max)
289
+ resize = 1 if use_origin_size else resize
290
+
291
+ # resize
292
+ if resize != 1:
293
+ if not from_PIL:
294
+ frames = F.interpolate(frames, scale_factor=resize)
295
+ else:
296
+ frames = [
297
+ cv2.resize(frame, None, None, fx=resize, fy=resize, interpolation=cv2.INTER_LINEAR)
298
+ for frame in frames
299
+ ]
300
+
301
+ # convert to torch.tensor format
302
+ if not from_PIL:
303
+ frames = frames.transpose(1, 2).transpose(1, 3).contiguous()
304
+ else:
305
+ frames = frames.transpose((0, 3, 1, 2))
306
+ frames = torch.from_numpy(frames)
307
+
308
+ return frames, resize
309
+
310
+ def batched_detect_faces(self, frames, conf_threshold=0.8, nms_threshold=0.4, use_origin_size=True):
311
+ """
312
+ Arguments:
313
+ frames: a list of PIL.Image, or np.array(shape=[n, h, w, c],
314
+ type=np.uint8, BGR format).
315
+ conf_threshold: confidence threshold.
316
+ nms_threshold: nms threshold.
317
+ use_origin_size: whether to use origin size.
318
+ Returns:
319
+ final_bounding_boxes: list of np.array ([n_boxes, 5],
320
+ type=np.float32).
321
+ final_landmarks: list of np.array ([n_boxes, 10], type=np.float32).
322
+ """
323
+ # self.t['forward_pass'].tic()
324
+ frames, self.resize = self.batched_transform(frames, use_origin_size)
325
+ frames = frames.to(device)
326
+ frames = frames - self.mean_tensor
327
+
328
+ b_loc, b_conf, b_landmarks, priors = self.__detect_faces(frames)
329
+
330
+ final_bounding_boxes, final_landmarks = [], []
331
+
332
+ # decode
333
+ priors = priors.unsqueeze(0)
334
+ b_loc = batched_decode(b_loc, priors, self.cfg['variance']) * self.scale / self.resize
335
+ b_landmarks = batched_decode_landm(b_landmarks, priors, self.cfg['variance']) * self.scale1 / self.resize
336
+ b_conf = b_conf[:, :, 1]
337
+
338
+ # index for selection
339
+ b_indice = b_conf > conf_threshold
340
+
341
+ # concat
342
+ b_loc_and_conf = torch.cat((b_loc, b_conf.unsqueeze(-1)), dim=2).float()
343
+
344
+ for pred, landm, inds in zip(b_loc_and_conf, b_landmarks, b_indice):
345
+
346
+ # ignore low scores
347
+ pred, landm = pred[inds, :], landm[inds, :]
348
+ if pred.shape[0] == 0:
349
+ final_bounding_boxes.append(np.array([], dtype=np.float32))
350
+ final_landmarks.append(np.array([], dtype=np.float32))
351
+ continue
352
+
353
+ # sort
354
+ # order = score.argsort(descending=True)
355
+ # box, landm, score = box[order], landm[order], score[order]
356
+
357
+ # to CPU
358
+ bounding_boxes, landm = pred.cpu().numpy(), landm.cpu().numpy()
359
+
360
+ # NMS
361
+ keep = py_cpu_nms(bounding_boxes, nms_threshold)
362
+ bounding_boxes, landmarks = bounding_boxes[keep, :], landm[keep]
363
+
364
+ # append
365
+ final_bounding_boxes.append(bounding_boxes)
366
+ final_landmarks.append(landmarks)
367
+ # self.t['forward_pass'].toc(average=True)
368
+ # self.batch_time += self.t['forward_pass'].diff
369
+ # self.total_frame += len(frames)
370
+ # print(self.batch_time / self.total_frame)
371
+
372
+ return final_bounding_boxes, final_landmarks
CodeFormer/facelib/detection/retinaface/retinaface_net.py ADDED
@@ -0,0 +1,196 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import torch
2
+ import torch.nn as nn
3
+ import torch.nn.functional as F
4
+
5
+
6
+ def conv_bn(inp, oup, stride=1, leaky=0):
7
+ return nn.Sequential(
8
+ nn.Conv2d(inp, oup, 3, stride, 1, bias=False), nn.BatchNorm2d(oup),
9
+ nn.LeakyReLU(negative_slope=leaky, inplace=True))
10
+
11
+
12
+ def conv_bn_no_relu(inp, oup, stride):
13
+ return nn.Sequential(
14
+ nn.Conv2d(inp, oup, 3, stride, 1, bias=False),
15
+ nn.BatchNorm2d(oup),
16
+ )
17
+
18
+
19
+ def conv_bn1X1(inp, oup, stride, leaky=0):
20
+ return nn.Sequential(
21
+ nn.Conv2d(inp, oup, 1, stride, padding=0, bias=False), nn.BatchNorm2d(oup),
22
+ nn.LeakyReLU(negative_slope=leaky, inplace=True))
23
+
24
+
25
+ def conv_dw(inp, oup, stride, leaky=0.1):
26
+ return nn.Sequential(
27
+ nn.Conv2d(inp, inp, 3, stride, 1, groups=inp, bias=False),
28
+ nn.BatchNorm2d(inp),
29
+ nn.LeakyReLU(negative_slope=leaky, inplace=True),
30
+ nn.Conv2d(inp, oup, 1, 1, 0, bias=False),
31
+ nn.BatchNorm2d(oup),
32
+ nn.LeakyReLU(negative_slope=leaky, inplace=True),
33
+ )
34
+
35
+
36
+ class SSH(nn.Module):
37
+
38
+ def __init__(self, in_channel, out_channel):
39
+ super(SSH, self).__init__()
40
+ assert out_channel % 4 == 0
41
+ leaky = 0
42
+ if (out_channel <= 64):
43
+ leaky = 0.1
44
+ self.conv3X3 = conv_bn_no_relu(in_channel, out_channel // 2, stride=1)
45
+
46
+ self.conv5X5_1 = conv_bn(in_channel, out_channel // 4, stride=1, leaky=leaky)
47
+ self.conv5X5_2 = conv_bn_no_relu(out_channel // 4, out_channel // 4, stride=1)
48
+
49
+ self.conv7X7_2 = conv_bn(out_channel // 4, out_channel // 4, stride=1, leaky=leaky)
50
+ self.conv7x7_3 = conv_bn_no_relu(out_channel // 4, out_channel // 4, stride=1)
51
+
52
+ def forward(self, input):
53
+ conv3X3 = self.conv3X3(input)
54
+
55
+ conv5X5_1 = self.conv5X5_1(input)
56
+ conv5X5 = self.conv5X5_2(conv5X5_1)
57
+
58
+ conv7X7_2 = self.conv7X7_2(conv5X5_1)
59
+ conv7X7 = self.conv7x7_3(conv7X7_2)
60
+
61
+ out = torch.cat([conv3X3, conv5X5, conv7X7], dim=1)
62
+ out = F.relu(out)
63
+ return out
64
+
65
+
66
+ class FPN(nn.Module):
67
+
68
+ def __init__(self, in_channels_list, out_channels):
69
+ super(FPN, self).__init__()
70
+ leaky = 0
71
+ if (out_channels <= 64):
72
+ leaky = 0.1
73
+ self.output1 = conv_bn1X1(in_channels_list[0], out_channels, stride=1, leaky=leaky)
74
+ self.output2 = conv_bn1X1(in_channels_list[1], out_channels, stride=1, leaky=leaky)
75
+ self.output3 = conv_bn1X1(in_channels_list[2], out_channels, stride=1, leaky=leaky)
76
+
77
+ self.merge1 = conv_bn(out_channels, out_channels, leaky=leaky)
78
+ self.merge2 = conv_bn(out_channels, out_channels, leaky=leaky)
79
+
80
+ def forward(self, input):
81
+ # names = list(input.keys())
82
+ # input = list(input.values())
83
+
84
+ output1 = self.output1(input[0])
85
+ output2 = self.output2(input[1])
86
+ output3 = self.output3(input[2])
87
+
88
+ up3 = F.interpolate(output3, size=[output2.size(2), output2.size(3)], mode='nearest')
89
+ output2 = output2 + up3
90
+ output2 = self.merge2(output2)
91
+
92
+ up2 = F.interpolate(output2, size=[output1.size(2), output1.size(3)], mode='nearest')
93
+ output1 = output1 + up2
94
+ output1 = self.merge1(output1)
95
+
96
+ out = [output1, output2, output3]
97
+ return out
98
+
99
+
100
+ class MobileNetV1(nn.Module):
101
+
102
+ def __init__(self):
103
+ super(MobileNetV1, self).__init__()
104
+ self.stage1 = nn.Sequential(
105
+ conv_bn(3, 8, 2, leaky=0.1), # 3
106
+ conv_dw(8, 16, 1), # 7
107
+ conv_dw(16, 32, 2), # 11
108
+ conv_dw(32, 32, 1), # 19
109
+ conv_dw(32, 64, 2), # 27
110
+ conv_dw(64, 64, 1), # 43
111
+ )
112
+ self.stage2 = nn.Sequential(
113
+ conv_dw(64, 128, 2), # 43 + 16 = 59
114
+ conv_dw(128, 128, 1), # 59 + 32 = 91
115
+ conv_dw(128, 128, 1), # 91 + 32 = 123
116
+ conv_dw(128, 128, 1), # 123 + 32 = 155
117
+ conv_dw(128, 128, 1), # 155 + 32 = 187
118
+ conv_dw(128, 128, 1), # 187 + 32 = 219
119
+ )
120
+ self.stage3 = nn.Sequential(
121
+ conv_dw(128, 256, 2), # 219 +3 2 = 241
122
+ conv_dw(256, 256, 1), # 241 + 64 = 301
123
+ )
124
+ self.avg = nn.AdaptiveAvgPool2d((1, 1))
125
+ self.fc = nn.Linear(256, 1000)
126
+
127
+ def forward(self, x):
128
+ x = self.stage1(x)
129
+ x = self.stage2(x)
130
+ x = self.stage3(x)
131
+ x = self.avg(x)
132
+ # x = self.model(x)
133
+ x = x.view(-1, 256)
134
+ x = self.fc(x)
135
+ return x
136
+
137
+
138
+ class ClassHead(nn.Module):
139
+
140
+ def __init__(self, inchannels=512, num_anchors=3):
141
+ super(ClassHead, self).__init__()
142
+ self.num_anchors = num_anchors
143
+ self.conv1x1 = nn.Conv2d(inchannels, self.num_anchors * 2, kernel_size=(1, 1), stride=1, padding=0)
144
+
145
+ def forward(self, x):
146
+ out = self.conv1x1(x)
147
+ out = out.permute(0, 2, 3, 1).contiguous()
148
+
149
+ return out.view(out.shape[0], -1, 2)
150
+
151
+
152
+ class BboxHead(nn.Module):
153
+
154
+ def __init__(self, inchannels=512, num_anchors=3):
155
+ super(BboxHead, self).__init__()
156
+ self.conv1x1 = nn.Conv2d(inchannels, num_anchors * 4, kernel_size=(1, 1), stride=1, padding=0)
157
+
158
+ def forward(self, x):
159
+ out = self.conv1x1(x)
160
+ out = out.permute(0, 2, 3, 1).contiguous()
161
+
162
+ return out.view(out.shape[0], -1, 4)
163
+
164
+
165
+ class LandmarkHead(nn.Module):
166
+
167
+ def __init__(self, inchannels=512, num_anchors=3):
168
+ super(LandmarkHead, self).__init__()
169
+ self.conv1x1 = nn.Conv2d(inchannels, num_anchors * 10, kernel_size=(1, 1), stride=1, padding=0)
170
+
171
+ def forward(self, x):
172
+ out = self.conv1x1(x)
173
+ out = out.permute(0, 2, 3, 1).contiguous()
174
+
175
+ return out.view(out.shape[0], -1, 10)
176
+
177
+
178
+ def make_class_head(fpn_num=3, inchannels=64, anchor_num=2):
179
+ classhead = nn.ModuleList()
180
+ for i in range(fpn_num):
181
+ classhead.append(ClassHead(inchannels, anchor_num))
182
+ return classhead
183
+
184
+
185
+ def make_bbox_head(fpn_num=3, inchannels=64, anchor_num=2):
186
+ bboxhead = nn.ModuleList()
187
+ for i in range(fpn_num):
188
+ bboxhead.append(BboxHead(inchannels, anchor_num))
189
+ return bboxhead
190
+
191
+
192
+ def make_landmark_head(fpn_num=3, inchannels=64, anchor_num=2):
193
+ landmarkhead = nn.ModuleList()
194
+ for i in range(fpn_num):
195
+ landmarkhead.append(LandmarkHead(inchannels, anchor_num))
196
+ return landmarkhead
CodeFormer/facelib/detection/retinaface/retinaface_utils.py ADDED
@@ -0,0 +1,421 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import numpy as np
2
+ import torch
3
+ import torchvision
4
+ from itertools import product as product
5
+ from math import ceil
6
+
7
+
8
+ class PriorBox(object):
9
+
10
+ def __init__(self, cfg, image_size=None, phase='train'):
11
+ super(PriorBox, self).__init__()
12
+ self.min_sizes = cfg['min_sizes']
13
+ self.steps = cfg['steps']
14
+ self.clip = cfg['clip']
15
+ self.image_size = image_size
16
+ self.feature_maps = [[ceil(self.image_size[0] / step), ceil(self.image_size[1] / step)] for step in self.steps]
17
+ self.name = 's'
18
+
19
+ def forward(self):
20
+ anchors = []
21
+ for k, f in enumerate(self.feature_maps):
22
+ min_sizes = self.min_sizes[k]
23
+ for i, j in product(range(f[0]), range(f[1])):
24
+ for min_size in min_sizes:
25
+ s_kx = min_size / self.image_size[1]
26
+ s_ky = min_size / self.image_size[0]
27
+ dense_cx = [x * self.steps[k] / self.image_size[1] for x in [j + 0.5]]
28
+ dense_cy = [y * self.steps[k] / self.image_size[0] for y in [i + 0.5]]
29
+ for cy, cx in product(dense_cy, dense_cx):
30
+ anchors += [cx, cy, s_kx, s_ky]
31
+
32
+ # back to torch land
33
+ output = torch.Tensor(anchors).view(-1, 4)
34
+ if self.clip:
35
+ output.clamp_(max=1, min=0)
36
+ return output
37
+
38
+
39
+ def py_cpu_nms(dets, thresh):
40
+ """Pure Python NMS baseline."""
41
+ keep = torchvision.ops.nms(
42
+ boxes=torch.Tensor(dets[:, :4]),
43
+ scores=torch.Tensor(dets[:, 4]),
44
+ iou_threshold=thresh,
45
+ )
46
+
47
+ return list(keep)
48
+
49
+
50
+ def point_form(boxes):
51
+ """ Convert prior_boxes to (xmin, ymin, xmax, ymax)
52
+ representation for comparison to point form ground truth data.
53
+ Args:
54
+ boxes: (tensor) center-size default boxes from priorbox layers.
55
+ Return:
56
+ boxes: (tensor) Converted xmin, ymin, xmax, ymax form of boxes.
57
+ """
58
+ return torch.cat(
59
+ (
60
+ boxes[:, :2] - boxes[:, 2:] / 2, # xmin, ymin
61
+ boxes[:, :2] + boxes[:, 2:] / 2),
62
+ 1) # xmax, ymax
63
+
64
+
65
+ def center_size(boxes):
66
+ """ Convert prior_boxes to (cx, cy, w, h)
67
+ representation for comparison to center-size form ground truth data.
68
+ Args:
69
+ boxes: (tensor) point_form boxes
70
+ Return:
71
+ boxes: (tensor) Converted xmin, ymin, xmax, ymax form of boxes.
72
+ """
73
+ return torch.cat(
74
+ (boxes[:, 2:] + boxes[:, :2]) / 2, # cx, cy
75
+ boxes[:, 2:] - boxes[:, :2],
76
+ 1) # w, h
77
+
78
+
79
+ def intersect(box_a, box_b):
80
+ """ We resize both tensors to [A,B,2] without new malloc:
81
+ [A,2] -> [A,1,2] -> [A,B,2]
82
+ [B,2] -> [1,B,2] -> [A,B,2]
83
+ Then we compute the area of intersect between box_a and box_b.
84
+ Args:
85
+ box_a: (tensor) bounding boxes, Shape: [A,4].
86
+ box_b: (tensor) bounding boxes, Shape: [B,4].
87
+ Return:
88
+ (tensor) intersection area, Shape: [A,B].
89
+ """
90
+ A = box_a.size(0)
91
+ B = box_b.size(0)
92
+ max_xy = torch.min(box_a[:, 2:].unsqueeze(1).expand(A, B, 2), box_b[:, 2:].unsqueeze(0).expand(A, B, 2))
93
+ min_xy = torch.max(box_a[:, :2].unsqueeze(1).expand(A, B, 2), box_b[:, :2].unsqueeze(0).expand(A, B, 2))
94
+ inter = torch.clamp((max_xy - min_xy), min=0)
95
+ return inter[:, :, 0] * inter[:, :, 1]
96
+
97
+
98
+ def jaccard(box_a, box_b):
99
+ """Compute the jaccard overlap of two sets of boxes. The jaccard overlap
100
+ is simply the intersection over union of two boxes. Here we operate on
101
+ ground truth boxes and default boxes.
102
+ E.g.:
103
+ A ∩ B / A ∪ B = A ∩ B / (area(A) + area(B) - A ∩ B)
104
+ Args:
105
+ box_a: (tensor) Ground truth bounding boxes, Shape: [num_objects,4]
106
+ box_b: (tensor) Prior boxes from priorbox layers, Shape: [num_priors,4]
107
+ Return:
108
+ jaccard overlap: (tensor) Shape: [box_a.size(0), box_b.size(0)]
109
+ """
110
+ inter = intersect(box_a, box_b)
111
+ area_a = ((box_a[:, 2] - box_a[:, 0]) * (box_a[:, 3] - box_a[:, 1])).unsqueeze(1).expand_as(inter) # [A,B]
112
+ area_b = ((box_b[:, 2] - box_b[:, 0]) * (box_b[:, 3] - box_b[:, 1])).unsqueeze(0).expand_as(inter) # [A,B]
113
+ union = area_a + area_b - inter
114
+ return inter / union # [A,B]
115
+
116
+
117
+ def matrix_iou(a, b):
118
+ """
119
+ return iou of a and b, numpy version for data augenmentation
120
+ """
121
+ lt = np.maximum(a[:, np.newaxis, :2], b[:, :2])
122
+ rb = np.minimum(a[:, np.newaxis, 2:], b[:, 2:])
123
+
124
+ area_i = np.prod(rb - lt, axis=2) * (lt < rb).all(axis=2)
125
+ area_a = np.prod(a[:, 2:] - a[:, :2], axis=1)
126
+ area_b = np.prod(b[:, 2:] - b[:, :2], axis=1)
127
+ return area_i / (area_a[:, np.newaxis] + area_b - area_i)
128
+
129
+
130
+ def matrix_iof(a, b):
131
+ """
132
+ return iof of a and b, numpy version for data augenmentation
133
+ """
134
+ lt = np.maximum(a[:, np.newaxis, :2], b[:, :2])
135
+ rb = np.minimum(a[:, np.newaxis, 2:], b[:, 2:])
136
+
137
+ area_i = np.prod(rb - lt, axis=2) * (lt < rb).all(axis=2)
138
+ area_a = np.prod(a[:, 2:] - a[:, :2], axis=1)
139
+ return area_i / np.maximum(area_a[:, np.newaxis], 1)
140
+
141
+
142
+ def match(threshold, truths, priors, variances, labels, landms, loc_t, conf_t, landm_t, idx):
143
+ """Match each prior box with the ground truth box of the highest jaccard
144
+ overlap, encode the bounding boxes, then return the matched indices
145
+ corresponding to both confidence and location preds.
146
+ Args:
147
+ threshold: (float) The overlap threshold used when matching boxes.
148
+ truths: (tensor) Ground truth boxes, Shape: [num_obj, 4].
149
+ priors: (tensor) Prior boxes from priorbox layers, Shape: [n_priors,4].
150
+ variances: (tensor) Variances corresponding to each prior coord,
151
+ Shape: [num_priors, 4].
152
+ labels: (tensor) All the class labels for the image, Shape: [num_obj].
153
+ landms: (tensor) Ground truth landms, Shape [num_obj, 10].
154
+ loc_t: (tensor) Tensor to be filled w/ encoded location targets.
155
+ conf_t: (tensor) Tensor to be filled w/ matched indices for conf preds.
156
+ landm_t: (tensor) Tensor to be filled w/ encoded landm targets.
157
+ idx: (int) current batch index
158
+ Return:
159
+ The matched indices corresponding to 1)location 2)confidence
160
+ 3)landm preds.
161
+ """
162
+ # jaccard index
163
+ overlaps = jaccard(truths, point_form(priors))
164
+ # (Bipartite Matching)
165
+ # [1,num_objects] best prior for each ground truth
166
+ best_prior_overlap, best_prior_idx = overlaps.max(1, keepdim=True)
167
+
168
+ # ignore hard gt
169
+ valid_gt_idx = best_prior_overlap[:, 0] >= 0.2
170
+ best_prior_idx_filter = best_prior_idx[valid_gt_idx, :]
171
+ if best_prior_idx_filter.shape[0] <= 0:
172
+ loc_t[idx] = 0
173
+ conf_t[idx] = 0
174
+ return
175
+
176
+ # [1,num_priors] best ground truth for each prior
177
+ best_truth_overlap, best_truth_idx = overlaps.max(0, keepdim=True)
178
+ best_truth_idx.squeeze_(0)
179
+ best_truth_overlap.squeeze_(0)
180
+ best_prior_idx.squeeze_(1)
181
+ best_prior_idx_filter.squeeze_(1)
182
+ best_prior_overlap.squeeze_(1)
183
+ best_truth_overlap.index_fill_(0, best_prior_idx_filter, 2) # ensure best prior
184
+ # TODO refactor: index best_prior_idx with long tensor
185
+ # ensure every gt matches with its prior of max overlap
186
+ for j in range(best_prior_idx.size(0)): # 判别此anchor是预测哪一个boxes
187
+ best_truth_idx[best_prior_idx[j]] = j
188
+ matches = truths[best_truth_idx] # Shape: [num_priors,4] 此处为每一个anchor对应的bbox取出来
189
+ conf = labels[best_truth_idx] # Shape: [num_priors] 此处为每一个anchor对应的label取出来
190
+ conf[best_truth_overlap < threshold] = 0 # label as background overlap<0.35的全部作为负样本
191
+ loc = encode(matches, priors, variances)
192
+
193
+ matches_landm = landms[best_truth_idx]
194
+ landm = encode_landm(matches_landm, priors, variances)
195
+ loc_t[idx] = loc # [num_priors,4] encoded offsets to learn
196
+ conf_t[idx] = conf # [num_priors] top class label for each prior
197
+ landm_t[idx] = landm
198
+
199
+
200
+ def encode(matched, priors, variances):
201
+ """Encode the variances from the priorbox layers into the ground truth boxes
202
+ we have matched (based on jaccard overlap) with the prior boxes.
203
+ Args:
204
+ matched: (tensor) Coords of ground truth for each prior in point-form
205
+ Shape: [num_priors, 4].
206
+ priors: (tensor) Prior boxes in center-offset form
207
+ Shape: [num_priors,4].
208
+ variances: (list[float]) Variances of priorboxes
209
+ Return:
210
+ encoded boxes (tensor), Shape: [num_priors, 4]
211
+ """
212
+
213
+ # dist b/t match center and prior's center
214
+ g_cxcy = (matched[:, :2] + matched[:, 2:]) / 2 - priors[:, :2]
215
+ # encode variance
216
+ g_cxcy /= (variances[0] * priors[:, 2:])
217
+ # match wh / prior wh
218
+ g_wh = (matched[:, 2:] - matched[:, :2]) / priors[:, 2:]
219
+ g_wh = torch.log(g_wh) / variances[1]
220
+ # return target for smooth_l1_loss
221
+ return torch.cat([g_cxcy, g_wh], 1) # [num_priors,4]
222
+
223
+
224
+ def encode_landm(matched, priors, variances):
225
+ """Encode the variances from the priorbox layers into the ground truth boxes
226
+ we have matched (based on jaccard overlap) with the prior boxes.
227
+ Args:
228
+ matched: (tensor) Coords of ground truth for each prior in point-form
229
+ Shape: [num_priors, 10].
230
+ priors: (tensor) Prior boxes in center-offset form
231
+ Shape: [num_priors,4].
232
+ variances: (list[float]) Variances of priorboxes
233
+ Return:
234
+ encoded landm (tensor), Shape: [num_priors, 10]
235
+ """
236
+
237
+ # dist b/t match center and prior's center
238
+ matched = torch.reshape(matched, (matched.size(0), 5, 2))
239
+ priors_cx = priors[:, 0].unsqueeze(1).expand(matched.size(0), 5).unsqueeze(2)
240
+ priors_cy = priors[:, 1].unsqueeze(1).expand(matched.size(0), 5).unsqueeze(2)
241
+ priors_w = priors[:, 2].unsqueeze(1).expand(matched.size(0), 5).unsqueeze(2)
242
+ priors_h = priors[:, 3].unsqueeze(1).expand(matched.size(0), 5).unsqueeze(2)
243
+ priors = torch.cat([priors_cx, priors_cy, priors_w, priors_h], dim=2)
244
+ g_cxcy = matched[:, :, :2] - priors[:, :, :2]
245
+ # encode variance
246
+ g_cxcy /= (variances[0] * priors[:, :, 2:])
247
+ # g_cxcy /= priors[:, :, 2:]
248
+ g_cxcy = g_cxcy.reshape(g_cxcy.size(0), -1)
249
+ # return target for smooth_l1_loss
250
+ return g_cxcy
251
+
252
+
253
+ # Adapted from https://github.com/Hakuyume/chainer-ssd
254
+ def decode(loc, priors, variances):
255
+ """Decode locations from predictions using priors to undo
256
+ the encoding we did for offset regression at train time.
257
+ Args:
258
+ loc (tensor): location predictions for loc layers,
259
+ Shape: [num_priors,4]
260
+ priors (tensor): Prior boxes in center-offset form.
261
+ Shape: [num_priors,4].
262
+ variances: (list[float]) Variances of priorboxes
263
+ Return:
264
+ decoded bounding box predictions
265
+ """
266
+
267
+ boxes = torch.cat((priors[:, :2] + loc[:, :2] * variances[0] * priors[:, 2:],
268
+ priors[:, 2:] * torch.exp(loc[:, 2:] * variances[1])), 1)
269
+ boxes[:, :2] -= boxes[:, 2:] / 2
270
+ boxes[:, 2:] += boxes[:, :2]
271
+ return boxes
272
+
273
+
274
+ def decode_landm(pre, priors, variances):
275
+ """Decode landm from predictions using priors to undo
276
+ the encoding we did for offset regression at train time.
277
+ Args:
278
+ pre (tensor): landm predictions for loc layers,
279
+ Shape: [num_priors,10]
280
+ priors (tensor): Prior boxes in center-offset form.
281
+ Shape: [num_priors,4].
282
+ variances: (list[float]) Variances of priorboxes
283
+ Return:
284
+ decoded landm predictions
285
+ """
286
+ tmp = (
287
+ priors[:, :2] + pre[:, :2] * variances[0] * priors[:, 2:],
288
+ priors[:, :2] + pre[:, 2:4] * variances[0] * priors[:, 2:],
289
+ priors[:, :2] + pre[:, 4:6] * variances[0] * priors[:, 2:],
290
+ priors[:, :2] + pre[:, 6:8] * variances[0] * priors[:, 2:],
291
+ priors[:, :2] + pre[:, 8:10] * variances[0] * priors[:, 2:],
292
+ )
293
+ landms = torch.cat(tmp, dim=1)
294
+ return landms
295
+
296
+
297
+ def batched_decode(b_loc, priors, variances):
298
+ """Decode locations from predictions using priors to undo
299
+ the encoding we did for offset regression at train time.
300
+ Args:
301
+ b_loc (tensor): location predictions for loc layers,
302
+ Shape: [num_batches,num_priors,4]
303
+ priors (tensor): Prior boxes in center-offset form.
304
+ Shape: [1,num_priors,4].
305
+ variances: (list[float]) Variances of priorboxes
306
+ Return:
307
+ decoded bounding box predictions
308
+ """
309
+ boxes = (
310
+ priors[:, :, :2] + b_loc[:, :, :2] * variances[0] * priors[:, :, 2:],
311
+ priors[:, :, 2:] * torch.exp(b_loc[:, :, 2:] * variances[1]),
312
+ )
313
+ boxes = torch.cat(boxes, dim=2)
314
+
315
+ boxes[:, :, :2] -= boxes[:, :, 2:] / 2
316
+ boxes[:, :, 2:] += boxes[:, :, :2]
317
+ return boxes
318
+
319
+
320
+ def batched_decode_landm(pre, priors, variances):
321
+ """Decode landm from predictions using priors to undo
322
+ the encoding we did for offset regression at train time.
323
+ Args:
324
+ pre (tensor): landm predictions for loc layers,
325
+ Shape: [num_batches,num_priors,10]
326
+ priors (tensor): Prior boxes in center-offset form.
327
+ Shape: [1,num_priors,4].
328
+ variances: (list[float]) Variances of priorboxes
329
+ Return:
330
+ decoded landm predictions
331
+ """
332
+ landms = (
333
+ priors[:, :, :2] + pre[:, :, :2] * variances[0] * priors[:, :, 2:],
334
+ priors[:, :, :2] + pre[:, :, 2:4] * variances[0] * priors[:, :, 2:],
335
+ priors[:, :, :2] + pre[:, :, 4:6] * variances[0] * priors[:, :, 2:],
336
+ priors[:, :, :2] + pre[:, :, 6:8] * variances[0] * priors[:, :, 2:],
337
+ priors[:, :, :2] + pre[:, :, 8:10] * variances[0] * priors[:, :, 2:],
338
+ )
339
+ landms = torch.cat(landms, dim=2)
340
+ return landms
341
+
342
+
343
+ def log_sum_exp(x):
344
+ """Utility function for computing log_sum_exp while determining
345
+ This will be used to determine unaveraged confidence loss across
346
+ all examples in a batch.
347
+ Args:
348
+ x (Variable(tensor)): conf_preds from conf layers
349
+ """
350
+ x_max = x.data.max()
351
+ return torch.log(torch.sum(torch.exp(x - x_max), 1, keepdim=True)) + x_max
352
+
353
+
354
+ # Original author: Francisco Massa:
355
+ # https://github.com/fmassa/object-detection.torch
356
+ # Ported to PyTorch by Max deGroot (02/01/2017)
357
+ def nms(boxes, scores, overlap=0.5, top_k=200):
358
+ """Apply non-maximum suppression at test time to avoid detecting too many
359
+ overlapping bounding boxes for a given object.
360
+ Args:
361
+ boxes: (tensor) The location preds for the img, Shape: [num_priors,4].
362
+ scores: (tensor) The class predscores for the img, Shape:[num_priors].
363
+ overlap: (float) The overlap thresh for suppressing unnecessary boxes.
364
+ top_k: (int) The Maximum number of box preds to consider.
365
+ Return:
366
+ The indices of the kept boxes with respect to num_priors.
367
+ """
368
+
369
+ keep = torch.Tensor(scores.size(0)).fill_(0).long()
370
+ if boxes.numel() == 0:
371
+ return keep
372
+ x1 = boxes[:, 0]
373
+ y1 = boxes[:, 1]
374
+ x2 = boxes[:, 2]
375
+ y2 = boxes[:, 3]
376
+ area = torch.mul(x2 - x1, y2 - y1)
377
+ v, idx = scores.sort(0) # sort in ascending order
378
+ # I = I[v >= 0.01]
379
+ idx = idx[-top_k:] # indices of the top-k largest vals
380
+ xx1 = boxes.new()
381
+ yy1 = boxes.new()
382
+ xx2 = boxes.new()
383
+ yy2 = boxes.new()
384
+ w = boxes.new()
385
+ h = boxes.new()
386
+
387
+ # keep = torch.Tensor()
388
+ count = 0
389
+ while idx.numel() > 0:
390
+ i = idx[-1] # index of current largest val
391
+ # keep.append(i)
392
+ keep[count] = i
393
+ count += 1
394
+ if idx.size(0) == 1:
395
+ break
396
+ idx = idx[:-1] # remove kept element from view
397
+ # load bboxes of next highest vals
398
+ torch.index_select(x1, 0, idx, out=xx1)
399
+ torch.index_select(y1, 0, idx, out=yy1)
400
+ torch.index_select(x2, 0, idx, out=xx2)
401
+ torch.index_select(y2, 0, idx, out=yy2)
402
+ # store element-wise max with next highest score
403
+ xx1 = torch.clamp(xx1, min=x1[i])
404
+ yy1 = torch.clamp(yy1, min=y1[i])
405
+ xx2 = torch.clamp(xx2, max=x2[i])
406
+ yy2 = torch.clamp(yy2, max=y2[i])
407
+ w.resize_as_(xx2)
408
+ h.resize_as_(yy2)
409
+ w = xx2 - xx1
410
+ h = yy2 - yy1
411
+ # check sizes of xx1 and xx2.. after each iteration
412
+ w = torch.clamp(w, min=0.0)
413
+ h = torch.clamp(h, min=0.0)
414
+ inter = w * h
415
+ # IoU = i / (area(a) + area(b) - i)
416
+ rem_areas = torch.index_select(area, 0, idx) # load remaining areas)
417
+ union = (rem_areas - inter) + area[i]
418
+ IoU = inter / union # store result in iou
419
+ # keep only elements with an IoU <= overlap
420
+ idx = idx[IoU.le(overlap)]
421
+ return keep, count
CodeFormer/facelib/detection/yolov5face/__init__.py ADDED
File without changes
CodeFormer/facelib/detection/yolov5face/face_detector.py ADDED
@@ -0,0 +1,141 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import cv2
2
+ import copy
3
+ import re
4
+ import torch
5
+ import numpy as np
6
+
7
+ from pathlib import Path
8
+ from facelib.detection.yolov5face.models.yolo import Model
9
+ from facelib.detection.yolov5face.utils.datasets import letterbox
10
+ from facelib.detection.yolov5face.utils.general import (
11
+ check_img_size,
12
+ non_max_suppression_face,
13
+ scale_coords,
14
+ scale_coords_landmarks,
15
+ )
16
+
17
+ # IS_HIGH_VERSION = tuple(map(int, torch.__version__.split('+')[0].split('.')[:2])) >= (1, 9)
18
+ IS_HIGH_VERSION = [int(m) for m in list(re.findall(r"^([0-9]+)\.([0-9]+)\.([0-9]+)([^0-9][a-zA-Z0-9]*)?(\+git.*)?$",\
19
+ torch.__version__)[0][:3])] >= [1, 9, 0]
20
+
21
+
22
+ def isListempty(inList):
23
+ if isinstance(inList, list): # Is a list
24
+ return all(map(isListempty, inList))
25
+ return False # Not a list
26
+
27
+ class YoloDetector:
28
+ def __init__(
29
+ self,
30
+ config_name,
31
+ min_face=10,
32
+ target_size=None,
33
+ device='cuda',
34
+ ):
35
+ """
36
+ config_name: name of .yaml config with network configuration from models/ folder.
37
+ min_face : minimal face size in pixels.
38
+ target_size : target size of smaller image axis (choose lower for faster work). e.g. 480, 720, 1080.
39
+ None for original resolution.
40
+ """
41
+ self._class_path = Path(__file__).parent.absolute()
42
+ self.target_size = target_size
43
+ self.min_face = min_face
44
+ self.detector = Model(cfg=config_name)
45
+ self.device = device
46
+
47
+
48
+ def _preprocess(self, imgs):
49
+ """
50
+ Preprocessing image before passing through the network. Resize and conversion to torch tensor.
51
+ """
52
+ pp_imgs = []
53
+ for img in imgs:
54
+ h0, w0 = img.shape[:2] # orig hw
55
+ if self.target_size:
56
+ r = self.target_size / min(h0, w0) # resize image to img_size
57
+ if r < 1:
58
+ img = cv2.resize(img, (int(w0 * r), int(h0 * r)), interpolation=cv2.INTER_LINEAR)
59
+
60
+ imgsz = check_img_size(max(img.shape[:2]), s=self.detector.stride.max()) # check img_size
61
+ img = letterbox(img, new_shape=imgsz)[0]
62
+ pp_imgs.append(img)
63
+ pp_imgs = np.array(pp_imgs)
64
+ pp_imgs = pp_imgs.transpose(0, 3, 1, 2)
65
+ pp_imgs = torch.from_numpy(pp_imgs).to(self.device)
66
+ pp_imgs = pp_imgs.float() # uint8 to fp16/32
67
+ return pp_imgs / 255.0 # 0 - 255 to 0.0 - 1.0
68
+
69
+ def _postprocess(self, imgs, origimgs, pred, conf_thres, iou_thres):
70
+ """
71
+ Postprocessing of raw pytorch model output.
72
+ Returns:
73
+ bboxes: list of arrays with 4 coordinates of bounding boxes with format x1,y1,x2,y2.
74
+ points: list of arrays with coordinates of 5 facial keypoints (eyes, nose, lips corners).
75
+ """
76
+ bboxes = [[] for _ in range(len(origimgs))]
77
+ landmarks = [[] for _ in range(len(origimgs))]
78
+
79
+ pred = non_max_suppression_face(pred, conf_thres, iou_thres)
80
+
81
+ for image_id, origimg in enumerate(origimgs):
82
+ img_shape = origimg.shape
83
+ image_height, image_width = img_shape[:2]
84
+ gn = torch.tensor(img_shape)[[1, 0, 1, 0]] # normalization gain whwh
85
+ gn_lks = torch.tensor(img_shape)[[1, 0, 1, 0, 1, 0, 1, 0, 1, 0]] # normalization gain landmarks
86
+ det = pred[image_id].cpu()
87
+ scale_coords(imgs[image_id].shape[1:], det[:, :4], img_shape).round()
88
+ scale_coords_landmarks(imgs[image_id].shape[1:], det[:, 5:15], img_shape).round()
89
+
90
+ for j in range(det.size()[0]):
91
+ box = (det[j, :4].view(1, 4) / gn).view(-1).tolist()
92
+ box = list(
93
+ map(int, [box[0] * image_width, box[1] * image_height, box[2] * image_width, box[3] * image_height])
94
+ )
95
+ if box[3] - box[1] < self.min_face:
96
+ continue
97
+ lm = (det[j, 5:15].view(1, 10) / gn_lks).view(-1).tolist()
98
+ lm = list(map(int, [i * image_width if j % 2 == 0 else i * image_height for j, i in enumerate(lm)]))
99
+ lm = [lm[i : i + 2] for i in range(0, len(lm), 2)]
100
+ bboxes[image_id].append(box)
101
+ landmarks[image_id].append(lm)
102
+ return bboxes, landmarks
103
+
104
+ def detect_faces(self, imgs, conf_thres=0.7, iou_thres=0.5):
105
+ """
106
+ Get bbox coordinates and keypoints of faces on original image.
107
+ Params:
108
+ imgs: image or list of images to detect faces on with BGR order (convert to RGB order for inference)
109
+ conf_thres: confidence threshold for each prediction
110
+ iou_thres: threshold for NMS (filter of intersecting bboxes)
111
+ Returns:
112
+ bboxes: list of arrays with 4 coordinates of bounding boxes with format x1,y1,x2,y2.
113
+ points: list of arrays with coordinates of 5 facial keypoints (eyes, nose, lips corners).
114
+ """
115
+ # Pass input images through face detector
116
+ images = imgs if isinstance(imgs, list) else [imgs]
117
+ images = [cv2.cvtColor(img, cv2.COLOR_BGR2RGB) for img in images]
118
+ origimgs = copy.deepcopy(images)
119
+
120
+ images = self._preprocess(images)
121
+
122
+ if IS_HIGH_VERSION:
123
+ with torch.inference_mode(): # for pytorch>=1.9
124
+ pred = self.detector(images)[0]
125
+ else:
126
+ with torch.no_grad(): # for pytorch<1.9
127
+ pred = self.detector(images)[0]
128
+
129
+ bboxes, points = self._postprocess(images, origimgs, pred, conf_thres, iou_thres)
130
+
131
+ # return bboxes, points
132
+ if not isListempty(points):
133
+ bboxes = np.array(bboxes).reshape(-1,4)
134
+ points = np.array(points).reshape(-1,10)
135
+ padding = bboxes[:,0].reshape(-1,1)
136
+ return np.concatenate((bboxes, padding, points), axis=1)
137
+ else:
138
+ return None
139
+
140
+ def __call__(self, *args):
141
+ return self.predict(*args)
CodeFormer/facelib/detection/yolov5face/models/__init__.py ADDED
File without changes
CodeFormer/facelib/detection/yolov5face/models/common.py ADDED
@@ -0,0 +1,299 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # This file contains modules common to various models
2
+
3
+ import math
4
+
5
+ import numpy as np
6
+ import torch
7
+ from torch import nn
8
+
9
+ from facelib.detection.yolov5face.utils.datasets import letterbox
10
+ from facelib.detection.yolov5face.utils.general import (
11
+ make_divisible,
12
+ non_max_suppression,
13
+ scale_coords,
14
+ xyxy2xywh,
15
+ )
16
+
17
+
18
+ def autopad(k, p=None): # kernel, padding
19
+ # Pad to 'same'
20
+ if p is None:
21
+ p = k // 2 if isinstance(k, int) else [x // 2 for x in k] # auto-pad
22
+ return p
23
+
24
+
25
+ def channel_shuffle(x, groups):
26
+ batchsize, num_channels, height, width = x.data.size()
27
+ channels_per_group = torch.div(num_channels, groups, rounding_mode="trunc")
28
+
29
+ # reshape
30
+ x = x.view(batchsize, groups, channels_per_group, height, width)
31
+ x = torch.transpose(x, 1, 2).contiguous()
32
+
33
+ # flatten
34
+ return x.view(batchsize, -1, height, width)
35
+
36
+
37
+ def DWConv(c1, c2, k=1, s=1, act=True):
38
+ # Depthwise convolution
39
+ return Conv(c1, c2, k, s, g=math.gcd(c1, c2), act=act)
40
+
41
+
42
+ class Conv(nn.Module):
43
+ # Standard convolution
44
+ def __init__(self, c1, c2, k=1, s=1, p=None, g=1, act=True): # ch_in, ch_out, kernel, stride, padding, groups
45
+ super().__init__()
46
+ self.conv = nn.Conv2d(c1, c2, k, s, autopad(k, p), groups=g, bias=False)
47
+ self.bn = nn.BatchNorm2d(c2)
48
+ self.act = nn.SiLU() if act is True else (act if isinstance(act, nn.Module) else nn.Identity())
49
+
50
+ def forward(self, x):
51
+ return self.act(self.bn(self.conv(x)))
52
+
53
+ def fuseforward(self, x):
54
+ return self.act(self.conv(x))
55
+
56
+
57
+ class StemBlock(nn.Module):
58
+ def __init__(self, c1, c2, k=3, s=2, p=None, g=1, act=True):
59
+ super().__init__()
60
+ self.stem_1 = Conv(c1, c2, k, s, p, g, act)
61
+ self.stem_2a = Conv(c2, c2 // 2, 1, 1, 0)
62
+ self.stem_2b = Conv(c2 // 2, c2, 3, 2, 1)
63
+ self.stem_2p = nn.MaxPool2d(kernel_size=2, stride=2, ceil_mode=True)
64
+ self.stem_3 = Conv(c2 * 2, c2, 1, 1, 0)
65
+
66
+ def forward(self, x):
67
+ stem_1_out = self.stem_1(x)
68
+ stem_2a_out = self.stem_2a(stem_1_out)
69
+ stem_2b_out = self.stem_2b(stem_2a_out)
70
+ stem_2p_out = self.stem_2p(stem_1_out)
71
+ return self.stem_3(torch.cat((stem_2b_out, stem_2p_out), 1))
72
+
73
+
74
+ class Bottleneck(nn.Module):
75
+ # Standard bottleneck
76
+ def __init__(self, c1, c2, shortcut=True, g=1, e=0.5): # ch_in, ch_out, shortcut, groups, expansion
77
+ super().__init__()
78
+ c_ = int(c2 * e) # hidden channels
79
+ self.cv1 = Conv(c1, c_, 1, 1)
80
+ self.cv2 = Conv(c_, c2, 3, 1, g=g)
81
+ self.add = shortcut and c1 == c2
82
+
83
+ def forward(self, x):
84
+ return x + self.cv2(self.cv1(x)) if self.add else self.cv2(self.cv1(x))
85
+
86
+
87
+ class BottleneckCSP(nn.Module):
88
+ # CSP Bottleneck https://github.com/WongKinYiu/CrossStagePartialNetworks
89
+ def __init__(self, c1, c2, n=1, shortcut=True, g=1, e=0.5): # ch_in, ch_out, number, shortcut, groups, expansion
90
+ super().__init__()
91
+ c_ = int(c2 * e) # hidden channels
92
+ self.cv1 = Conv(c1, c_, 1, 1)
93
+ self.cv2 = nn.Conv2d(c1, c_, 1, 1, bias=False)
94
+ self.cv3 = nn.Conv2d(c_, c_, 1, 1, bias=False)
95
+ self.cv4 = Conv(2 * c_, c2, 1, 1)
96
+ self.bn = nn.BatchNorm2d(2 * c_) # applied to cat(cv2, cv3)
97
+ self.act = nn.LeakyReLU(0.1, inplace=True)
98
+ self.m = nn.Sequential(*(Bottleneck(c_, c_, shortcut, g, e=1.0) for _ in range(n)))
99
+
100
+ def forward(self, x):
101
+ y1 = self.cv3(self.m(self.cv1(x)))
102
+ y2 = self.cv2(x)
103
+ return self.cv4(self.act(self.bn(torch.cat((y1, y2), dim=1))))
104
+
105
+
106
+ class C3(nn.Module):
107
+ # CSP Bottleneck with 3 convolutions
108
+ def __init__(self, c1, c2, n=1, shortcut=True, g=1, e=0.5): # ch_in, ch_out, number, shortcut, groups, expansion
109
+ super().__init__()
110
+ c_ = int(c2 * e) # hidden channels
111
+ self.cv1 = Conv(c1, c_, 1, 1)
112
+ self.cv2 = Conv(c1, c_, 1, 1)
113
+ self.cv3 = Conv(2 * c_, c2, 1) # act=FReLU(c2)
114
+ self.m = nn.Sequential(*(Bottleneck(c_, c_, shortcut, g, e=1.0) for _ in range(n)))
115
+
116
+ def forward(self, x):
117
+ return self.cv3(torch.cat((self.m(self.cv1(x)), self.cv2(x)), dim=1))
118
+
119
+
120
+ class ShuffleV2Block(nn.Module):
121
+ def __init__(self, inp, oup, stride):
122
+ super().__init__()
123
+
124
+ if not 1 <= stride <= 3:
125
+ raise ValueError("illegal stride value")
126
+ self.stride = stride
127
+
128
+ branch_features = oup // 2
129
+
130
+ if self.stride > 1:
131
+ self.branch1 = nn.Sequential(
132
+ self.depthwise_conv(inp, inp, kernel_size=3, stride=self.stride, padding=1),
133
+ nn.BatchNorm2d(inp),
134
+ nn.Conv2d(inp, branch_features, kernel_size=1, stride=1, padding=0, bias=False),
135
+ nn.BatchNorm2d(branch_features),
136
+ nn.SiLU(),
137
+ )
138
+ else:
139
+ self.branch1 = nn.Sequential()
140
+
141
+ self.branch2 = nn.Sequential(
142
+ nn.Conv2d(
143
+ inp if (self.stride > 1) else branch_features,
144
+ branch_features,
145
+ kernel_size=1,
146
+ stride=1,
147
+ padding=0,
148
+ bias=False,
149
+ ),
150
+ nn.BatchNorm2d(branch_features),
151
+ nn.SiLU(),
152
+ self.depthwise_conv(branch_features, branch_features, kernel_size=3, stride=self.stride, padding=1),
153
+ nn.BatchNorm2d(branch_features),
154
+ nn.Conv2d(branch_features, branch_features, kernel_size=1, stride=1, padding=0, bias=False),
155
+ nn.BatchNorm2d(branch_features),
156
+ nn.SiLU(),
157
+ )
158
+
159
+ @staticmethod
160
+ def depthwise_conv(i, o, kernel_size, stride=1, padding=0, bias=False):
161
+ return nn.Conv2d(i, o, kernel_size, stride, padding, bias=bias, groups=i)
162
+
163
+ def forward(self, x):
164
+ if self.stride == 1:
165
+ x1, x2 = x.chunk(2, dim=1)
166
+ out = torch.cat((x1, self.branch2(x2)), dim=1)
167
+ else:
168
+ out = torch.cat((self.branch1(x), self.branch2(x)), dim=1)
169
+ out = channel_shuffle(out, 2)
170
+ return out
171
+
172
+
173
+ class SPP(nn.Module):
174
+ # Spatial pyramid pooling layer used in YOLOv3-SPP
175
+ def __init__(self, c1, c2, k=(5, 9, 13)):
176
+ super().__init__()
177
+ c_ = c1 // 2 # hidden channels
178
+ self.cv1 = Conv(c1, c_, 1, 1)
179
+ self.cv2 = Conv(c_ * (len(k) + 1), c2, 1, 1)
180
+ self.m = nn.ModuleList([nn.MaxPool2d(kernel_size=x, stride=1, padding=x // 2) for x in k])
181
+
182
+ def forward(self, x):
183
+ x = self.cv1(x)
184
+ return self.cv2(torch.cat([x] + [m(x) for m in self.m], 1))
185
+
186
+
187
+ class Focus(nn.Module):
188
+ # Focus wh information into c-space
189
+ def __init__(self, c1, c2, k=1, s=1, p=None, g=1, act=True): # ch_in, ch_out, kernel, stride, padding, groups
190
+ super().__init__()
191
+ self.conv = Conv(c1 * 4, c2, k, s, p, g, act)
192
+
193
+ def forward(self, x): # x(b,c,w,h) -> y(b,4c,w/2,h/2)
194
+ return self.conv(torch.cat([x[..., ::2, ::2], x[..., 1::2, ::2], x[..., ::2, 1::2], x[..., 1::2, 1::2]], 1))
195
+
196
+
197
+ class Concat(nn.Module):
198
+ # Concatenate a list of tensors along dimension
199
+ def __init__(self, dimension=1):
200
+ super().__init__()
201
+ self.d = dimension
202
+
203
+ def forward(self, x):
204
+ return torch.cat(x, self.d)
205
+
206
+
207
+ class NMS(nn.Module):
208
+ # Non-Maximum Suppression (NMS) module
209
+ conf = 0.25 # confidence threshold
210
+ iou = 0.45 # IoU threshold
211
+ classes = None # (optional list) filter by class
212
+
213
+ def forward(self, x):
214
+ return non_max_suppression(x[0], conf_thres=self.conf, iou_thres=self.iou, classes=self.classes)
215
+
216
+
217
+ class AutoShape(nn.Module):
218
+ # input-robust model wrapper for passing cv2/np/PIL/torch inputs. Includes preprocessing, inference and NMS
219
+ img_size = 640 # inference size (pixels)
220
+ conf = 0.25 # NMS confidence threshold
221
+ iou = 0.45 # NMS IoU threshold
222
+ classes = None # (optional list) filter by class
223
+
224
+ def __init__(self, model):
225
+ super().__init__()
226
+ self.model = model.eval()
227
+
228
+ def autoshape(self):
229
+ print("autoShape already enabled, skipping... ") # model already converted to model.autoshape()
230
+ return self
231
+
232
+ def forward(self, imgs, size=640, augment=False, profile=False):
233
+ # Inference from various sources. For height=720, width=1280, RGB images example inputs are:
234
+ # OpenCV: = cv2.imread('image.jpg')[:,:,::-1] # HWC BGR to RGB x(720,1280,3)
235
+ # PIL: = Image.open('image.jpg') # HWC x(720,1280,3)
236
+ # numpy: = np.zeros((720,1280,3)) # HWC
237
+ # torch: = torch.zeros(16,3,720,1280) # BCHW
238
+ # multiple: = [Image.open('image1.jpg'), Image.open('image2.jpg'), ...] # list of images
239
+
240
+ p = next(self.model.parameters()) # for device and type
241
+ if isinstance(imgs, torch.Tensor): # torch
242
+ return self.model(imgs.to(p.device).type_as(p), augment, profile) # inference
243
+
244
+ # Pre-process
245
+ n, imgs = (len(imgs), imgs) if isinstance(imgs, list) else (1, [imgs]) # number of images, list of images
246
+ shape0, shape1 = [], [] # image and inference shapes
247
+ for i, im in enumerate(imgs):
248
+ im = np.array(im) # to numpy
249
+ if im.shape[0] < 5: # image in CHW
250
+ im = im.transpose((1, 2, 0)) # reverse dataloader .transpose(2, 0, 1)
251
+ im = im[:, :, :3] if im.ndim == 3 else np.tile(im[:, :, None], 3) # enforce 3ch input
252
+ s = im.shape[:2] # HWC
253
+ shape0.append(s) # image shape
254
+ g = size / max(s) # gain
255
+ shape1.append([y * g for y in s])
256
+ imgs[i] = im # update
257
+ shape1 = [make_divisible(x, int(self.stride.max())) for x in np.stack(shape1, 0).max(0)] # inference shape
258
+ x = [letterbox(im, new_shape=shape1, auto=False)[0] for im in imgs] # pad
259
+ x = np.stack(x, 0) if n > 1 else x[0][None] # stack
260
+ x = np.ascontiguousarray(x.transpose((0, 3, 1, 2))) # BHWC to BCHW
261
+ x = torch.from_numpy(x).to(p.device).type_as(p) / 255.0 # uint8 to fp16/32
262
+
263
+ # Inference
264
+ with torch.no_grad():
265
+ y = self.model(x, augment, profile)[0] # forward
266
+ y = non_max_suppression(y, conf_thres=self.conf, iou_thres=self.iou, classes=self.classes) # NMS
267
+
268
+ # Post-process
269
+ for i in range(n):
270
+ scale_coords(shape1, y[i][:, :4], shape0[i])
271
+
272
+ return Detections(imgs, y, self.names)
273
+
274
+
275
+ class Detections:
276
+ # detections class for YOLOv5 inference results
277
+ def __init__(self, imgs, pred, names=None):
278
+ super().__init__()
279
+ d = pred[0].device # device
280
+ gn = [torch.tensor([*(im.shape[i] for i in [1, 0, 1, 0]), 1.0, 1.0], device=d) for im in imgs] # normalizations
281
+ self.imgs = imgs # list of images as numpy arrays
282
+ self.pred = pred # list of tensors pred[0] = (xyxy, conf, cls)
283
+ self.names = names # class names
284
+ self.xyxy = pred # xyxy pixels
285
+ self.xywh = [xyxy2xywh(x) for x in pred] # xywh pixels
286
+ self.xyxyn = [x / g for x, g in zip(self.xyxy, gn)] # xyxy normalized
287
+ self.xywhn = [x / g for x, g in zip(self.xywh, gn)] # xywh normalized
288
+ self.n = len(self.pred)
289
+
290
+ def __len__(self):
291
+ return self.n
292
+
293
+ def tolist(self):
294
+ # return a list of Detections objects, i.e. 'for result in results.tolist():'
295
+ x = [Detections([self.imgs[i]], [self.pred[i]], self.names) for i in range(self.n)]
296
+ for d in x:
297
+ for k in ["imgs", "pred", "xyxy", "xyxyn", "xywh", "xywhn"]:
298
+ setattr(d, k, getattr(d, k)[0]) # pop out of list
299
+ return x
CodeFormer/facelib/detection/yolov5face/models/experimental.py ADDED
@@ -0,0 +1,45 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # # This file contains experimental modules
2
+
3
+ import numpy as np
4
+ import torch
5
+ from torch import nn
6
+
7
+ from facelib.detection.yolov5face.models.common import Conv
8
+
9
+
10
+ class CrossConv(nn.Module):
11
+ # Cross Convolution Downsample
12
+ def __init__(self, c1, c2, k=3, s=1, g=1, e=1.0, shortcut=False):
13
+ # ch_in, ch_out, kernel, stride, groups, expansion, shortcut
14
+ super().__init__()
15
+ c_ = int(c2 * e) # hidden channels
16
+ self.cv1 = Conv(c1, c_, (1, k), (1, s))
17
+ self.cv2 = Conv(c_, c2, (k, 1), (s, 1), g=g)
18
+ self.add = shortcut and c1 == c2
19
+
20
+ def forward(self, x):
21
+ return x + self.cv2(self.cv1(x)) if self.add else self.cv2(self.cv1(x))
22
+
23
+
24
+ class MixConv2d(nn.Module):
25
+ # Mixed Depthwise Conv https://arxiv.org/abs/1907.09595
26
+ def __init__(self, c1, c2, k=(1, 3), s=1, equal_ch=True):
27
+ super().__init__()
28
+ groups = len(k)
29
+ if equal_ch: # equal c_ per group
30
+ i = torch.linspace(0, groups - 1e-6, c2).floor() # c2 indices
31
+ c_ = [(i == g).sum() for g in range(groups)] # intermediate channels
32
+ else: # equal weight.numel() per group
33
+ b = [c2] + [0] * groups
34
+ a = np.eye(groups + 1, groups, k=-1)
35
+ a -= np.roll(a, 1, axis=1)
36
+ a *= np.array(k) ** 2
37
+ a[0] = 1
38
+ c_ = np.linalg.lstsq(a, b, rcond=None)[0].round() # solve for equal weight indices, ax = b
39
+
40
+ self.m = nn.ModuleList([nn.Conv2d(c1, int(c_[g]), k[g], s, k[g] // 2, bias=False) for g in range(groups)])
41
+ self.bn = nn.BatchNorm2d(c2)
42
+ self.act = nn.LeakyReLU(0.1, inplace=True)
43
+
44
+ def forward(self, x):
45
+ return x + self.act(self.bn(torch.cat([m(x) for m in self.m], 1)))
CodeFormer/facelib/detection/yolov5face/models/yolo.py ADDED
@@ -0,0 +1,235 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import math
2
+ from copy import deepcopy
3
+ from pathlib import Path
4
+
5
+ import torch
6
+ import yaml # for torch hub
7
+ from torch import nn
8
+
9
+ from facelib.detection.yolov5face.models.common import (
10
+ C3,
11
+ NMS,
12
+ SPP,
13
+ AutoShape,
14
+ Bottleneck,
15
+ BottleneckCSP,
16
+ Concat,
17
+ Conv,
18
+ DWConv,
19
+ Focus,
20
+ ShuffleV2Block,
21
+ StemBlock,
22
+ )
23
+ from facelib.detection.yolov5face.models.experimental import CrossConv, MixConv2d
24
+ from facelib.detection.yolov5face.utils.autoanchor import check_anchor_order
25
+ from facelib.detection.yolov5face.utils.general import make_divisible
26
+ from facelib.detection.yolov5face.utils.torch_utils import copy_attr, fuse_conv_and_bn
27
+
28
+
29
+ class Detect(nn.Module):
30
+ stride = None # strides computed during build
31
+ export = False # onnx export
32
+
33
+ def __init__(self, nc=80, anchors=(), ch=()): # detection layer
34
+ super().__init__()
35
+ self.nc = nc # number of classes
36
+ self.no = nc + 5 + 10 # number of outputs per anchor
37
+
38
+ self.nl = len(anchors) # number of detection layers
39
+ self.na = len(anchors[0]) // 2 # number of anchors
40
+ self.grid = [torch.zeros(1)] * self.nl # init grid
41
+ a = torch.tensor(anchors).float().view(self.nl, -1, 2)
42
+ self.register_buffer("anchors", a) # shape(nl,na,2)
43
+ self.register_buffer("anchor_grid", a.clone().view(self.nl, 1, -1, 1, 1, 2)) # shape(nl,1,na,1,1,2)
44
+ self.m = nn.ModuleList(nn.Conv2d(x, self.no * self.na, 1) for x in ch) # output conv
45
+
46
+ def forward(self, x):
47
+ z = [] # inference output
48
+ if self.export:
49
+ for i in range(self.nl):
50
+ x[i] = self.m[i](x[i])
51
+ return x
52
+ for i in range(self.nl):
53
+ x[i] = self.m[i](x[i]) # conv
54
+ bs, _, ny, nx = x[i].shape # x(bs,255,20,20) to x(bs,3,20,20,85)
55
+ x[i] = x[i].view(bs, self.na, self.no, ny, nx).permute(0, 1, 3, 4, 2).contiguous()
56
+
57
+ if not self.training: # inference
58
+ if self.grid[i].shape[2:4] != x[i].shape[2:4]:
59
+ self.grid[i] = self._make_grid(nx, ny).to(x[i].device)
60
+
61
+ y = torch.full_like(x[i], 0)
62
+ y[..., [0, 1, 2, 3, 4, 15]] = x[i][..., [0, 1, 2, 3, 4, 15]].sigmoid()
63
+ y[..., 5:15] = x[i][..., 5:15]
64
+
65
+ y[..., 0:2] = (y[..., 0:2] * 2.0 - 0.5 + self.grid[i].to(x[i].device)) * self.stride[i] # xy
66
+ y[..., 2:4] = (y[..., 2:4] * 2) ** 2 * self.anchor_grid[i] # wh
67
+
68
+ y[..., 5:7] = (
69
+ y[..., 5:7] * self.anchor_grid[i] + self.grid[i].to(x[i].device) * self.stride[i]
70
+ ) # landmark x1 y1
71
+ y[..., 7:9] = (
72
+ y[..., 7:9] * self.anchor_grid[i] + self.grid[i].to(x[i].device) * self.stride[i]
73
+ ) # landmark x2 y2
74
+ y[..., 9:11] = (
75
+ y[..., 9:11] * self.anchor_grid[i] + self.grid[i].to(x[i].device) * self.stride[i]
76
+ ) # landmark x3 y3
77
+ y[..., 11:13] = (
78
+ y[..., 11:13] * self.anchor_grid[i] + self.grid[i].to(x[i].device) * self.stride[i]
79
+ ) # landmark x4 y4
80
+ y[..., 13:15] = (
81
+ y[..., 13:15] * self.anchor_grid[i] + self.grid[i].to(x[i].device) * self.stride[i]
82
+ ) # landmark x5 y5
83
+
84
+ z.append(y.view(bs, -1, self.no))
85
+
86
+ return x if self.training else (torch.cat(z, 1), x)
87
+
88
+ @staticmethod
89
+ def _make_grid(nx=20, ny=20):
90
+ # yv, xv = torch.meshgrid([torch.arange(ny), torch.arange(nx)], indexing="ij") # for pytorch>=1.10
91
+ yv, xv = torch.meshgrid([torch.arange(ny), torch.arange(nx)])
92
+ return torch.stack((xv, yv), 2).view((1, 1, ny, nx, 2)).float()
93
+
94
+
95
+ class Model(nn.Module):
96
+ def __init__(self, cfg="yolov5s.yaml", ch=3, nc=None): # model, input channels, number of classes
97
+ super().__init__()
98
+ self.yaml_file = Path(cfg).name
99
+ with Path(cfg).open(encoding="utf8") as f:
100
+ self.yaml = yaml.safe_load(f) # model dict
101
+
102
+ # Define model
103
+ ch = self.yaml["ch"] = self.yaml.get("ch", ch) # input channels
104
+ if nc and nc != self.yaml["nc"]:
105
+ self.yaml["nc"] = nc # override yaml value
106
+
107
+ self.model, self.save = parse_model(deepcopy(self.yaml), ch=[ch]) # model, savelist
108
+ self.names = [str(i) for i in range(self.yaml["nc"])] # default names
109
+
110
+ # Build strides, anchors
111
+ m = self.model[-1] # Detect()
112
+ if isinstance(m, Detect):
113
+ s = 128 # 2x min stride
114
+ m.stride = torch.tensor([s / x.shape[-2] for x in self.forward(torch.zeros(1, ch, s, s))]) # forward
115
+ m.anchors /= m.stride.view(-1, 1, 1)
116
+ check_anchor_order(m)
117
+ self.stride = m.stride
118
+ self._initialize_biases() # only run once
119
+
120
+ def forward(self, x):
121
+ return self.forward_once(x) # single-scale inference, train
122
+
123
+ def forward_once(self, x):
124
+ y = [] # outputs
125
+ for m in self.model:
126
+ if m.f != -1: # if not from previous layer
127
+ x = y[m.f] if isinstance(m.f, int) else [x if j == -1 else y[j] for j in m.f] # from earlier layers
128
+
129
+ x = m(x) # run
130
+ y.append(x if m.i in self.save else None) # save output
131
+
132
+ return x
133
+
134
+ def _initialize_biases(self, cf=None): # initialize biases into Detect(), cf is class frequency
135
+ # https://arxiv.org/abs/1708.02002 section 3.3
136
+ m = self.model[-1] # Detect() module
137
+ for mi, s in zip(m.m, m.stride): # from
138
+ b = mi.bias.view(m.na, -1) # conv.bias(255) to (3,85)
139
+ b.data[:, 4] += math.log(8 / (640 / s) ** 2) # obj (8 objects per 640 image)
140
+ b.data[:, 5:] += math.log(0.6 / (m.nc - 0.99)) if cf is None else torch.log(cf / cf.sum()) # cls
141
+ mi.bias = torch.nn.Parameter(b.view(-1), requires_grad=True)
142
+
143
+ def _print_biases(self):
144
+ m = self.model[-1] # Detect() module
145
+ for mi in m.m: # from
146
+ b = mi.bias.detach().view(m.na, -1).T # conv.bias(255) to (3,85)
147
+ print(("%6g Conv2d.bias:" + "%10.3g" * 6) % (mi.weight.shape[1], *b[:5].mean(1).tolist(), b[5:].mean()))
148
+
149
+ def fuse(self): # fuse model Conv2d() + BatchNorm2d() layers
150
+ print("Fusing layers... ")
151
+ for m in self.model.modules():
152
+ if isinstance(m, Conv) and hasattr(m, "bn"):
153
+ m.conv = fuse_conv_and_bn(m.conv, m.bn) # update conv
154
+ delattr(m, "bn") # remove batchnorm
155
+ m.forward = m.fuseforward # update forward
156
+ elif type(m) is nn.Upsample:
157
+ m.recompute_scale_factor = None # torch 1.11.0 compatibility
158
+ return self
159
+
160
+ def nms(self, mode=True): # add or remove NMS module
161
+ present = isinstance(self.model[-1], NMS) # last layer is NMS
162
+ if mode and not present:
163
+ print("Adding NMS... ")
164
+ m = NMS() # module
165
+ m.f = -1 # from
166
+ m.i = self.model[-1].i + 1 # index
167
+ self.model.add_module(name=str(m.i), module=m) # add
168
+ self.eval()
169
+ elif not mode and present:
170
+ print("Removing NMS... ")
171
+ self.model = self.model[:-1] # remove
172
+ return self
173
+
174
+ def autoshape(self): # add autoShape module
175
+ print("Adding autoShape... ")
176
+ m = AutoShape(self) # wrap model
177
+ copy_attr(m, self, include=("yaml", "nc", "hyp", "names", "stride"), exclude=()) # copy attributes
178
+ return m
179
+
180
+
181
+ def parse_model(d, ch): # model_dict, input_channels(3)
182
+ anchors, nc, gd, gw = d["anchors"], d["nc"], d["depth_multiple"], d["width_multiple"]
183
+ na = (len(anchors[0]) // 2) if isinstance(anchors, list) else anchors # number of anchors
184
+ no = na * (nc + 5) # number of outputs = anchors * (classes + 5)
185
+
186
+ layers, save, c2 = [], [], ch[-1] # layers, savelist, ch out
187
+ for i, (f, n, m, args) in enumerate(d["backbone"] + d["head"]): # from, number, module, args
188
+ m = eval(m) if isinstance(m, str) else m # eval strings
189
+ for j, a in enumerate(args):
190
+ try:
191
+ args[j] = eval(a) if isinstance(a, str) else a # eval strings
192
+ except:
193
+ pass
194
+
195
+ n = max(round(n * gd), 1) if n > 1 else n # depth gain
196
+ if m in [
197
+ Conv,
198
+ Bottleneck,
199
+ SPP,
200
+ DWConv,
201
+ MixConv2d,
202
+ Focus,
203
+ CrossConv,
204
+ BottleneckCSP,
205
+ C3,
206
+ ShuffleV2Block,
207
+ StemBlock,
208
+ ]:
209
+ c1, c2 = ch[f], args[0]
210
+
211
+ c2 = make_divisible(c2 * gw, 8) if c2 != no else c2
212
+
213
+ args = [c1, c2, *args[1:]]
214
+ if m in [BottleneckCSP, C3]:
215
+ args.insert(2, n)
216
+ n = 1
217
+ elif m is nn.BatchNorm2d:
218
+ args = [ch[f]]
219
+ elif m is Concat:
220
+ c2 = sum(ch[-1 if x == -1 else x + 1] for x in f)
221
+ elif m is Detect:
222
+ args.append([ch[x + 1] for x in f])
223
+ if isinstance(args[1], int): # number of anchors
224
+ args[1] = [list(range(args[1] * 2))] * len(f)
225
+ else:
226
+ c2 = ch[f]
227
+
228
+ m_ = nn.Sequential(*(m(*args) for _ in range(n))) if n > 1 else m(*args) # module
229
+ t = str(m)[8:-2].replace("__main__.", "") # module type
230
+ np = sum(x.numel() for x in m_.parameters()) # number params
231
+ m_.i, m_.f, m_.type, m_.np = i, f, t, np # attach index, 'from' index, type, number params
232
+ save.extend(x % i for x in ([f] if isinstance(f, int) else f) if x != -1) # append to savelist
233
+ layers.append(m_)
234
+ ch.append(c2)
235
+ return nn.Sequential(*layers), sorted(save)
CodeFormer/facelib/detection/yolov5face/models/yolov5l.yaml ADDED
@@ -0,0 +1,47 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # parameters
2
+ nc: 1 # number of classes
3
+ depth_multiple: 1.0 # model depth multiple
4
+ width_multiple: 1.0 # layer channel multiple
5
+
6
+ # anchors
7
+ anchors:
8
+ - [4,5, 8,10, 13,16] # P3/8
9
+ - [23,29, 43,55, 73,105] # P4/16
10
+ - [146,217, 231,300, 335,433] # P5/32
11
+
12
+ # YOLOv5 backbone
13
+ backbone:
14
+ # [from, number, module, args]
15
+ [[-1, 1, StemBlock, [64, 3, 2]], # 0-P1/2
16
+ [-1, 3, C3, [128]],
17
+ [-1, 1, Conv, [256, 3, 2]], # 2-P3/8
18
+ [-1, 9, C3, [256]],
19
+ [-1, 1, Conv, [512, 3, 2]], # 4-P4/16
20
+ [-1, 9, C3, [512]],
21
+ [-1, 1, Conv, [1024, 3, 2]], # 6-P5/32
22
+ [-1, 1, SPP, [1024, [3,5,7]]],
23
+ [-1, 3, C3, [1024, False]], # 8
24
+ ]
25
+
26
+ # YOLOv5 head
27
+ head:
28
+ [[-1, 1, Conv, [512, 1, 1]],
29
+ [-1, 1, nn.Upsample, [None, 2, 'nearest']],
30
+ [[-1, 5], 1, Concat, [1]], # cat backbone P4
31
+ [-1, 3, C3, [512, False]], # 12
32
+
33
+ [-1, 1, Conv, [256, 1, 1]],
34
+ [-1, 1, nn.Upsample, [None, 2, 'nearest']],
35
+ [[-1, 3], 1, Concat, [1]], # cat backbone P3
36
+ [-1, 3, C3, [256, False]], # 16 (P3/8-small)
37
+
38
+ [-1, 1, Conv, [256, 3, 2]],
39
+ [[-1, 13], 1, Concat, [1]], # cat head P4
40
+ [-1, 3, C3, [512, False]], # 19 (P4/16-medium)
41
+
42
+ [-1, 1, Conv, [512, 3, 2]],
43
+ [[-1, 9], 1, Concat, [1]], # cat head P5
44
+ [-1, 3, C3, [1024, False]], # 22 (P5/32-large)
45
+
46
+ [[16, 19, 22], 1, Detect, [nc, anchors]], # Detect(P3, P4, P5)
47
+ ]
CodeFormer/facelib/detection/yolov5face/models/yolov5n.yaml ADDED
@@ -0,0 +1,45 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # parameters
2
+ nc: 1 # number of classes
3
+ depth_multiple: 1.0 # model depth multiple
4
+ width_multiple: 1.0 # layer channel multiple
5
+
6
+ # anchors
7
+ anchors:
8
+ - [4,5, 8,10, 13,16] # P3/8
9
+ - [23,29, 43,55, 73,105] # P4/16
10
+ - [146,217, 231,300, 335,433] # P5/32
11
+
12
+ # YOLOv5 backbone
13
+ backbone:
14
+ # [from, number, module, args]
15
+ [[-1, 1, StemBlock, [32, 3, 2]], # 0-P2/4
16
+ [-1, 1, ShuffleV2Block, [128, 2]], # 1-P3/8
17
+ [-1, 3, ShuffleV2Block, [128, 1]], # 2
18
+ [-1, 1, ShuffleV2Block, [256, 2]], # 3-P4/16
19
+ [-1, 7, ShuffleV2Block, [256, 1]], # 4
20
+ [-1, 1, ShuffleV2Block, [512, 2]], # 5-P5/32
21
+ [-1, 3, ShuffleV2Block, [512, 1]], # 6
22
+ ]
23
+
24
+ # YOLOv5 head
25
+ head:
26
+ [[-1, 1, Conv, [128, 1, 1]],
27
+ [-1, 1, nn.Upsample, [None, 2, 'nearest']],
28
+ [[-1, 4], 1, Concat, [1]], # cat backbone P4
29
+ [-1, 1, C3, [128, False]], # 10
30
+
31
+ [-1, 1, Conv, [128, 1, 1]],
32
+ [-1, 1, nn.Upsample, [None, 2, 'nearest']],
33
+ [[-1, 2], 1, Concat, [1]], # cat backbone P3
34
+ [-1, 1, C3, [128, False]], # 14 (P3/8-small)
35
+
36
+ [-1, 1, Conv, [128, 3, 2]],
37
+ [[-1, 11], 1, Concat, [1]], # cat head P4
38
+ [-1, 1, C3, [128, False]], # 17 (P4/16-medium)
39
+
40
+ [-1, 1, Conv, [128, 3, 2]],
41
+ [[-1, 7], 1, Concat, [1]], # cat head P5
42
+ [-1, 1, C3, [128, False]], # 20 (P5/32-large)
43
+
44
+ [[14, 17, 20], 1, Detect, [nc, anchors]], # Detect(P3, P4, P5)
45
+ ]
CodeFormer/facelib/detection/yolov5face/utils/__init__.py ADDED
File without changes
CodeFormer/facelib/detection/yolov5face/utils/autoanchor.py ADDED
@@ -0,0 +1,12 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Auto-anchor utils
2
+
3
+
4
+ def check_anchor_order(m):
5
+ # Check anchor order against stride order for YOLOv5 Detect() module m, and correct if necessary
6
+ a = m.anchor_grid.prod(-1).view(-1) # anchor area
7
+ da = a[-1] - a[0] # delta a
8
+ ds = m.stride[-1] - m.stride[0] # delta s
9
+ if da.sign() != ds.sign(): # same order
10
+ print("Reversing anchor order")
11
+ m.anchors[:] = m.anchors.flip(0)
12
+ m.anchor_grid[:] = m.anchor_grid.flip(0)
CodeFormer/facelib/detection/yolov5face/utils/datasets.py ADDED
@@ -0,0 +1,35 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import cv2
2
+ import numpy as np
3
+
4
+
5
+ def letterbox(img, new_shape=(640, 640), color=(114, 114, 114), auto=True, scale_fill=False, scaleup=True):
6
+ # Resize image to a 32-pixel-multiple rectangle https://github.com/ultralytics/yolov3/issues/232
7
+ shape = img.shape[:2] # current shape [height, width]
8
+ if isinstance(new_shape, int):
9
+ new_shape = (new_shape, new_shape)
10
+
11
+ # Scale ratio (new / old)
12
+ r = min(new_shape[0] / shape[0], new_shape[1] / shape[1])
13
+ if not scaleup: # only scale down, do not scale up (for better test mAP)
14
+ r = min(r, 1.0)
15
+
16
+ # Compute padding
17
+ ratio = r, r # width, height ratios
18
+ new_unpad = int(round(shape[1] * r)), int(round(shape[0] * r))
19
+ dw, dh = new_shape[1] - new_unpad[0], new_shape[0] - new_unpad[1] # wh padding
20
+ if auto: # minimum rectangle
21
+ dw, dh = np.mod(dw, 64), np.mod(dh, 64) # wh padding
22
+ elif scale_fill: # stretch
23
+ dw, dh = 0.0, 0.0
24
+ new_unpad = (new_shape[1], new_shape[0])
25
+ ratio = new_shape[1] / shape[1], new_shape[0] / shape[0] # width, height ratios
26
+
27
+ dw /= 2 # divide padding into 2 sides
28
+ dh /= 2
29
+
30
+ if shape[::-1] != new_unpad: # resize
31
+ img = cv2.resize(img, new_unpad, interpolation=cv2.INTER_LINEAR)
32
+ top, bottom = int(round(dh - 0.1)), int(round(dh + 0.1))
33
+ left, right = int(round(dw - 0.1)), int(round(dw + 0.1))
34
+ img = cv2.copyMakeBorder(img, top, bottom, left, right, cv2.BORDER_CONSTANT, value=color) # add border
35
+ return img, ratio, (dw, dh)
CodeFormer/facelib/detection/yolov5face/utils/extract_ckpt.py ADDED
@@ -0,0 +1,5 @@
 
 
 
 
 
 
1
+ import torch
2
+ import sys
3
+ sys.path.insert(0,'./facelib/detection/yolov5face')
4
+ model = torch.load('facelib/detection/yolov5face/yolov5n-face.pt', map_location='cpu')['model']
5
+ torch.save(model.state_dict(),'weights/facelib/yolov5n-face.pth')
CodeFormer/facelib/detection/yolov5face/utils/general.py ADDED
@@ -0,0 +1,271 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import math
2
+ import time
3
+
4
+ import numpy as np
5
+ import torch
6
+ import torchvision
7
+
8
+
9
+ def check_img_size(img_size, s=32):
10
+ # Verify img_size is a multiple of stride s
11
+ new_size = make_divisible(img_size, int(s)) # ceil gs-multiple
12
+ # if new_size != img_size:
13
+ # print(f"WARNING: --img-size {img_size:g} must be multiple of max stride {s:g}, updating to {new_size:g}")
14
+ return new_size
15
+
16
+
17
+ def make_divisible(x, divisor):
18
+ # Returns x evenly divisible by divisor
19
+ return math.ceil(x / divisor) * divisor
20
+
21
+
22
+ def xyxy2xywh(x):
23
+ # Convert nx4 boxes from [x1, y1, x2, y2] to [x, y, w, h] where xy1=top-left, xy2=bottom-right
24
+ y = x.clone() if isinstance(x, torch.Tensor) else np.copy(x)
25
+ y[:, 0] = (x[:, 0] + x[:, 2]) / 2 # x center
26
+ y[:, 1] = (x[:, 1] + x[:, 3]) / 2 # y center
27
+ y[:, 2] = x[:, 2] - x[:, 0] # width
28
+ y[:, 3] = x[:, 3] - x[:, 1] # height
29
+ return y
30
+
31
+
32
+ def xywh2xyxy(x):
33
+ # Convert nx4 boxes from [x, y, w, h] to [x1, y1, x2, y2] where xy1=top-left, xy2=bottom-right
34
+ y = x.clone() if isinstance(x, torch.Tensor) else np.copy(x)
35
+ y[:, 0] = x[:, 0] - x[:, 2] / 2 # top left x
36
+ y[:, 1] = x[:, 1] - x[:, 3] / 2 # top left y
37
+ y[:, 2] = x[:, 0] + x[:, 2] / 2 # bottom right x
38
+ y[:, 3] = x[:, 1] + x[:, 3] / 2 # bottom right y
39
+ return y
40
+
41
+
42
+ def scale_coords(img1_shape, coords, img0_shape, ratio_pad=None):
43
+ # Rescale coords (xyxy) from img1_shape to img0_shape
44
+ if ratio_pad is None: # calculate from img0_shape
45
+ gain = min(img1_shape[0] / img0_shape[0], img1_shape[1] / img0_shape[1]) # gain = old / new
46
+ pad = (img1_shape[1] - img0_shape[1] * gain) / 2, (img1_shape[0] - img0_shape[0] * gain) / 2 # wh padding
47
+ else:
48
+ gain = ratio_pad[0][0]
49
+ pad = ratio_pad[1]
50
+
51
+ coords[:, [0, 2]] -= pad[0] # x padding
52
+ coords[:, [1, 3]] -= pad[1] # y padding
53
+ coords[:, :4] /= gain
54
+ clip_coords(coords, img0_shape)
55
+ return coords
56
+
57
+
58
+ def clip_coords(boxes, img_shape):
59
+ # Clip bounding xyxy bounding boxes to image shape (height, width)
60
+ boxes[:, 0].clamp_(0, img_shape[1]) # x1
61
+ boxes[:, 1].clamp_(0, img_shape[0]) # y1
62
+ boxes[:, 2].clamp_(0, img_shape[1]) # x2
63
+ boxes[:, 3].clamp_(0, img_shape[0]) # y2
64
+
65
+
66
+ def box_iou(box1, box2):
67
+ # https://github.com/pytorch/vision/blob/master/torchvision/ops/boxes.py
68
+ """
69
+ Return intersection-over-union (Jaccard index) of boxes.
70
+ Both sets of boxes are expected to be in (x1, y1, x2, y2) format.
71
+ Arguments:
72
+ box1 (Tensor[N, 4])
73
+ box2 (Tensor[M, 4])
74
+ Returns:
75
+ iou (Tensor[N, M]): the NxM matrix containing the pairwise
76
+ IoU values for every element in boxes1 and boxes2
77
+ """
78
+
79
+ def box_area(box):
80
+ return (box[2] - box[0]) * (box[3] - box[1])
81
+
82
+ area1 = box_area(box1.T)
83
+ area2 = box_area(box2.T)
84
+
85
+ inter = (torch.min(box1[:, None, 2:], box2[:, 2:]) - torch.max(box1[:, None, :2], box2[:, :2])).clamp(0).prod(2)
86
+ return inter / (area1[:, None] + area2 - inter)
87
+
88
+
89
+ def non_max_suppression_face(prediction, conf_thres=0.25, iou_thres=0.45, classes=None, agnostic=False, labels=()):
90
+ """Performs Non-Maximum Suppression (NMS) on inference results
91
+ Returns:
92
+ detections with shape: nx6 (x1, y1, x2, y2, conf, cls)
93
+ """
94
+
95
+ nc = prediction.shape[2] - 15 # number of classes
96
+ xc = prediction[..., 4] > conf_thres # candidates
97
+
98
+ # Settings
99
+ # (pixels) maximum box width and height
100
+ max_wh = 4096
101
+ time_limit = 10.0 # seconds to quit after
102
+ redundant = True # require redundant detections
103
+ multi_label = nc > 1 # multiple labels per box (adds 0.5ms/img)
104
+ merge = False # use merge-NMS
105
+
106
+ t = time.time()
107
+ output = [torch.zeros((0, 16), device=prediction.device)] * prediction.shape[0]
108
+ for xi, x in enumerate(prediction): # image index, image inference
109
+ # Apply constraints
110
+ x = x[xc[xi]] # confidence
111
+
112
+ # Cat apriori labels if autolabelling
113
+ if labels and len(labels[xi]):
114
+ label = labels[xi]
115
+ v = torch.zeros((len(label), nc + 15), device=x.device)
116
+ v[:, :4] = label[:, 1:5] # box
117
+ v[:, 4] = 1.0 # conf
118
+ v[range(len(label)), label[:, 0].long() + 15] = 1.0 # cls
119
+ x = torch.cat((x, v), 0)
120
+
121
+ # If none remain process next image
122
+ if not x.shape[0]:
123
+ continue
124
+
125
+ # Compute conf
126
+ x[:, 15:] *= x[:, 4:5] # conf = obj_conf * cls_conf
127
+
128
+ # Box (center x, center y, width, height) to (x1, y1, x2, y2)
129
+ box = xywh2xyxy(x[:, :4])
130
+
131
+ # Detections matrix nx6 (xyxy, conf, landmarks, cls)
132
+ if multi_label:
133
+ i, j = (x[:, 15:] > conf_thres).nonzero(as_tuple=False).T
134
+ x = torch.cat((box[i], x[i, j + 15, None], x[:, 5:15], j[:, None].float()), 1)
135
+ else: # best class only
136
+ conf, j = x[:, 15:].max(1, keepdim=True)
137
+ x = torch.cat((box, conf, x[:, 5:15], j.float()), 1)[conf.view(-1) > conf_thres]
138
+
139
+ # Filter by class
140
+ if classes is not None:
141
+ x = x[(x[:, 5:6] == torch.tensor(classes, device=x.device)).any(1)]
142
+
143
+ # If none remain process next image
144
+ n = x.shape[0] # number of boxes
145
+ if not n:
146
+ continue
147
+
148
+ # Batched NMS
149
+ c = x[:, 15:16] * (0 if agnostic else max_wh) # classes
150
+ boxes, scores = x[:, :4] + c, x[:, 4] # boxes (offset by class), scores
151
+ i = torchvision.ops.nms(boxes, scores, iou_thres) # NMS
152
+
153
+ if merge and (1 < n < 3e3): # Merge NMS (boxes merged using weighted mean)
154
+ # update boxes as boxes(i,4) = weights(i,n) * boxes(n,4)
155
+ iou = box_iou(boxes[i], boxes) > iou_thres # iou matrix
156
+ weights = iou * scores[None] # box weights
157
+ x[i, :4] = torch.mm(weights, x[:, :4]).float() / weights.sum(1, keepdim=True) # merged boxes
158
+ if redundant:
159
+ i = i[iou.sum(1) > 1] # require redundancy
160
+
161
+ output[xi] = x[i]
162
+ if (time.time() - t) > time_limit:
163
+ break # time limit exceeded
164
+
165
+ return output
166
+
167
+
168
+ def non_max_suppression(prediction, conf_thres=0.25, iou_thres=0.45, classes=None, agnostic=False, labels=()):
169
+ """Performs Non-Maximum Suppression (NMS) on inference results
170
+
171
+ Returns:
172
+ detections with shape: nx6 (x1, y1, x2, y2, conf, cls)
173
+ """
174
+
175
+ nc = prediction.shape[2] - 5 # number of classes
176
+ xc = prediction[..., 4] > conf_thres # candidates
177
+
178
+ # Settings
179
+ # (pixels) maximum box width and height
180
+ max_wh = 4096
181
+ time_limit = 10.0 # seconds to quit after
182
+ redundant = True # require redundant detections
183
+ multi_label = nc > 1 # multiple labels per box (adds 0.5ms/img)
184
+ merge = False # use merge-NMS
185
+
186
+ t = time.time()
187
+ output = [torch.zeros((0, 6), device=prediction.device)] * prediction.shape[0]
188
+ for xi, x in enumerate(prediction): # image index, image inference
189
+ x = x[xc[xi]] # confidence
190
+
191
+ # Cat apriori labels if autolabelling
192
+ if labels and len(labels[xi]):
193
+ label_id = labels[xi]
194
+ v = torch.zeros((len(label_id), nc + 5), device=x.device)
195
+ v[:, :4] = label_id[:, 1:5] # box
196
+ v[:, 4] = 1.0 # conf
197
+ v[range(len(label_id)), label_id[:, 0].long() + 5] = 1.0 # cls
198
+ x = torch.cat((x, v), 0)
199
+
200
+ # If none remain process next image
201
+ if not x.shape[0]:
202
+ continue
203
+
204
+ # Compute conf
205
+ x[:, 5:] *= x[:, 4:5] # conf = obj_conf * cls_conf
206
+
207
+ # Box (center x, center y, width, height) to (x1, y1, x2, y2)
208
+ box = xywh2xyxy(x[:, :4])
209
+
210
+ # Detections matrix nx6 (xyxy, conf, cls)
211
+ if multi_label:
212
+ i, j = (x[:, 5:] > conf_thres).nonzero(as_tuple=False).T
213
+ x = torch.cat((box[i], x[i, j + 5, None], j[:, None].float()), 1)
214
+ else: # best class only
215
+ conf, j = x[:, 5:].max(1, keepdim=True)
216
+ x = torch.cat((box, conf, j.float()), 1)[conf.view(-1) > conf_thres]
217
+
218
+ # Filter by class
219
+ if classes is not None:
220
+ x = x[(x[:, 5:6] == torch.tensor(classes, device=x.device)).any(1)]
221
+
222
+ # Check shape
223
+ n = x.shape[0] # number of boxes
224
+ if not n: # no boxes
225
+ continue
226
+
227
+ x = x[x[:, 4].argsort(descending=True)] # sort by confidence
228
+
229
+ # Batched NMS
230
+ c = x[:, 5:6] * (0 if agnostic else max_wh) # classes
231
+ boxes, scores = x[:, :4] + c, x[:, 4] # boxes (offset by class), scores
232
+ i = torchvision.ops.nms(boxes, scores, iou_thres) # NMS
233
+ if merge and (1 < n < 3e3): # Merge NMS (boxes merged using weighted mean)
234
+ # update boxes as boxes(i,4) = weights(i,n) * boxes(n,4)
235
+ iou = box_iou(boxes[i], boxes) > iou_thres # iou matrix
236
+ weights = iou * scores[None] # box weights
237
+ x[i, :4] = torch.mm(weights, x[:, :4]).float() / weights.sum(1, keepdim=True) # merged boxes
238
+ if redundant:
239
+ i = i[iou.sum(1) > 1] # require redundancy
240
+
241
+ output[xi] = x[i]
242
+ if (time.time() - t) > time_limit:
243
+ print(f"WARNING: NMS time limit {time_limit}s exceeded")
244
+ break # time limit exceeded
245
+
246
+ return output
247
+
248
+
249
+ def scale_coords_landmarks(img1_shape, coords, img0_shape, ratio_pad=None):
250
+ # Rescale coords (xyxy) from img1_shape to img0_shape
251
+ if ratio_pad is None: # calculate from img0_shape
252
+ gain = min(img1_shape[0] / img0_shape[0], img1_shape[1] / img0_shape[1]) # gain = old / new
253
+ pad = (img1_shape[1] - img0_shape[1] * gain) / 2, (img1_shape[0] - img0_shape[0] * gain) / 2 # wh padding
254
+ else:
255
+ gain = ratio_pad[0][0]
256
+ pad = ratio_pad[1]
257
+
258
+ coords[:, [0, 2, 4, 6, 8]] -= pad[0] # x padding
259
+ coords[:, [1, 3, 5, 7, 9]] -= pad[1] # y padding
260
+ coords[:, :10] /= gain
261
+ coords[:, 0].clamp_(0, img0_shape[1]) # x1
262
+ coords[:, 1].clamp_(0, img0_shape[0]) # y1
263
+ coords[:, 2].clamp_(0, img0_shape[1]) # x2
264
+ coords[:, 3].clamp_(0, img0_shape[0]) # y2
265
+ coords[:, 4].clamp_(0, img0_shape[1]) # x3
266
+ coords[:, 5].clamp_(0, img0_shape[0]) # y3
267
+ coords[:, 6].clamp_(0, img0_shape[1]) # x4
268
+ coords[:, 7].clamp_(0, img0_shape[0]) # y4
269
+ coords[:, 8].clamp_(0, img0_shape[1]) # x5
270
+ coords[:, 9].clamp_(0, img0_shape[0]) # y5
271
+ return coords
CodeFormer/facelib/detection/yolov5face/utils/torch_utils.py ADDED
@@ -0,0 +1,40 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import torch
2
+ from torch import nn
3
+
4
+
5
+ def fuse_conv_and_bn(conv, bn):
6
+ # Fuse convolution and batchnorm layers https://tehnokv.com/posts/fusing-batchnorm-and-conv/
7
+ fusedconv = (
8
+ nn.Conv2d(
9
+ conv.in_channels,
10
+ conv.out_channels,
11
+ kernel_size=conv.kernel_size,
12
+ stride=conv.stride,
13
+ padding=conv.padding,
14
+ groups=conv.groups,
15
+ bias=True,
16
+ )
17
+ .requires_grad_(False)
18
+ .to(conv.weight.device)
19
+ )
20
+
21
+ # prepare filters
22
+ w_conv = conv.weight.clone().view(conv.out_channels, -1)
23
+ w_bn = torch.diag(bn.weight.div(torch.sqrt(bn.eps + bn.running_var)))
24
+ fusedconv.weight.copy_(torch.mm(w_bn, w_conv).view(fusedconv.weight.size()))
25
+
26
+ # prepare spatial bias
27
+ b_conv = torch.zeros(conv.weight.size(0), device=conv.weight.device) if conv.bias is None else conv.bias
28
+ b_bn = bn.bias - bn.weight.mul(bn.running_mean).div(torch.sqrt(bn.running_var + bn.eps))
29
+ fusedconv.bias.copy_(torch.mm(w_bn, b_conv.reshape(-1, 1)).reshape(-1) + b_bn)
30
+
31
+ return fusedconv
32
+
33
+
34
+ def copy_attr(a, b, include=(), exclude=()):
35
+ # Copy attributes from b to a, options to only include [...] and to exclude [...]
36
+ for k, v in b.__dict__.items():
37
+ if (include and k not in include) or k.startswith("_") or k in exclude:
38
+ continue
39
+
40
+ setattr(a, k, v)
CodeFormer/facelib/parsing/__init__.py ADDED
@@ -0,0 +1,23 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import torch
2
+
3
+ from facelib.utils import load_file_from_url
4
+ from .bisenet import BiSeNet
5
+ from .parsenet import ParseNet
6
+
7
+
8
+ def init_parsing_model(model_name='bisenet', half=False, device='cuda'):
9
+ if model_name == 'bisenet':
10
+ model = BiSeNet(num_class=19)
11
+ model_url = 'https://github.com/sczhou/CodeFormer/releases/download/v0.1.0/parsing_bisenet.pth'
12
+ elif model_name == 'parsenet':
13
+ model = ParseNet(in_size=512, out_size=512, parsing_ch=19)
14
+ model_url = 'https://github.com/sczhou/CodeFormer/releases/download/v0.1.0/parsing_parsenet.pth'
15
+ else:
16
+ raise NotImplementedError(f'{model_name} is not implemented.')
17
+
18
+ model_path = load_file_from_url(url=model_url, model_dir='weights/facelib', progress=True, file_name=None)
19
+ load_net = torch.load(model_path, map_location=lambda storage, loc: storage)
20
+ model.load_state_dict(load_net, strict=True)
21
+ model.eval()
22
+ model = model.to(device)
23
+ return model
CodeFormer/facelib/parsing/bisenet.py ADDED
@@ -0,0 +1,140 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import torch
2
+ import torch.nn as nn
3
+ import torch.nn.functional as F
4
+
5
+ from .resnet import ResNet18
6
+
7
+
8
+ class ConvBNReLU(nn.Module):
9
+
10
+ def __init__(self, in_chan, out_chan, ks=3, stride=1, padding=1):
11
+ super(ConvBNReLU, self).__init__()
12
+ self.conv = nn.Conv2d(in_chan, out_chan, kernel_size=ks, stride=stride, padding=padding, bias=False)
13
+ self.bn = nn.BatchNorm2d(out_chan)
14
+
15
+ def forward(self, x):
16
+ x = self.conv(x)
17
+ x = F.relu(self.bn(x))
18
+ return x
19
+
20
+
21
+ class BiSeNetOutput(nn.Module):
22
+
23
+ def __init__(self, in_chan, mid_chan, num_class):
24
+ super(BiSeNetOutput, self).__init__()
25
+ self.conv = ConvBNReLU(in_chan, mid_chan, ks=3, stride=1, padding=1)
26
+ self.conv_out = nn.Conv2d(mid_chan, num_class, kernel_size=1, bias=False)
27
+
28
+ def forward(self, x):
29
+ feat = self.conv(x)
30
+ out = self.conv_out(feat)
31
+ return out, feat
32
+
33
+
34
+ class AttentionRefinementModule(nn.Module):
35
+
36
+ def __init__(self, in_chan, out_chan):
37
+ super(AttentionRefinementModule, self).__init__()
38
+ self.conv = ConvBNReLU(in_chan, out_chan, ks=3, stride=1, padding=1)
39
+ self.conv_atten = nn.Conv2d(out_chan, out_chan, kernel_size=1, bias=False)
40
+ self.bn_atten = nn.BatchNorm2d(out_chan)
41
+ self.sigmoid_atten = nn.Sigmoid()
42
+
43
+ def forward(self, x):
44
+ feat = self.conv(x)
45
+ atten = F.avg_pool2d(feat, feat.size()[2:])
46
+ atten = self.conv_atten(atten)
47
+ atten = self.bn_atten(atten)
48
+ atten = self.sigmoid_atten(atten)
49
+ out = torch.mul(feat, atten)
50
+ return out
51
+
52
+
53
+ class ContextPath(nn.Module):
54
+
55
+ def __init__(self):
56
+ super(ContextPath, self).__init__()
57
+ self.resnet = ResNet18()
58
+ self.arm16 = AttentionRefinementModule(256, 128)
59
+ self.arm32 = AttentionRefinementModule(512, 128)
60
+ self.conv_head32 = ConvBNReLU(128, 128, ks=3, stride=1, padding=1)
61
+ self.conv_head16 = ConvBNReLU(128, 128, ks=3, stride=1, padding=1)
62
+ self.conv_avg = ConvBNReLU(512, 128, ks=1, stride=1, padding=0)
63
+
64
+ def forward(self, x):
65
+ feat8, feat16, feat32 = self.resnet(x)
66
+ h8, w8 = feat8.size()[2:]
67
+ h16, w16 = feat16.size()[2:]
68
+ h32, w32 = feat32.size()[2:]
69
+
70
+ avg = F.avg_pool2d(feat32, feat32.size()[2:])
71
+ avg = self.conv_avg(avg)
72
+ avg_up = F.interpolate(avg, (h32, w32), mode='nearest')
73
+
74
+ feat32_arm = self.arm32(feat32)
75
+ feat32_sum = feat32_arm + avg_up
76
+ feat32_up = F.interpolate(feat32_sum, (h16, w16), mode='nearest')
77
+ feat32_up = self.conv_head32(feat32_up)
78
+
79
+ feat16_arm = self.arm16(feat16)
80
+ feat16_sum = feat16_arm + feat32_up
81
+ feat16_up = F.interpolate(feat16_sum, (h8, w8), mode='nearest')
82
+ feat16_up = self.conv_head16(feat16_up)
83
+
84
+ return feat8, feat16_up, feat32_up # x8, x8, x16
85
+
86
+
87
+ class FeatureFusionModule(nn.Module):
88
+
89
+ def __init__(self, in_chan, out_chan):
90
+ super(FeatureFusionModule, self).__init__()
91
+ self.convblk = ConvBNReLU(in_chan, out_chan, ks=1, stride=1, padding=0)
92
+ self.conv1 = nn.Conv2d(out_chan, out_chan // 4, kernel_size=1, stride=1, padding=0, bias=False)
93
+ self.conv2 = nn.Conv2d(out_chan // 4, out_chan, kernel_size=1, stride=1, padding=0, bias=False)
94
+ self.relu = nn.ReLU(inplace=True)
95
+ self.sigmoid = nn.Sigmoid()
96
+
97
+ def forward(self, fsp, fcp):
98
+ fcat = torch.cat([fsp, fcp], dim=1)
99
+ feat = self.convblk(fcat)
100
+ atten = F.avg_pool2d(feat, feat.size()[2:])
101
+ atten = self.conv1(atten)
102
+ atten = self.relu(atten)
103
+ atten = self.conv2(atten)
104
+ atten = self.sigmoid(atten)
105
+ feat_atten = torch.mul(feat, atten)
106
+ feat_out = feat_atten + feat
107
+ return feat_out
108
+
109
+
110
+ class BiSeNet(nn.Module):
111
+
112
+ def __init__(self, num_class):
113
+ super(BiSeNet, self).__init__()
114
+ self.cp = ContextPath()
115
+ self.ffm = FeatureFusionModule(256, 256)
116
+ self.conv_out = BiSeNetOutput(256, 256, num_class)
117
+ self.conv_out16 = BiSeNetOutput(128, 64, num_class)
118
+ self.conv_out32 = BiSeNetOutput(128, 64, num_class)
119
+
120
+ def forward(self, x, return_feat=False):
121
+ h, w = x.size()[2:]
122
+ feat_res8, feat_cp8, feat_cp16 = self.cp(x) # return res3b1 feature
123
+ feat_sp = feat_res8 # replace spatial path feature with res3b1 feature
124
+ feat_fuse = self.ffm(feat_sp, feat_cp8)
125
+
126
+ out, feat = self.conv_out(feat_fuse)
127
+ out16, feat16 = self.conv_out16(feat_cp8)
128
+ out32, feat32 = self.conv_out32(feat_cp16)
129
+
130
+ out = F.interpolate(out, (h, w), mode='bilinear', align_corners=True)
131
+ out16 = F.interpolate(out16, (h, w), mode='bilinear', align_corners=True)
132
+ out32 = F.interpolate(out32, (h, w), mode='bilinear', align_corners=True)
133
+
134
+ if return_feat:
135
+ feat = F.interpolate(feat, (h, w), mode='bilinear', align_corners=True)
136
+ feat16 = F.interpolate(feat16, (h, w), mode='bilinear', align_corners=True)
137
+ feat32 = F.interpolate(feat32, (h, w), mode='bilinear', align_corners=True)
138
+ return out, out16, out32, feat, feat16, feat32
139
+ else:
140
+ return out, out16, out32
CodeFormer/facelib/parsing/parsenet.py ADDED
@@ -0,0 +1,194 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Modified from https://github.com/chaofengc/PSFRGAN
2
+ """
3
+ import numpy as np
4
+ import torch.nn as nn
5
+ from torch.nn import functional as F
6
+
7
+
8
+ class NormLayer(nn.Module):
9
+ """Normalization Layers.
10
+
11
+ Args:
12
+ channels: input channels, for batch norm and instance norm.
13
+ input_size: input shape without batch size, for layer norm.
14
+ """
15
+
16
+ def __init__(self, channels, normalize_shape=None, norm_type='bn'):
17
+ super(NormLayer, self).__init__()
18
+ norm_type = norm_type.lower()
19
+ self.norm_type = norm_type
20
+ if norm_type == 'bn':
21
+ self.norm = nn.BatchNorm2d(channels, affine=True)
22
+ elif norm_type == 'in':
23
+ self.norm = nn.InstanceNorm2d(channels, affine=False)
24
+ elif norm_type == 'gn':
25
+ self.norm = nn.GroupNorm(32, channels, affine=True)
26
+ elif norm_type == 'pixel':
27
+ self.norm = lambda x: F.normalize(x, p=2, dim=1)
28
+ elif norm_type == 'layer':
29
+ self.norm = nn.LayerNorm(normalize_shape)
30
+ elif norm_type == 'none':
31
+ self.norm = lambda x: x * 1.0
32
+ else:
33
+ assert 1 == 0, f'Norm type {norm_type} not support.'
34
+
35
+ def forward(self, x, ref=None):
36
+ if self.norm_type == 'spade':
37
+ return self.norm(x, ref)
38
+ else:
39
+ return self.norm(x)
40
+
41
+
42
+ class ReluLayer(nn.Module):
43
+ """Relu Layer.
44
+
45
+ Args:
46
+ relu type: type of relu layer, candidates are
47
+ - ReLU
48
+ - LeakyReLU: default relu slope 0.2
49
+ - PRelu
50
+ - SELU
51
+ - none: direct pass
52
+ """
53
+
54
+ def __init__(self, channels, relu_type='relu'):
55
+ super(ReluLayer, self).__init__()
56
+ relu_type = relu_type.lower()
57
+ if relu_type == 'relu':
58
+ self.func = nn.ReLU(True)
59
+ elif relu_type == 'leakyrelu':
60
+ self.func = nn.LeakyReLU(0.2, inplace=True)
61
+ elif relu_type == 'prelu':
62
+ self.func = nn.PReLU(channels)
63
+ elif relu_type == 'selu':
64
+ self.func = nn.SELU(True)
65
+ elif relu_type == 'none':
66
+ self.func = lambda x: x * 1.0
67
+ else:
68
+ assert 1 == 0, f'Relu type {relu_type} not support.'
69
+
70
+ def forward(self, x):
71
+ return self.func(x)
72
+
73
+
74
+ class ConvLayer(nn.Module):
75
+
76
+ def __init__(self,
77
+ in_channels,
78
+ out_channels,
79
+ kernel_size=3,
80
+ scale='none',
81
+ norm_type='none',
82
+ relu_type='none',
83
+ use_pad=True,
84
+ bias=True):
85
+ super(ConvLayer, self).__init__()
86
+ self.use_pad = use_pad
87
+ self.norm_type = norm_type
88
+ if norm_type in ['bn']:
89
+ bias = False
90
+
91
+ stride = 2 if scale == 'down' else 1
92
+
93
+ self.scale_func = lambda x: x
94
+ if scale == 'up':
95
+ self.scale_func = lambda x: nn.functional.interpolate(x, scale_factor=2, mode='nearest')
96
+
97
+ self.reflection_pad = nn.ReflectionPad2d(int(np.ceil((kernel_size - 1.) / 2)))
98
+ self.conv2d = nn.Conv2d(in_channels, out_channels, kernel_size, stride, bias=bias)
99
+
100
+ self.relu = ReluLayer(out_channels, relu_type)
101
+ self.norm = NormLayer(out_channels, norm_type=norm_type)
102
+
103
+ def forward(self, x):
104
+ out = self.scale_func(x)
105
+ if self.use_pad:
106
+ out = self.reflection_pad(out)
107
+ out = self.conv2d(out)
108
+ out = self.norm(out)
109
+ out = self.relu(out)
110
+ return out
111
+
112
+
113
+ class ResidualBlock(nn.Module):
114
+ """
115
+ Residual block recommended in: http://torch.ch/blog/2016/02/04/resnets.html
116
+ """
117
+
118
+ def __init__(self, c_in, c_out, relu_type='prelu', norm_type='bn', scale='none'):
119
+ super(ResidualBlock, self).__init__()
120
+
121
+ if scale == 'none' and c_in == c_out:
122
+ self.shortcut_func = lambda x: x
123
+ else:
124
+ self.shortcut_func = ConvLayer(c_in, c_out, 3, scale)
125
+
126
+ scale_config_dict = {'down': ['none', 'down'], 'up': ['up', 'none'], 'none': ['none', 'none']}
127
+ scale_conf = scale_config_dict[scale]
128
+
129
+ self.conv1 = ConvLayer(c_in, c_out, 3, scale_conf[0], norm_type=norm_type, relu_type=relu_type)
130
+ self.conv2 = ConvLayer(c_out, c_out, 3, scale_conf[1], norm_type=norm_type, relu_type='none')
131
+
132
+ def forward(self, x):
133
+ identity = self.shortcut_func(x)
134
+
135
+ res = self.conv1(x)
136
+ res = self.conv2(res)
137
+ return identity + res
138
+
139
+
140
+ class ParseNet(nn.Module):
141
+
142
+ def __init__(self,
143
+ in_size=128,
144
+ out_size=128,
145
+ min_feat_size=32,
146
+ base_ch=64,
147
+ parsing_ch=19,
148
+ res_depth=10,
149
+ relu_type='LeakyReLU',
150
+ norm_type='bn',
151
+ ch_range=[32, 256]):
152
+ super().__init__()
153
+ self.res_depth = res_depth
154
+ act_args = {'norm_type': norm_type, 'relu_type': relu_type}
155
+ min_ch, max_ch = ch_range
156
+
157
+ ch_clip = lambda x: max(min_ch, min(x, max_ch)) # noqa: E731
158
+ min_feat_size = min(in_size, min_feat_size)
159
+
160
+ down_steps = int(np.log2(in_size // min_feat_size))
161
+ up_steps = int(np.log2(out_size // min_feat_size))
162
+
163
+ # =============== define encoder-body-decoder ====================
164
+ self.encoder = []
165
+ self.encoder.append(ConvLayer(3, base_ch, 3, 1))
166
+ head_ch = base_ch
167
+ for i in range(down_steps):
168
+ cin, cout = ch_clip(head_ch), ch_clip(head_ch * 2)
169
+ self.encoder.append(ResidualBlock(cin, cout, scale='down', **act_args))
170
+ head_ch = head_ch * 2
171
+
172
+ self.body = []
173
+ for i in range(res_depth):
174
+ self.body.append(ResidualBlock(ch_clip(head_ch), ch_clip(head_ch), **act_args))
175
+
176
+ self.decoder = []
177
+ for i in range(up_steps):
178
+ cin, cout = ch_clip(head_ch), ch_clip(head_ch // 2)
179
+ self.decoder.append(ResidualBlock(cin, cout, scale='up', **act_args))
180
+ head_ch = head_ch // 2
181
+
182
+ self.encoder = nn.Sequential(*self.encoder)
183
+ self.body = nn.Sequential(*self.body)
184
+ self.decoder = nn.Sequential(*self.decoder)
185
+ self.out_img_conv = ConvLayer(ch_clip(head_ch), 3)
186
+ self.out_mask_conv = ConvLayer(ch_clip(head_ch), parsing_ch)
187
+
188
+ def forward(self, x):
189
+ feat = self.encoder(x)
190
+ x = feat + self.body(feat)
191
+ x = self.decoder(x)
192
+ out_img = self.out_img_conv(x)
193
+ out_mask = self.out_mask_conv(x)
194
+ return out_mask, out_img
CodeFormer/facelib/parsing/resnet.py ADDED
@@ -0,0 +1,69 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import torch.nn as nn
2
+ import torch.nn.functional as F
3
+
4
+
5
+ def conv3x3(in_planes, out_planes, stride=1):
6
+ """3x3 convolution with padding"""
7
+ return nn.Conv2d(in_planes, out_planes, kernel_size=3, stride=stride, padding=1, bias=False)
8
+
9
+
10
+ class BasicBlock(nn.Module):
11
+
12
+ def __init__(self, in_chan, out_chan, stride=1):
13
+ super(BasicBlock, self).__init__()
14
+ self.conv1 = conv3x3(in_chan, out_chan, stride)
15
+ self.bn1 = nn.BatchNorm2d(out_chan)
16
+ self.conv2 = conv3x3(out_chan, out_chan)
17
+ self.bn2 = nn.BatchNorm2d(out_chan)
18
+ self.relu = nn.ReLU(inplace=True)
19
+ self.downsample = None
20
+ if in_chan != out_chan or stride != 1:
21
+ self.downsample = nn.Sequential(
22
+ nn.Conv2d(in_chan, out_chan, kernel_size=1, stride=stride, bias=False),
23
+ nn.BatchNorm2d(out_chan),
24
+ )
25
+
26
+ def forward(self, x):
27
+ residual = self.conv1(x)
28
+ residual = F.relu(self.bn1(residual))
29
+ residual = self.conv2(residual)
30
+ residual = self.bn2(residual)
31
+
32
+ shortcut = x
33
+ if self.downsample is not None:
34
+ shortcut = self.downsample(x)
35
+
36
+ out = shortcut + residual
37
+ out = self.relu(out)
38
+ return out
39
+
40
+
41
+ def create_layer_basic(in_chan, out_chan, bnum, stride=1):
42
+ layers = [BasicBlock(in_chan, out_chan, stride=stride)]
43
+ for i in range(bnum - 1):
44
+ layers.append(BasicBlock(out_chan, out_chan, stride=1))
45
+ return nn.Sequential(*layers)
46
+
47
+
48
+ class ResNet18(nn.Module):
49
+
50
+ def __init__(self):
51
+ super(ResNet18, self).__init__()
52
+ self.conv1 = nn.Conv2d(3, 64, kernel_size=7, stride=2, padding=3, bias=False)
53
+ self.bn1 = nn.BatchNorm2d(64)
54
+ self.maxpool = nn.MaxPool2d(kernel_size=3, stride=2, padding=1)
55
+ self.layer1 = create_layer_basic(64, 64, bnum=2, stride=1)
56
+ self.layer2 = create_layer_basic(64, 128, bnum=2, stride=2)
57
+ self.layer3 = create_layer_basic(128, 256, bnum=2, stride=2)
58
+ self.layer4 = create_layer_basic(256, 512, bnum=2, stride=2)
59
+
60
+ def forward(self, x):
61
+ x = self.conv1(x)
62
+ x = F.relu(self.bn1(x))
63
+ x = self.maxpool(x)
64
+
65
+ x = self.layer1(x)
66
+ feat8 = self.layer2(x) # 1/8
67
+ feat16 = self.layer3(feat8) # 1/16
68
+ feat32 = self.layer4(feat16) # 1/32
69
+ return feat8, feat16, feat32
CodeFormer/facelib/utils/__init__.py ADDED
@@ -0,0 +1,7 @@
 
 
 
 
 
 
 
 
1
+ from .face_utils import align_crop_face_landmarks, compute_increased_bbox, get_valid_bboxes, paste_face_back
2
+ from .misc import img2tensor, load_file_from_url, download_pretrained_models, scandir
3
+
4
+ __all__ = [
5
+ 'align_crop_face_landmarks', 'compute_increased_bbox', 'get_valid_bboxes', 'load_file_from_url',
6
+ 'download_pretrained_models', 'paste_face_back', 'img2tensor', 'scandir'
7
+ ]
CodeFormer/facelib/utils/face_restoration_helper.py ADDED
@@ -0,0 +1,525 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import cv2
2
+ import numpy as np
3
+ import os
4
+ import torch
5
+ from torchvision.transforms.functional import normalize
6
+
7
+ from facelib.detection import init_detection_model
8
+ from facelib.parsing import init_parsing_model
9
+ from facelib.utils.misc import img2tensor, imwrite, is_gray, bgr2gray, adain_npy
10
+ from basicsr.utils.download_util import load_file_from_url
11
+ from basicsr.utils.misc import get_device
12
+
13
+ dlib_model_url = {
14
+ 'face_detector': 'https://github.com/sczhou/CodeFormer/releases/download/v0.1.0/mmod_human_face_detector-4cb19393.dat',
15
+ 'shape_predictor_5': 'https://github.com/sczhou/CodeFormer/releases/download/v0.1.0/shape_predictor_5_face_landmarks-c4b1e980.dat'
16
+ }
17
+
18
+ def get_largest_face(det_faces, h, w):
19
+
20
+ def get_location(val, length):
21
+ if val < 0:
22
+ return 0
23
+ elif val > length:
24
+ return length
25
+ else:
26
+ return val
27
+
28
+ face_areas = []
29
+ for det_face in det_faces:
30
+ left = get_location(det_face[0], w)
31
+ right = get_location(det_face[2], w)
32
+ top = get_location(det_face[1], h)
33
+ bottom = get_location(det_face[3], h)
34
+ face_area = (right - left) * (bottom - top)
35
+ face_areas.append(face_area)
36
+ largest_idx = face_areas.index(max(face_areas))
37
+ return det_faces[largest_idx], largest_idx
38
+
39
+
40
+ def get_center_face(det_faces, h=0, w=0, center=None):
41
+ if center is not None:
42
+ center = np.array(center)
43
+ else:
44
+ center = np.array([w / 2, h / 2])
45
+ center_dist = []
46
+ for det_face in det_faces:
47
+ face_center = np.array([(det_face[0] + det_face[2]) / 2, (det_face[1] + det_face[3]) / 2])
48
+ dist = np.linalg.norm(face_center - center)
49
+ center_dist.append(dist)
50
+ center_idx = center_dist.index(min(center_dist))
51
+ return det_faces[center_idx], center_idx
52
+
53
+
54
+ class FaceRestoreHelper(object):
55
+ """Helper for the face restoration pipeline (base class)."""
56
+
57
+ def __init__(self,
58
+ upscale_factor,
59
+ face_size=512,
60
+ crop_ratio=(1, 1),
61
+ det_model='retinaface_resnet50',
62
+ save_ext='png',
63
+ template_3points=False,
64
+ pad_blur=False,
65
+ use_parse=False,
66
+ device=None):
67
+ self.template_3points = template_3points # improve robustness
68
+ self.upscale_factor = int(upscale_factor)
69
+ # the cropped face ratio based on the square face
70
+ self.crop_ratio = crop_ratio # (h, w)
71
+ assert (self.crop_ratio[0] >= 1 and self.crop_ratio[1] >= 1), 'crop ration only supports >=1'
72
+ self.face_size = (int(face_size * self.crop_ratio[1]), int(face_size * self.crop_ratio[0]))
73
+ self.det_model = det_model
74
+
75
+ if self.det_model == 'dlib':
76
+ # standard 5 landmarks for FFHQ faces with 1024 x 1024
77
+ self.face_template = np.array([[686.77227723, 488.62376238], [586.77227723, 493.59405941],
78
+ [337.91089109, 488.38613861], [437.95049505, 493.51485149],
79
+ [513.58415842, 678.5049505]])
80
+ self.face_template = self.face_template / (1024 // face_size)
81
+ elif self.template_3points:
82
+ self.face_template = np.array([[192, 240], [319, 240], [257, 371]])
83
+ else:
84
+ # standard 5 landmarks for FFHQ faces with 512 x 512
85
+ # facexlib
86
+ self.face_template = np.array([[192.98138, 239.94708], [318.90277, 240.1936], [256.63416, 314.01935],
87
+ [201.26117, 371.41043], [313.08905, 371.15118]])
88
+
89
+ # dlib: left_eye: 36:41 right_eye: 42:47 nose: 30,32,33,34 left mouth corner: 48 right mouth corner: 54
90
+ # self.face_template = np.array([[193.65928, 242.98541], [318.32558, 243.06108], [255.67984, 328.82894],
91
+ # [198.22603, 372.82502], [313.91018, 372.75659]])
92
+
93
+ self.face_template = self.face_template * (face_size / 512.0)
94
+ if self.crop_ratio[0] > 1:
95
+ self.face_template[:, 1] += face_size * (self.crop_ratio[0] - 1) / 2
96
+ if self.crop_ratio[1] > 1:
97
+ self.face_template[:, 0] += face_size * (self.crop_ratio[1] - 1) / 2
98
+ self.save_ext = save_ext
99
+ self.pad_blur = pad_blur
100
+ if self.pad_blur is True:
101
+ self.template_3points = False
102
+
103
+ self.all_landmarks_5 = []
104
+ self.det_faces = []
105
+ self.affine_matrices = []
106
+ self.inverse_affine_matrices = []
107
+ self.cropped_faces = []
108
+ self.restored_faces = []
109
+ self.pad_input_imgs = []
110
+
111
+ if device is None:
112
+ # self.device = torch.device('cuda' if torch.cuda.is_available() else 'cpu')
113
+ self.device = get_device()
114
+ else:
115
+ self.device = device
116
+
117
+ # init face detection model
118
+ if self.det_model == 'dlib':
119
+ self.face_detector, self.shape_predictor_5 = self.init_dlib(dlib_model_url['face_detector'], dlib_model_url['shape_predictor_5'])
120
+ else:
121
+ self.face_detector = init_detection_model(det_model, half=False, device=self.device)
122
+
123
+ # init face parsing model
124
+ self.use_parse = use_parse
125
+ self.face_parse = init_parsing_model(model_name='parsenet', device=self.device)
126
+
127
+ def set_upscale_factor(self, upscale_factor):
128
+ self.upscale_factor = upscale_factor
129
+
130
+ def read_image(self, img):
131
+ """img can be image path or cv2 loaded image."""
132
+ # self.input_img is Numpy array, (h, w, c), BGR, uint8, [0, 255]
133
+ if isinstance(img, str):
134
+ img = cv2.imread(img)
135
+
136
+ if np.max(img) > 256: # 16-bit image
137
+ img = img / 65535 * 255
138
+ if len(img.shape) == 2: # gray image
139
+ img = cv2.cvtColor(img, cv2.COLOR_GRAY2BGR)
140
+ elif img.shape[2] == 4: # BGRA image with alpha channel
141
+ img = img[:, :, 0:3]
142
+
143
+ self.input_img = img
144
+ self.is_gray = is_gray(img, threshold=10)
145
+ if self.is_gray:
146
+ print('Grayscale input: True')
147
+
148
+ if min(self.input_img.shape[:2])<512:
149
+ f = 512.0/min(self.input_img.shape[:2])
150
+ self.input_img = cv2.resize(self.input_img, (0,0), fx=f, fy=f, interpolation=cv2.INTER_LINEAR)
151
+
152
+ def init_dlib(self, detection_path, landmark5_path):
153
+ """Initialize the dlib detectors and predictors."""
154
+ try:
155
+ import dlib
156
+ except ImportError:
157
+ print('Please install dlib by running:' 'conda install -c conda-forge dlib')
158
+ detection_path = load_file_from_url(url=detection_path, model_dir='weights/dlib', progress=True, file_name=None)
159
+ landmark5_path = load_file_from_url(url=landmark5_path, model_dir='weights/dlib', progress=True, file_name=None)
160
+ face_detector = dlib.cnn_face_detection_model_v1(detection_path)
161
+ shape_predictor_5 = dlib.shape_predictor(landmark5_path)
162
+ return face_detector, shape_predictor_5
163
+
164
+ def get_face_landmarks_5_dlib(self,
165
+ only_keep_largest=False,
166
+ scale=1):
167
+ det_faces = self.face_detector(self.input_img, scale)
168
+
169
+ if len(det_faces) == 0:
170
+ print('No face detected. Try to increase upsample_num_times.')
171
+ return 0
172
+ else:
173
+ if only_keep_largest:
174
+ print('Detect several faces and only keep the largest.')
175
+ face_areas = []
176
+ for i in range(len(det_faces)):
177
+ face_area = (det_faces[i].rect.right() - det_faces[i].rect.left()) * (
178
+ det_faces[i].rect.bottom() - det_faces[i].rect.top())
179
+ face_areas.append(face_area)
180
+ largest_idx = face_areas.index(max(face_areas))
181
+ self.det_faces = [det_faces[largest_idx]]
182
+ else:
183
+ self.det_faces = det_faces
184
+
185
+ if len(self.det_faces) == 0:
186
+ return 0
187
+
188
+ for face in self.det_faces:
189
+ shape = self.shape_predictor_5(self.input_img, face.rect)
190
+ landmark = np.array([[part.x, part.y] for part in shape.parts()])
191
+ self.all_landmarks_5.append(landmark)
192
+
193
+ return len(self.all_landmarks_5)
194
+
195
+
196
+ def get_face_landmarks_5(self,
197
+ only_keep_largest=False,
198
+ only_center_face=False,
199
+ resize=None,
200
+ blur_ratio=0.01,
201
+ eye_dist_threshold=None):
202
+ if self.det_model == 'dlib':
203
+ return self.get_face_landmarks_5_dlib(only_keep_largest)
204
+
205
+ if resize is None:
206
+ scale = 1
207
+ input_img = self.input_img
208
+ else:
209
+ h, w = self.input_img.shape[0:2]
210
+ scale = resize / min(h, w)
211
+ # scale = max(1, scale) # always scale up; comment this out for HD images, e.g., AIGC faces.
212
+ h, w = int(h * scale), int(w * scale)
213
+ interp = cv2.INTER_AREA if scale < 1 else cv2.INTER_LINEAR
214
+ input_img = cv2.resize(self.input_img, (w, h), interpolation=interp)
215
+
216
+ with torch.no_grad():
217
+ bboxes = self.face_detector.detect_faces(input_img)
218
+
219
+ if bboxes is None or bboxes.shape[0] == 0:
220
+ return 0
221
+ else:
222
+ bboxes = bboxes / scale
223
+
224
+ for bbox in bboxes:
225
+ # remove faces with too small eye distance: side faces or too small faces
226
+ eye_dist = np.linalg.norm([bbox[6] - bbox[8], bbox[7] - bbox[9]])
227
+ if eye_dist_threshold is not None and (eye_dist < eye_dist_threshold):
228
+ continue
229
+
230
+ if self.template_3points:
231
+ landmark = np.array([[bbox[i], bbox[i + 1]] for i in range(5, 11, 2)])
232
+ else:
233
+ landmark = np.array([[bbox[i], bbox[i + 1]] for i in range(5, 15, 2)])
234
+ self.all_landmarks_5.append(landmark)
235
+ self.det_faces.append(bbox[0:5])
236
+
237
+ if len(self.det_faces) == 0:
238
+ return 0
239
+ if only_keep_largest:
240
+ h, w, _ = self.input_img.shape
241
+ self.det_faces, largest_idx = get_largest_face(self.det_faces, h, w)
242
+ self.all_landmarks_5 = [self.all_landmarks_5[largest_idx]]
243
+ elif only_center_face:
244
+ h, w, _ = self.input_img.shape
245
+ self.det_faces, center_idx = get_center_face(self.det_faces, h, w)
246
+ self.all_landmarks_5 = [self.all_landmarks_5[center_idx]]
247
+
248
+ # pad blurry images
249
+ if self.pad_blur:
250
+ self.pad_input_imgs = []
251
+ for landmarks in self.all_landmarks_5:
252
+ # get landmarks
253
+ eye_left = landmarks[0, :]
254
+ eye_right = landmarks[1, :]
255
+ eye_avg = (eye_left + eye_right) * 0.5
256
+ mouth_avg = (landmarks[3, :] + landmarks[4, :]) * 0.5
257
+ eye_to_eye = eye_right - eye_left
258
+ eye_to_mouth = mouth_avg - eye_avg
259
+
260
+ # Get the oriented crop rectangle
261
+ # x: half width of the oriented crop rectangle
262
+ x = eye_to_eye - np.flipud(eye_to_mouth) * [-1, 1]
263
+ # - np.flipud(eye_to_mouth) * [-1, 1]: rotate 90 clockwise
264
+ # norm with the hypotenuse: get the direction
265
+ x /= np.hypot(*x) # get the hypotenuse of a right triangle
266
+ rect_scale = 1.5
267
+ x *= max(np.hypot(*eye_to_eye) * 2.0 * rect_scale, np.hypot(*eye_to_mouth) * 1.8 * rect_scale)
268
+ # y: half height of the oriented crop rectangle
269
+ y = np.flipud(x) * [-1, 1]
270
+
271
+ # c: center
272
+ c = eye_avg + eye_to_mouth * 0.1
273
+ # quad: (left_top, left_bottom, right_bottom, right_top)
274
+ quad = np.stack([c - x - y, c - x + y, c + x + y, c + x - y])
275
+ # qsize: side length of the square
276
+ qsize = np.hypot(*x) * 2
277
+ border = max(int(np.rint(qsize * 0.1)), 3)
278
+
279
+ # get pad
280
+ # pad: (width_left, height_top, width_right, height_bottom)
281
+ pad = (int(np.floor(min(quad[:, 0]))), int(np.floor(min(quad[:, 1]))), int(np.ceil(max(quad[:, 0]))),
282
+ int(np.ceil(max(quad[:, 1]))))
283
+ pad = [
284
+ max(-pad[0] + border, 1),
285
+ max(-pad[1] + border, 1),
286
+ max(pad[2] - self.input_img.shape[0] + border, 1),
287
+ max(pad[3] - self.input_img.shape[1] + border, 1)
288
+ ]
289
+
290
+ if max(pad) > 1:
291
+ # pad image
292
+ pad_img = np.pad(self.input_img, ((pad[1], pad[3]), (pad[0], pad[2]), (0, 0)), 'reflect')
293
+ # modify landmark coords
294
+ landmarks[:, 0] += pad[0]
295
+ landmarks[:, 1] += pad[1]
296
+ # blur pad images
297
+ h, w, _ = pad_img.shape
298
+ y, x, _ = np.ogrid[:h, :w, :1]
299
+ mask = np.maximum(1.0 - np.minimum(np.float32(x) / pad[0],
300
+ np.float32(w - 1 - x) / pad[2]),
301
+ 1.0 - np.minimum(np.float32(y) / pad[1],
302
+ np.float32(h - 1 - y) / pad[3]))
303
+ blur = int(qsize * blur_ratio)
304
+ if blur % 2 == 0:
305
+ blur += 1
306
+ blur_img = cv2.boxFilter(pad_img, 0, ksize=(blur, blur))
307
+ # blur_img = cv2.GaussianBlur(pad_img, (blur, blur), 0)
308
+
309
+ pad_img = pad_img.astype('float32')
310
+ pad_img += (blur_img - pad_img) * np.clip(mask * 3.0 + 1.0, 0.0, 1.0)
311
+ pad_img += (np.median(pad_img, axis=(0, 1)) - pad_img) * np.clip(mask, 0.0, 1.0)
312
+ pad_img = np.clip(pad_img, 0, 255) # float32, [0, 255]
313
+ self.pad_input_imgs.append(pad_img)
314
+ else:
315
+ self.pad_input_imgs.append(np.copy(self.input_img))
316
+
317
+ return len(self.all_landmarks_5)
318
+
319
+ def align_warp_face(self, save_cropped_path=None, border_mode='constant'):
320
+ """Align and warp faces with face template.
321
+ """
322
+ if self.pad_blur:
323
+ assert len(self.pad_input_imgs) == len(
324
+ self.all_landmarks_5), f'Mismatched samples: {len(self.pad_input_imgs)} and {len(self.all_landmarks_5)}'
325
+ for idx, landmark in enumerate(self.all_landmarks_5):
326
+ # use 5 landmarks to get affine matrix
327
+ # use cv2.LMEDS method for the equivalence to skimage transform
328
+ # ref: https://blog.csdn.net/yichxi/article/details/115827338
329
+ affine_matrix = cv2.estimateAffinePartial2D(landmark, self.face_template, method=cv2.LMEDS)[0]
330
+ self.affine_matrices.append(affine_matrix)
331
+ # warp and crop faces
332
+ if border_mode == 'constant':
333
+ border_mode = cv2.BORDER_CONSTANT
334
+ elif border_mode == 'reflect101':
335
+ border_mode = cv2.BORDER_REFLECT101
336
+ elif border_mode == 'reflect':
337
+ border_mode = cv2.BORDER_REFLECT
338
+ if self.pad_blur:
339
+ input_img = self.pad_input_imgs[idx]
340
+ else:
341
+ input_img = self.input_img
342
+ cropped_face = cv2.warpAffine(
343
+ input_img, affine_matrix, self.face_size, borderMode=border_mode, borderValue=(135, 133, 132)) # gray
344
+ self.cropped_faces.append(cropped_face)
345
+ # save the cropped face
346
+ if save_cropped_path is not None:
347
+ path = os.path.splitext(save_cropped_path)[0]
348
+ save_path = f'{path}_{idx:02d}.{self.save_ext}'
349
+ imwrite(cropped_face, save_path)
350
+
351
+ def get_inverse_affine(self, save_inverse_affine_path=None):
352
+ """Get inverse affine matrix."""
353
+ for idx, affine_matrix in enumerate(self.affine_matrices):
354
+ inverse_affine = cv2.invertAffineTransform(affine_matrix)
355
+ inverse_affine *= self.upscale_factor
356
+ self.inverse_affine_matrices.append(inverse_affine)
357
+ # save inverse affine matrices
358
+ if save_inverse_affine_path is not None:
359
+ path, _ = os.path.splitext(save_inverse_affine_path)
360
+ save_path = f'{path}_{idx:02d}.pth'
361
+ torch.save(inverse_affine, save_path)
362
+
363
+
364
+ def add_restored_face(self, restored_face, input_face=None):
365
+ if self.is_gray:
366
+ restored_face = bgr2gray(restored_face) # convert img into grayscale
367
+ if input_face is not None:
368
+ restored_face = adain_npy(restored_face, input_face) # transfer the color
369
+ self.restored_faces.append(restored_face)
370
+
371
+
372
+ def paste_faces_to_input_image(self, save_path=None, upsample_img=None, draw_box=False, face_upsampler=None):
373
+ h, w, _ = self.input_img.shape
374
+ h_up, w_up = int(h * self.upscale_factor), int(w * self.upscale_factor)
375
+
376
+ if upsample_img is None:
377
+ # simply resize the background
378
+ # upsample_img = cv2.resize(self.input_img, (w_up, h_up), interpolation=cv2.INTER_LANCZOS4)
379
+ upsample_img = cv2.resize(self.input_img, (w_up, h_up), interpolation=cv2.INTER_LINEAR)
380
+ else:
381
+ upsample_img = cv2.resize(upsample_img, (w_up, h_up), interpolation=cv2.INTER_LANCZOS4)
382
+
383
+ assert len(self.restored_faces) == len(
384
+ self.inverse_affine_matrices), ('length of restored_faces and affine_matrices are different.')
385
+
386
+ inv_mask_borders = []
387
+ for restored_face, inverse_affine in zip(self.restored_faces, self.inverse_affine_matrices):
388
+ if face_upsampler is not None:
389
+ restored_face = face_upsampler.enhance(restored_face, outscale=self.upscale_factor)[0]
390
+ inverse_affine /= self.upscale_factor
391
+ inverse_affine[:, 2] *= self.upscale_factor
392
+ face_size = (self.face_size[0]*self.upscale_factor, self.face_size[1]*self.upscale_factor)
393
+ else:
394
+ # Add an offset to inverse affine matrix, for more precise back alignment
395
+ if self.upscale_factor > 1:
396
+ extra_offset = 0.5 * self.upscale_factor
397
+ else:
398
+ extra_offset = 0
399
+ inverse_affine[:, 2] += extra_offset
400
+ face_size = self.face_size
401
+ inv_restored = cv2.warpAffine(restored_face, inverse_affine, (w_up, h_up))
402
+
403
+ # if draw_box or not self.use_parse: # use square parse maps
404
+ # mask = np.ones(face_size, dtype=np.float32)
405
+ # inv_mask = cv2.warpAffine(mask, inverse_affine, (w_up, h_up))
406
+ # # remove the black borders
407
+ # inv_mask_erosion = cv2.erode(
408
+ # inv_mask, np.ones((int(2 * self.upscale_factor), int(2 * self.upscale_factor)), np.uint8))
409
+ # pasted_face = inv_mask_erosion[:, :, None] * inv_restored
410
+ # total_face_area = np.sum(inv_mask_erosion) # // 3
411
+ # # add border
412
+ # if draw_box:
413
+ # h, w = face_size
414
+ # mask_border = np.ones((h, w, 3), dtype=np.float32)
415
+ # border = int(1400/np.sqrt(total_face_area))
416
+ # mask_border[border:h-border, border:w-border,:] = 0
417
+ # inv_mask_border = cv2.warpAffine(mask_border, inverse_affine, (w_up, h_up))
418
+ # inv_mask_borders.append(inv_mask_border)
419
+ # if not self.use_parse:
420
+ # # compute the fusion edge based on the area of face
421
+ # w_edge = int(total_face_area**0.5) // 20
422
+ # erosion_radius = w_edge * 2
423
+ # inv_mask_center = cv2.erode(inv_mask_erosion, np.ones((erosion_radius, erosion_radius), np.uint8))
424
+ # blur_size = w_edge * 2
425
+ # inv_soft_mask = cv2.GaussianBlur(inv_mask_center, (blur_size + 1, blur_size + 1), 0)
426
+ # if len(upsample_img.shape) == 2: # upsample_img is gray image
427
+ # upsample_img = upsample_img[:, :, None]
428
+ # inv_soft_mask = inv_soft_mask[:, :, None]
429
+
430
+ # always use square mask
431
+ mask = np.ones(face_size, dtype=np.float32)
432
+ inv_mask = cv2.warpAffine(mask, inverse_affine, (w_up, h_up))
433
+ # remove the black borders
434
+ inv_mask_erosion = cv2.erode(
435
+ inv_mask, np.ones((int(2 * self.upscale_factor), int(2 * self.upscale_factor)), np.uint8))
436
+ pasted_face = inv_mask_erosion[:, :, None] * inv_restored
437
+ total_face_area = np.sum(inv_mask_erosion) # // 3
438
+ # add border
439
+ if draw_box:
440
+ h, w = face_size
441
+ mask_border = np.ones((h, w, 3), dtype=np.float32)
442
+ border = int(1400/np.sqrt(total_face_area))
443
+ mask_border[border:h-border, border:w-border,:] = 0
444
+ inv_mask_border = cv2.warpAffine(mask_border, inverse_affine, (w_up, h_up))
445
+ inv_mask_borders.append(inv_mask_border)
446
+ # compute the fusion edge based on the area of face
447
+ w_edge = int(total_face_area**0.5) // 20
448
+ erosion_radius = w_edge * 2
449
+ inv_mask_center = cv2.erode(inv_mask_erosion, np.ones((erosion_radius, erosion_radius), np.uint8))
450
+ blur_size = w_edge * 2
451
+ inv_soft_mask = cv2.GaussianBlur(inv_mask_center, (blur_size + 1, blur_size + 1), 0)
452
+ if len(upsample_img.shape) == 2: # upsample_img is gray image
453
+ upsample_img = upsample_img[:, :, None]
454
+ inv_soft_mask = inv_soft_mask[:, :, None]
455
+
456
+ # parse mask
457
+ if self.use_parse:
458
+ # inference
459
+ face_input = cv2.resize(restored_face, (512, 512), interpolation=cv2.INTER_LINEAR)
460
+ face_input = img2tensor(face_input.astype('float32') / 255., bgr2rgb=True, float32=True)
461
+ normalize(face_input, (0.5, 0.5, 0.5), (0.5, 0.5, 0.5), inplace=True)
462
+ face_input = torch.unsqueeze(face_input, 0).to(self.device)
463
+ with torch.no_grad():
464
+ out = self.face_parse(face_input)[0]
465
+ out = out.argmax(dim=1).squeeze().cpu().numpy()
466
+
467
+ parse_mask = np.zeros(out.shape)
468
+ MASK_COLORMAP = [0, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 0, 255, 0, 0, 0]
469
+ for idx, color in enumerate(MASK_COLORMAP):
470
+ parse_mask[out == idx] = color
471
+ # blur the mask
472
+ parse_mask = cv2.GaussianBlur(parse_mask, (101, 101), 11)
473
+ parse_mask = cv2.GaussianBlur(parse_mask, (101, 101), 11)
474
+ # remove the black borders
475
+ thres = 10
476
+ parse_mask[:thres, :] = 0
477
+ parse_mask[-thres:, :] = 0
478
+ parse_mask[:, :thres] = 0
479
+ parse_mask[:, -thres:] = 0
480
+ parse_mask = parse_mask / 255.
481
+
482
+ parse_mask = cv2.resize(parse_mask, face_size)
483
+ parse_mask = cv2.warpAffine(parse_mask, inverse_affine, (w_up, h_up), flags=3)
484
+ inv_soft_parse_mask = parse_mask[:, :, None]
485
+ # pasted_face = inv_restored
486
+ fuse_mask = (inv_soft_parse_mask<inv_soft_mask).astype('int')
487
+ inv_soft_mask = inv_soft_parse_mask*fuse_mask + inv_soft_mask*(1-fuse_mask)
488
+
489
+ if len(upsample_img.shape) == 3 and upsample_img.shape[2] == 4: # alpha channel
490
+ alpha = upsample_img[:, :, 3:]
491
+ upsample_img = inv_soft_mask * pasted_face + (1 - inv_soft_mask) * upsample_img[:, :, 0:3]
492
+ upsample_img = np.concatenate((upsample_img, alpha), axis=2)
493
+ else:
494
+ upsample_img = inv_soft_mask * pasted_face + (1 - inv_soft_mask) * upsample_img
495
+
496
+ if np.max(upsample_img) > 256: # 16-bit image
497
+ upsample_img = upsample_img.astype(np.uint16)
498
+ else:
499
+ upsample_img = upsample_img.astype(np.uint8)
500
+
501
+ # draw bounding box
502
+ if draw_box:
503
+ # upsample_input_img = cv2.resize(input_img, (w_up, h_up))
504
+ img_color = np.ones([*upsample_img.shape], dtype=np.float32)
505
+ img_color[:,:,0] = 0
506
+ img_color[:,:,1] = 255
507
+ img_color[:,:,2] = 0
508
+ for inv_mask_border in inv_mask_borders:
509
+ upsample_img = inv_mask_border * img_color + (1 - inv_mask_border) * upsample_img
510
+ # upsample_input_img = inv_mask_border * img_color + (1 - inv_mask_border) * upsample_input_img
511
+
512
+ if save_path is not None:
513
+ path = os.path.splitext(save_path)[0]
514
+ save_path = f'{path}.{self.save_ext}'
515
+ imwrite(upsample_img, save_path)
516
+ return upsample_img
517
+
518
+ def clean_all(self):
519
+ self.all_landmarks_5 = []
520
+ self.restored_faces = []
521
+ self.affine_matrices = []
522
+ self.cropped_faces = []
523
+ self.inverse_affine_matrices = []
524
+ self.det_faces = []
525
+ self.pad_input_imgs = []
CodeFormer/facelib/utils/face_utils.py ADDED
@@ -0,0 +1,248 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import cv2
2
+ import numpy as np
3
+ import torch
4
+
5
+
6
+ def compute_increased_bbox(bbox, increase_area, preserve_aspect=True):
7
+ left, top, right, bot = bbox
8
+ width = right - left
9
+ height = bot - top
10
+
11
+ if preserve_aspect:
12
+ width_increase = max(increase_area, ((1 + 2 * increase_area) * height - width) / (2 * width))
13
+ height_increase = max(increase_area, ((1 + 2 * increase_area) * width - height) / (2 * height))
14
+ else:
15
+ width_increase = height_increase = increase_area
16
+ left = int(left - width_increase * width)
17
+ top = int(top - height_increase * height)
18
+ right = int(right + width_increase * width)
19
+ bot = int(bot + height_increase * height)
20
+ return (left, top, right, bot)
21
+
22
+
23
+ def get_valid_bboxes(bboxes, h, w):
24
+ left = max(bboxes[0], 0)
25
+ top = max(bboxes[1], 0)
26
+ right = min(bboxes[2], w)
27
+ bottom = min(bboxes[3], h)
28
+ return (left, top, right, bottom)
29
+
30
+
31
+ def align_crop_face_landmarks(img,
32
+ landmarks,
33
+ output_size,
34
+ transform_size=None,
35
+ enable_padding=True,
36
+ return_inverse_affine=False,
37
+ shrink_ratio=(1, 1)):
38
+ """Align and crop face with landmarks.
39
+
40
+ The output_size and transform_size are based on width. The height is
41
+ adjusted based on shrink_ratio_h/shring_ration_w.
42
+
43
+ Modified from:
44
+ https://github.com/NVlabs/ffhq-dataset/blob/master/download_ffhq.py
45
+
46
+ Args:
47
+ img (Numpy array): Input image.
48
+ landmarks (Numpy array): 5 or 68 or 98 landmarks.
49
+ output_size (int): Output face size.
50
+ transform_size (ing): Transform size. Usually the four time of
51
+ output_size.
52
+ enable_padding (float): Default: True.
53
+ shrink_ratio (float | tuple[float] | list[float]): Shring the whole
54
+ face for height and width (crop larger area). Default: (1, 1).
55
+
56
+ Returns:
57
+ (Numpy array): Cropped face.
58
+ """
59
+ lm_type = 'retinaface_5' # Options: dlib_5, retinaface_5
60
+
61
+ if isinstance(shrink_ratio, (float, int)):
62
+ shrink_ratio = (shrink_ratio, shrink_ratio)
63
+ if transform_size is None:
64
+ transform_size = output_size * 4
65
+
66
+ # Parse landmarks
67
+ lm = np.array(landmarks)
68
+ if lm.shape[0] == 5 and lm_type == 'retinaface_5':
69
+ eye_left = lm[0]
70
+ eye_right = lm[1]
71
+ mouth_avg = (lm[3] + lm[4]) * 0.5
72
+ elif lm.shape[0] == 5 and lm_type == 'dlib_5':
73
+ lm_eye_left = lm[2:4]
74
+ lm_eye_right = lm[0:2]
75
+ eye_left = np.mean(lm_eye_left, axis=0)
76
+ eye_right = np.mean(lm_eye_right, axis=0)
77
+ mouth_avg = lm[4]
78
+ elif lm.shape[0] == 68:
79
+ lm_eye_left = lm[36:42]
80
+ lm_eye_right = lm[42:48]
81
+ eye_left = np.mean(lm_eye_left, axis=0)
82
+ eye_right = np.mean(lm_eye_right, axis=0)
83
+ mouth_avg = (lm[48] + lm[54]) * 0.5
84
+ elif lm.shape[0] == 98:
85
+ lm_eye_left = lm[60:68]
86
+ lm_eye_right = lm[68:76]
87
+ eye_left = np.mean(lm_eye_left, axis=0)
88
+ eye_right = np.mean(lm_eye_right, axis=0)
89
+ mouth_avg = (lm[76] + lm[82]) * 0.5
90
+
91
+ eye_avg = (eye_left + eye_right) * 0.5
92
+ eye_to_eye = eye_right - eye_left
93
+ eye_to_mouth = mouth_avg - eye_avg
94
+
95
+ # Get the oriented crop rectangle
96
+ # x: half width of the oriented crop rectangle
97
+ x = eye_to_eye - np.flipud(eye_to_mouth) * [-1, 1]
98
+ # - np.flipud(eye_to_mouth) * [-1, 1]: rotate 90 clockwise
99
+ # norm with the hypotenuse: get the direction
100
+ x /= np.hypot(*x) # get the hypotenuse of a right triangle
101
+ rect_scale = 1 # TODO: you can edit it to get larger rect
102
+ x *= max(np.hypot(*eye_to_eye) * 2.0 * rect_scale, np.hypot(*eye_to_mouth) * 1.8 * rect_scale)
103
+ # y: half height of the oriented crop rectangle
104
+ y = np.flipud(x) * [-1, 1]
105
+
106
+ x *= shrink_ratio[1] # width
107
+ y *= shrink_ratio[0] # height
108
+
109
+ # c: center
110
+ c = eye_avg + eye_to_mouth * 0.1
111
+ # quad: (left_top, left_bottom, right_bottom, right_top)
112
+ quad = np.stack([c - x - y, c - x + y, c + x + y, c + x - y])
113
+ # qsize: side length of the square
114
+ qsize = np.hypot(*x) * 2
115
+
116
+ quad_ori = np.copy(quad)
117
+ # Shrink, for large face
118
+ # TODO: do we really need shrink
119
+ shrink = int(np.floor(qsize / output_size * 0.5))
120
+ if shrink > 1:
121
+ h, w = img.shape[0:2]
122
+ rsize = (int(np.rint(float(w) / shrink)), int(np.rint(float(h) / shrink)))
123
+ img = cv2.resize(img, rsize, interpolation=cv2.INTER_AREA)
124
+ quad /= shrink
125
+ qsize /= shrink
126
+
127
+ # Crop
128
+ h, w = img.shape[0:2]
129
+ border = max(int(np.rint(qsize * 0.1)), 3)
130
+ crop = (int(np.floor(min(quad[:, 0]))), int(np.floor(min(quad[:, 1]))), int(np.ceil(max(quad[:, 0]))),
131
+ int(np.ceil(max(quad[:, 1]))))
132
+ crop = (max(crop[0] - border, 0), max(crop[1] - border, 0), min(crop[2] + border, w), min(crop[3] + border, h))
133
+ if crop[2] - crop[0] < w or crop[3] - crop[1] < h:
134
+ img = img[crop[1]:crop[3], crop[0]:crop[2], :]
135
+ quad -= crop[0:2]
136
+
137
+ # Pad
138
+ # pad: (width_left, height_top, width_right, height_bottom)
139
+ h, w = img.shape[0:2]
140
+ pad = (int(np.floor(min(quad[:, 0]))), int(np.floor(min(quad[:, 1]))), int(np.ceil(max(quad[:, 0]))),
141
+ int(np.ceil(max(quad[:, 1]))))
142
+ pad = (max(-pad[0] + border, 0), max(-pad[1] + border, 0), max(pad[2] - w + border, 0), max(pad[3] - h + border, 0))
143
+ if enable_padding and max(pad) > border - 4:
144
+ pad = np.maximum(pad, int(np.rint(qsize * 0.3)))
145
+ img = np.pad(img, ((pad[1], pad[3]), (pad[0], pad[2]), (0, 0)), 'reflect')
146
+ h, w = img.shape[0:2]
147
+ y, x, _ = np.ogrid[:h, :w, :1]
148
+ mask = np.maximum(1.0 - np.minimum(np.float32(x) / pad[0],
149
+ np.float32(w - 1 - x) / pad[2]),
150
+ 1.0 - np.minimum(np.float32(y) / pad[1],
151
+ np.float32(h - 1 - y) / pad[3]))
152
+ blur = int(qsize * 0.02)
153
+ if blur % 2 == 0:
154
+ blur += 1
155
+ blur_img = cv2.boxFilter(img, 0, ksize=(blur, blur))
156
+
157
+ img = img.astype('float32')
158
+ img += (blur_img - img) * np.clip(mask * 3.0 + 1.0, 0.0, 1.0)
159
+ img += (np.median(img, axis=(0, 1)) - img) * np.clip(mask, 0.0, 1.0)
160
+ img = np.clip(img, 0, 255) # float32, [0, 255]
161
+ quad += pad[:2]
162
+
163
+ # Transform use cv2
164
+ h_ratio = shrink_ratio[0] / shrink_ratio[1]
165
+ dst_h, dst_w = int(transform_size * h_ratio), transform_size
166
+ template = np.array([[0, 0], [0, dst_h], [dst_w, dst_h], [dst_w, 0]])
167
+ # use cv2.LMEDS method for the equivalence to skimage transform
168
+ # ref: https://blog.csdn.net/yichxi/article/details/115827338
169
+ affine_matrix = cv2.estimateAffinePartial2D(quad, template, method=cv2.LMEDS)[0]
170
+ cropped_face = cv2.warpAffine(
171
+ img, affine_matrix, (dst_w, dst_h), borderMode=cv2.BORDER_CONSTANT, borderValue=(135, 133, 132)) # gray
172
+
173
+ if output_size < transform_size:
174
+ cropped_face = cv2.resize(
175
+ cropped_face, (output_size, int(output_size * h_ratio)), interpolation=cv2.INTER_LINEAR)
176
+
177
+ if return_inverse_affine:
178
+ dst_h, dst_w = int(output_size * h_ratio), output_size
179
+ template = np.array([[0, 0], [0, dst_h], [dst_w, dst_h], [dst_w, 0]])
180
+ # use cv2.LMEDS method for the equivalence to skimage transform
181
+ # ref: https://blog.csdn.net/yichxi/article/details/115827338
182
+ affine_matrix = cv2.estimateAffinePartial2D(
183
+ quad_ori, np.array([[0, 0], [0, output_size], [dst_w, dst_h], [dst_w, 0]]), method=cv2.LMEDS)[0]
184
+ inverse_affine = cv2.invertAffineTransform(affine_matrix)
185
+ else:
186
+ inverse_affine = None
187
+ return cropped_face, inverse_affine
188
+
189
+
190
+ def paste_face_back(img, face, inverse_affine):
191
+ h, w = img.shape[0:2]
192
+ face_h, face_w = face.shape[0:2]
193
+ inv_restored = cv2.warpAffine(face, inverse_affine, (w, h))
194
+ mask = np.ones((face_h, face_w, 3), dtype=np.float32)
195
+ inv_mask = cv2.warpAffine(mask, inverse_affine, (w, h))
196
+ # remove the black borders
197
+ inv_mask_erosion = cv2.erode(inv_mask, np.ones((2, 2), np.uint8))
198
+ inv_restored_remove_border = inv_mask_erosion * inv_restored
199
+ total_face_area = np.sum(inv_mask_erosion) // 3
200
+ # compute the fusion edge based on the area of face
201
+ w_edge = int(total_face_area**0.5) // 20
202
+ erosion_radius = w_edge * 2
203
+ inv_mask_center = cv2.erode(inv_mask_erosion, np.ones((erosion_radius, erosion_radius), np.uint8))
204
+ blur_size = w_edge * 2
205
+ inv_soft_mask = cv2.GaussianBlur(inv_mask_center, (blur_size + 1, blur_size + 1), 0)
206
+ img = inv_soft_mask * inv_restored_remove_border + (1 - inv_soft_mask) * img
207
+ # float32, [0, 255]
208
+ return img
209
+
210
+
211
+ if __name__ == '__main__':
212
+ import os
213
+
214
+ from facelib.detection import init_detection_model
215
+ from facelib.utils.face_restoration_helper import get_largest_face
216
+
217
+ img_path = '/home/wxt/datasets/ffhq/ffhq_wild/00009.png'
218
+ img_name = os.splitext(os.path.basename(img_path))[0]
219
+
220
+ # initialize model
221
+ det_net = init_detection_model('retinaface_resnet50', half=False)
222
+ img_ori = cv2.imread(img_path)
223
+ h, w = img_ori.shape[0:2]
224
+ # if larger than 800, scale it
225
+ scale = max(h / 800, w / 800)
226
+ if scale > 1:
227
+ img = cv2.resize(img_ori, (int(w / scale), int(h / scale)), interpolation=cv2.INTER_LINEAR)
228
+
229
+ with torch.no_grad():
230
+ bboxes = det_net.detect_faces(img, 0.97)
231
+ if scale > 1:
232
+ bboxes *= scale # the score is incorrect
233
+ bboxes = get_largest_face(bboxes, h, w)[0]
234
+
235
+ landmarks = np.array([[bboxes[i], bboxes[i + 1]] for i in range(5, 15, 2)])
236
+
237
+ cropped_face, inverse_affine = align_crop_face_landmarks(
238
+ img_ori,
239
+ landmarks,
240
+ output_size=512,
241
+ transform_size=None,
242
+ enable_padding=True,
243
+ return_inverse_affine=True,
244
+ shrink_ratio=(1, 1))
245
+
246
+ cv2.imwrite(f'tmp/{img_name}_cropeed_face.png', cropped_face)
247
+ img = paste_face_back(img_ori, cropped_face, inverse_affine)
248
+ cv2.imwrite(f'tmp/{img_name}_back.png', img)
CodeFormer/facelib/utils/misc.py ADDED
@@ -0,0 +1,202 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import cv2
2
+ import os
3
+ import os.path as osp
4
+ import numpy as np
5
+ from PIL import Image
6
+ import torch
7
+ from torch.hub import download_url_to_file, get_dir
8
+ from urllib.parse import urlparse
9
+ # from basicsr.utils.download_util import download_file_from_google_drive
10
+
11
+ ROOT_DIR = os.path.dirname(os.path.dirname(os.path.dirname(os.path.abspath(__file__))))
12
+
13
+
14
+ def download_pretrained_models(file_ids, save_path_root):
15
+ import gdown
16
+
17
+ os.makedirs(save_path_root, exist_ok=True)
18
+
19
+ for file_name, file_id in file_ids.items():
20
+ file_url = 'https://drive.google.com/uc?id='+file_id
21
+ save_path = osp.abspath(osp.join(save_path_root, file_name))
22
+ if osp.exists(save_path):
23
+ user_response = input(f'{file_name} already exist. Do you want to cover it? Y/N\n')
24
+ if user_response.lower() == 'y':
25
+ print(f'Covering {file_name} to {save_path}')
26
+ gdown.download(file_url, save_path, quiet=False)
27
+ # download_file_from_google_drive(file_id, save_path)
28
+ elif user_response.lower() == 'n':
29
+ print(f'Skipping {file_name}')
30
+ else:
31
+ raise ValueError('Wrong input. Only accepts Y/N.')
32
+ else:
33
+ print(f'Downloading {file_name} to {save_path}')
34
+ gdown.download(file_url, save_path, quiet=False)
35
+ # download_file_from_google_drive(file_id, save_path)
36
+
37
+
38
+ def imwrite(img, file_path, params=None, auto_mkdir=True):
39
+ """Write image to file.
40
+
41
+ Args:
42
+ img (ndarray): Image array to be written.
43
+ file_path (str): Image file path.
44
+ params (None or list): Same as opencv's :func:`imwrite` interface.
45
+ auto_mkdir (bool): If the parent folder of `file_path` does not exist,
46
+ whether to create it automatically.
47
+
48
+ Returns:
49
+ bool: Successful or not.
50
+ """
51
+ if auto_mkdir:
52
+ dir_name = os.path.abspath(os.path.dirname(file_path))
53
+ os.makedirs(dir_name, exist_ok=True)
54
+ return cv2.imwrite(file_path, img, params)
55
+
56
+
57
+ def img2tensor(imgs, bgr2rgb=True, float32=True):
58
+ """Numpy array to tensor.
59
+
60
+ Args:
61
+ imgs (list[ndarray] | ndarray): Input images.
62
+ bgr2rgb (bool): Whether to change bgr to rgb.
63
+ float32 (bool): Whether to change to float32.
64
+
65
+ Returns:
66
+ list[tensor] | tensor: Tensor images. If returned results only have
67
+ one element, just return tensor.
68
+ """
69
+
70
+ def _totensor(img, bgr2rgb, float32):
71
+ if img.shape[2] == 3 and bgr2rgb:
72
+ if img.dtype == 'float64':
73
+ img = img.astype('float32')
74
+ img = cv2.cvtColor(img, cv2.COLOR_BGR2RGB)
75
+ img = torch.from_numpy(img.transpose(2, 0, 1))
76
+ if float32:
77
+ img = img.float()
78
+ return img
79
+
80
+ if isinstance(imgs, list):
81
+ return [_totensor(img, bgr2rgb, float32) for img in imgs]
82
+ else:
83
+ return _totensor(imgs, bgr2rgb, float32)
84
+
85
+
86
+ def load_file_from_url(url, model_dir=None, progress=True, file_name=None):
87
+ """Ref:https://github.com/1adrianb/face-alignment/blob/master/face_alignment/utils.py
88
+ """
89
+ if model_dir is None:
90
+ hub_dir = get_dir()
91
+ model_dir = os.path.join(hub_dir, 'checkpoints')
92
+
93
+ os.makedirs(os.path.join(ROOT_DIR, model_dir), exist_ok=True)
94
+
95
+ parts = urlparse(url)
96
+ filename = os.path.basename(parts.path)
97
+ if file_name is not None:
98
+ filename = file_name
99
+ cached_file = os.path.abspath(os.path.join(ROOT_DIR, model_dir, filename))
100
+ if not os.path.exists(cached_file):
101
+ print(f'Downloading: "{url}" to {cached_file}\n')
102
+ download_url_to_file(url, cached_file, hash_prefix=None, progress=progress)
103
+ return cached_file
104
+
105
+
106
+ def scandir(dir_path, suffix=None, recursive=False, full_path=False):
107
+ """Scan a directory to find the interested files.
108
+ Args:
109
+ dir_path (str): Path of the directory.
110
+ suffix (str | tuple(str), optional): File suffix that we are
111
+ interested in. Default: None.
112
+ recursive (bool, optional): If set to True, recursively scan the
113
+ directory. Default: False.
114
+ full_path (bool, optional): If set to True, include the dir_path.
115
+ Default: False.
116
+ Returns:
117
+ A generator for all the interested files with relative paths.
118
+ """
119
+
120
+ if (suffix is not None) and not isinstance(suffix, (str, tuple)):
121
+ raise TypeError('"suffix" must be a string or tuple of strings')
122
+
123
+ root = dir_path
124
+
125
+ def _scandir(dir_path, suffix, recursive):
126
+ for entry in os.scandir(dir_path):
127
+ if not entry.name.startswith('.') and entry.is_file():
128
+ if full_path:
129
+ return_path = entry.path
130
+ else:
131
+ return_path = osp.relpath(entry.path, root)
132
+
133
+ if suffix is None:
134
+ yield return_path
135
+ elif return_path.endswith(suffix):
136
+ yield return_path
137
+ else:
138
+ if recursive:
139
+ yield from _scandir(entry.path, suffix=suffix, recursive=recursive)
140
+ else:
141
+ continue
142
+
143
+ return _scandir(dir_path, suffix=suffix, recursive=recursive)
144
+
145
+
146
+ def is_gray(img, threshold=10):
147
+ img = Image.fromarray(img)
148
+ if len(img.getbands()) == 1:
149
+ return True
150
+ img1 = np.asarray(img.getchannel(channel=0), dtype=np.int16)
151
+ img2 = np.asarray(img.getchannel(channel=1), dtype=np.int16)
152
+ img3 = np.asarray(img.getchannel(channel=2), dtype=np.int16)
153
+ diff1 = (img1 - img2).var()
154
+ diff2 = (img2 - img3).var()
155
+ diff3 = (img3 - img1).var()
156
+ diff_sum = (diff1 + diff2 + diff3) / 3.0
157
+ if diff_sum <= threshold:
158
+ return True
159
+ else:
160
+ return False
161
+
162
+ def rgb2gray(img, out_channel=3):
163
+ r, g, b = img[:,:,0], img[:,:,1], img[:,:,2]
164
+ gray = 0.2989 * r + 0.5870 * g + 0.1140 * b
165
+ if out_channel == 3:
166
+ gray = gray[:,:,np.newaxis].repeat(3, axis=2)
167
+ return gray
168
+
169
+ def bgr2gray(img, out_channel=3):
170
+ b, g, r = img[:,:,0], img[:,:,1], img[:,:,2]
171
+ gray = 0.2989 * r + 0.5870 * g + 0.1140 * b
172
+ if out_channel == 3:
173
+ gray = gray[:,:,np.newaxis].repeat(3, axis=2)
174
+ return gray
175
+
176
+
177
+ def calc_mean_std(feat, eps=1e-5):
178
+ """
179
+ Args:
180
+ feat (numpy): 3D [w h c]s
181
+ """
182
+ size = feat.shape
183
+ assert len(size) == 3, 'The input feature should be 3D tensor.'
184
+ c = size[2]
185
+ feat_var = feat.reshape(-1, c).var(axis=0) + eps
186
+ feat_std = np.sqrt(feat_var).reshape(1, 1, c)
187
+ feat_mean = feat.reshape(-1, c).mean(axis=0).reshape(1, 1, c)
188
+ return feat_mean, feat_std
189
+
190
+
191
+ def adain_npy(content_feat, style_feat):
192
+ """Adaptive instance normalization for numpy.
193
+
194
+ Args:
195
+ content_feat (numpy): The input feature.
196
+ style_feat (numpy): The reference feature.
197
+ """
198
+ size = content_feat.shape
199
+ style_mean, style_std = calc_mean_std(style_feat)
200
+ content_mean, content_std = calc_mean_std(content_feat)
201
+ normalized_feat = (content_feat - np.broadcast_to(content_mean, size)) / np.broadcast_to(content_std, size)
202
+ return normalized_feat * np.broadcast_to(style_std, size) + np.broadcast_to(style_mean, size)
CodeFormer/inference_codeformer.py ADDED
@@ -0,0 +1,281 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import os
2
+ import cv2
3
+ import argparse
4
+ import glob
5
+ import torch
6
+ from torchvision.transforms.functional import normalize
7
+ from basicsr.utils import imwrite, img2tensor, tensor2img
8
+ from basicsr.utils.download_util import load_file_from_url
9
+ import torch
10
+
11
+ def gpu_is_available():
12
+ return torch.cuda.is_available()
13
+
14
+ def get_device():
15
+ return torch.device('cuda' if torch.cuda.is_available() else 'cpu')
16
+
17
+ from facelib.utils.face_restoration_helper import FaceRestoreHelper
18
+ from facelib.utils.misc import is_gray
19
+
20
+ from basicsr.utils.registry import ARCH_REGISTRY
21
+
22
+ pretrain_model_url = {
23
+ 'restoration': 'https://github.com/sczhou/CodeFormer/releases/download/v0.1.0/codeformer.pth',
24
+ }
25
+
26
+ def set_realesrgan():
27
+ from basicsr.archs.rrdbnet_arch import RRDBNet
28
+ from basicsr.utils.realesrgan_utils import RealESRGANer
29
+
30
+ use_half = False
31
+ if torch.cuda.is_available(): # set False in CPU/MPS mode
32
+ no_half_gpu_list = ['1650', '1660'] # set False for GPUs that don't support f16
33
+ if not True in [gpu in torch.cuda.get_device_name(0) for gpu in no_half_gpu_list]:
34
+ use_half = True
35
+
36
+ model = RRDBNet(
37
+ num_in_ch=3,
38
+ num_out_ch=3,
39
+ num_feat=64,
40
+ num_block=23,
41
+ num_grow_ch=32,
42
+ scale=2,
43
+ )
44
+ upsampler = RealESRGANer(
45
+ scale=2,
46
+ model_path="https://github.com/sczhou/CodeFormer/releases/download/v0.1.0/RealESRGAN_x2plus.pth",
47
+ model=model,
48
+ tile=args.bg_tile,
49
+ tile_pad=40,
50
+ pre_pad=0,
51
+ half=use_half
52
+ )
53
+
54
+ if not gpu_is_available(): # CPU
55
+ import warnings
56
+ warnings.warn('Running on CPU now! Make sure your PyTorch version matches your CUDA.'
57
+ 'The unoptimized RealESRGAN is slow on CPU. '
58
+ 'If you want to disable it, please remove `--bg_upsampler` and `--face_upsample` in command.',
59
+ category=RuntimeWarning)
60
+ return upsampler
61
+
62
+ if __name__ == '__main__':
63
+ # device = torch.device('cuda' if torch.cuda.is_available() else 'cpu')
64
+ device = get_device()
65
+ parser = argparse.ArgumentParser()
66
+
67
+ parser.add_argument('-i', '--input_path', type=str, default='./inputs/whole_imgs',
68
+ help='Input image, video or folder. Default: inputs/whole_imgs')
69
+ parser.add_argument('-o', '--output_path', type=str, default=None,
70
+ help='Output folder. Default: results/<input_name>_<w>')
71
+ parser.add_argument('-w', '--fidelity_weight', type=float, default=0.5,
72
+ help='Balance the quality and fidelity. Default: 0.5')
73
+ parser.add_argument('-s', '--upscale', type=int, default=2,
74
+ help='The final upsampling scale of the image. Default: 2')
75
+ parser.add_argument('--has_aligned', action='store_true', help='Input are cropped and aligned faces. Default: False')
76
+ parser.add_argument('--only_center_face', action='store_true', help='Only restore the center face. Default: False')
77
+ parser.add_argument('--draw_box', action='store_true', help='Draw the bounding box for the detected faces. Default: False')
78
+ # large det_model: 'YOLOv5l', 'retinaface_resnet50'
79
+ # small det_model: 'YOLOv5n', 'retinaface_mobile0.25'
80
+ parser.add_argument('--detection_model', type=str, default='retinaface_resnet50',
81
+ help='Face detector. Optional: retinaface_resnet50, retinaface_mobile0.25, YOLOv5l, YOLOv5n, dlib. \
82
+ Default: retinaface_resnet50')
83
+ parser.add_argument('--bg_upsampler', type=str, default='None', help='Background upsampler. Optional: realesrgan')
84
+ parser.add_argument('--face_upsample', action='store_true', help='Face upsampler after enhancement. Default: False')
85
+ parser.add_argument('--bg_tile', type=int, default=400, help='Tile size for background sampler. Default: 400')
86
+ parser.add_argument('--suffix', type=str, default=None, help='Suffix of the restored faces. Default: None')
87
+ parser.add_argument('--save_video_fps', type=float, default=None, help='Frame rate for saving video. Default: None')
88
+
89
+ args = parser.parse_args()
90
+
91
+ # ------------------------ input & output ------------------------
92
+ w = args.fidelity_weight
93
+ input_video = False
94
+ if args.input_path.endswith(('jpg', 'jpeg', 'png', 'JPG', 'JPEG', 'PNG')): # input single img path
95
+ input_img_list = [args.input_path]
96
+ result_root = f'results/test_img_{w}'
97
+ elif args.input_path.endswith(('mp4', 'mov', 'avi', 'MP4', 'MOV', 'AVI')): # input video path
98
+ from basicsr.utils.video_util import VideoReader, VideoWriter
99
+ input_img_list = []
100
+ vidreader = VideoReader(args.input_path)
101
+ image = vidreader.get_frame()
102
+ while image is not None:
103
+ input_img_list.append(image)
104
+ image = vidreader.get_frame()
105
+ audio = vidreader.get_audio()
106
+ fps = vidreader.get_fps() if args.save_video_fps is None else args.save_video_fps
107
+ video_name = os.path.basename(args.input_path)[:-4]
108
+ result_root = f'results/{video_name}_{w}'
109
+ input_video = True
110
+ vidreader.close()
111
+ else: # input img folder
112
+ if args.input_path.endswith('/'): # solve when path ends with /
113
+ args.input_path = args.input_path[:-1]
114
+ # scan all the jpg and png images
115
+ input_img_list = sorted(glob.glob(os.path.join(args.input_path, '*.[jpJP][pnPN]*[gG]')))
116
+ result_root = f'results/{os.path.basename(args.input_path)}_{w}'
117
+
118
+ if not args.output_path is None: # set output path
119
+ result_root = args.output_path
120
+
121
+ test_img_num = len(input_img_list)
122
+ if test_img_num == 0:
123
+ raise FileNotFoundError('No input image/video is found...\n'
124
+ '\tNote that --input_path for video should end with .mp4|.mov|.avi')
125
+
126
+ # ------------------ set up background upsampler ------------------
127
+ if args.bg_upsampler == 'realesrgan':
128
+ bg_upsampler = set_realesrgan()
129
+ else:
130
+ bg_upsampler = None
131
+
132
+ # ------------------ set up face upsampler ------------------
133
+ if args.face_upsample:
134
+ if bg_upsampler is not None:
135
+ face_upsampler = bg_upsampler
136
+ else:
137
+ face_upsampler = set_realesrgan()
138
+ else:
139
+ face_upsampler = None
140
+
141
+ # ------------------ set up CodeFormer restorer -------------------
142
+ net = ARCH_REGISTRY.get('CodeFormer')(dim_embd=512, codebook_size=1024, n_head=8, n_layers=9,
143
+ connect_list=['32', '64', '128', '256']).to(device)
144
+
145
+ # ckpt_path = 'weights/CodeFormer/codeformer.pth'
146
+ ckpt_path = load_file_from_url(url=pretrain_model_url['restoration'],
147
+ model_dir='weights/CodeFormer', progress=True, file_name=None)
148
+ checkpoint = torch.load(ckpt_path)['params_ema']
149
+ net.load_state_dict(checkpoint)
150
+ net.eval()
151
+
152
+ # ------------------ set up FaceRestoreHelper -------------------
153
+ # large det_model: 'YOLOv5l', 'retinaface_resnet50'
154
+ # small det_model: 'YOLOv5n', 'retinaface_mobile0.25'
155
+ if not args.has_aligned:
156
+ print(f'Face detection model: {args.detection_model}')
157
+ if bg_upsampler is not None:
158
+ print(f'Background upsampling: True, Face upsampling: {args.face_upsample}')
159
+ else:
160
+ print(f'Background upsampling: False, Face upsampling: {args.face_upsample}')
161
+
162
+ face_helper = FaceRestoreHelper(
163
+ args.upscale,
164
+ face_size=512,
165
+ crop_ratio=(1, 1),
166
+ det_model = args.detection_model,
167
+ save_ext='png',
168
+ use_parse=True,
169
+ device=device)
170
+
171
+ # -------------------- start to processing ---------------------
172
+ for i, img_path in enumerate(input_img_list):
173
+ # clean all the intermediate results to process the next image
174
+ face_helper.clean_all()
175
+
176
+ if isinstance(img_path, str):
177
+ img_name = os.path.basename(img_path)
178
+ basename, ext = os.path.splitext(img_name)
179
+ print(f'[{i+1}/{test_img_num}] Processing: {img_name}')
180
+ img = cv2.imread(img_path, cv2.IMREAD_COLOR)
181
+ else: # for video processing
182
+ basename = str(i).zfill(6)
183
+ img_name = f'{video_name}_{basename}' if input_video else basename
184
+ print(f'[{i+1}/{test_img_num}] Processing: {img_name}')
185
+ img = img_path
186
+
187
+ if args.has_aligned:
188
+ # the input faces are already cropped and aligned
189
+ img = cv2.resize(img, (512, 512), interpolation=cv2.INTER_LINEAR)
190
+ face_helper.is_gray = is_gray(img, threshold=10)
191
+ if face_helper.is_gray:
192
+ print('Grayscale input: True')
193
+ face_helper.cropped_faces = [img]
194
+ else:
195
+ face_helper.read_image(img)
196
+ # get face landmarks for each face
197
+ num_det_faces = face_helper.get_face_landmarks_5(
198
+ only_center_face=args.only_center_face, resize=640, eye_dist_threshold=5)
199
+ print(f'\tdetect {num_det_faces} faces')
200
+ # align and warp each face
201
+ face_helper.align_warp_face()
202
+
203
+ # face restoration for each cropped face
204
+ for idx, cropped_face in enumerate(face_helper.cropped_faces):
205
+ # prepare data
206
+ cropped_face_t = img2tensor(cropped_face / 255., bgr2rgb=True, float32=True)
207
+ normalize(cropped_face_t, (0.5, 0.5, 0.5), (0.5, 0.5, 0.5), inplace=True)
208
+ cropped_face_t = cropped_face_t.unsqueeze(0).to(device)
209
+
210
+ try:
211
+ with torch.no_grad():
212
+ output = net(cropped_face_t, w=w, adain=True)[0]
213
+ restored_face = tensor2img(output, rgb2bgr=True, min_max=(-1, 1))
214
+ del output
215
+ torch.cuda.empty_cache()
216
+ except Exception as error:
217
+ print(f'\tFailed inference for CodeFormer: {error}')
218
+ restored_face = tensor2img(cropped_face_t, rgb2bgr=True, min_max=(-1, 1))
219
+
220
+ restored_face = restored_face.astype('uint8')
221
+ face_helper.add_restored_face(restored_face, cropped_face)
222
+
223
+ # paste_back
224
+ if not args.has_aligned:
225
+ # upsample the background
226
+ if bg_upsampler is not None:
227
+ # Now only support RealESRGAN for upsampling background
228
+ bg_img = bg_upsampler.enhance(img, outscale=args.upscale)[0]
229
+ else:
230
+ bg_img = None
231
+ face_helper.get_inverse_affine(None)
232
+ # paste each restored face to the input image
233
+ if args.face_upsample and face_upsampler is not None:
234
+ restored_img = face_helper.paste_faces_to_input_image(upsample_img=bg_img, draw_box=args.draw_box, face_upsampler=face_upsampler)
235
+ else:
236
+ restored_img = face_helper.paste_faces_to_input_image(upsample_img=bg_img, draw_box=args.draw_box)
237
+
238
+ # save faces
239
+ for idx, (cropped_face, restored_face) in enumerate(zip(face_helper.cropped_faces, face_helper.restored_faces)):
240
+ # save cropped face
241
+ if not args.has_aligned:
242
+ save_crop_path = os.path.join(result_root, 'cropped_faces', f'{basename}_{idx:02d}.png')
243
+ imwrite(cropped_face, save_crop_path)
244
+ # save restored face
245
+ if args.has_aligned:
246
+ save_face_name = f'{basename}.png'
247
+ else:
248
+ save_face_name = f'{basename}_{idx:02d}.png'
249
+ if args.suffix is not None:
250
+ save_face_name = f'{save_face_name[:-4]}_{args.suffix}.png'
251
+ save_restore_path = os.path.join(result_root, 'restored_faces', save_face_name)
252
+ imwrite(restored_face, save_restore_path)
253
+
254
+ # save restored img
255
+ if not args.has_aligned and restored_img is not None:
256
+ if args.suffix is not None:
257
+ basename = f'{basename}_{args.suffix}'
258
+ save_restore_path = os.path.join(result_root, 'final_results', f'{basename}.png')
259
+ imwrite(restored_img, save_restore_path)
260
+
261
+ # save enhanced video
262
+ if input_video:
263
+ print('Video Saving...')
264
+ # load images
265
+ video_frames = []
266
+ img_list = sorted(glob.glob(os.path.join(result_root, 'final_results', '*.[jp][pn]g')))
267
+ for img_path in img_list:
268
+ img = cv2.imread(img_path)
269
+ video_frames.append(img)
270
+ # write images to video
271
+ height, width = video_frames[0].shape[:2]
272
+ if args.suffix is not None:
273
+ video_name = f'{video_name}_{args.suffix}.png'
274
+ save_restore_path = os.path.join(result_root, f'{video_name}.mp4')
275
+ vidwriter = VideoWriter(save_restore_path, height, width, fps, audio)
276
+
277
+ for f in video_frames:
278
+ vidwriter.write_frame(f)
279
+ vidwriter.close()
280
+
281
+ print(f'\nAll results are saved in {result_root}')
CodeFormer/inference_colorization.py ADDED
@@ -0,0 +1,86 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import os
2
+ import cv2
3
+ import argparse
4
+ import glob
5
+ import torch
6
+ from torchvision.transforms.functional import normalize
7
+ from basicsr.utils import imwrite, img2tensor, tensor2img
8
+ from basicsr.utils.download_util import load_file_from_url
9
+ from basicsr.utils.misc import get_device
10
+ from basicsr.utils.registry import ARCH_REGISTRY
11
+
12
+ pretrain_model_url = 'https://github.com/sczhou/CodeFormer/releases/download/v0.1.0/codeformer_colorization.pth'
13
+
14
+ if __name__ == '__main__':
15
+ # device = torch.device('cuda' if torch.cuda.is_available() else 'cpu')
16
+ device = get_device()
17
+ parser = argparse.ArgumentParser()
18
+
19
+ parser.add_argument('-i', '--input_path', type=str, default='./inputs/gray_faces',
20
+ help='Input image or folder. Default: inputs/gray_faces')
21
+ parser.add_argument('-o', '--output_path', type=str, default=None,
22
+ help='Output folder. Default: results/<input_name>')
23
+ parser.add_argument('--suffix', type=str, default=None,
24
+ help='Suffix of the restored faces. Default: None')
25
+ args = parser.parse_args()
26
+
27
+ # ------------------------ input & output ------------------------
28
+ print('[NOTE] The input face images should be aligned and cropped to a resolution of 512x512.')
29
+ if args.input_path.endswith(('jpg', 'jpeg', 'png', 'JPG', 'JPEG', 'PNG')): # input single img path
30
+ input_img_list = [args.input_path]
31
+ result_root = f'results/test_colorization_img'
32
+ else: # input img folder
33
+ if args.input_path.endswith('/'): # solve when path ends with /
34
+ args.input_path = args.input_path[:-1]
35
+ # scan all the jpg and png images
36
+ input_img_list = sorted(glob.glob(os.path.join(args.input_path, '*.[jpJP][pnPN]*[gG]')))
37
+ result_root = f'results/{os.path.basename(args.input_path)}'
38
+
39
+ if not args.output_path is None: # set output path
40
+ result_root = args.output_path
41
+
42
+ test_img_num = len(input_img_list)
43
+
44
+ # ------------------ set up CodeFormer restorer -------------------
45
+ net = ARCH_REGISTRY.get('CodeFormer')(dim_embd=512, codebook_size=1024, n_head=8, n_layers=9,
46
+ connect_list=['32', '64', '128']).to(device)
47
+
48
+ # ckpt_path = 'weights/CodeFormer/codeformer.pth'
49
+ ckpt_path = load_file_from_url(url=pretrain_model_url,
50
+ model_dir='weights/CodeFormer', progress=True, file_name=None)
51
+ checkpoint = torch.load(ckpt_path)['params_ema']
52
+ net.load_state_dict(checkpoint)
53
+ net.eval()
54
+
55
+ # -------------------- start to processing ---------------------
56
+ for i, img_path in enumerate(input_img_list):
57
+ img_name = os.path.basename(img_path)
58
+ basename, ext = os.path.splitext(img_name)
59
+ print(f'[{i+1}/{test_img_num}] Processing: {img_name}')
60
+ input_face = cv2.imread(img_path)
61
+ assert input_face.shape[:2] == (512, 512), 'Input resolution must be 512x512 for colorization.'
62
+ # input_face = cv2.resize(input_face, (512, 512), interpolation=cv2.INTER_LINEAR)
63
+ input_face = img2tensor(input_face / 255., bgr2rgb=True, float32=True)
64
+ normalize(input_face, (0.5, 0.5, 0.5), (0.5, 0.5, 0.5), inplace=True)
65
+ input_face = input_face.unsqueeze(0).to(device)
66
+ try:
67
+ with torch.no_grad():
68
+ # w is fixed to 0 since we didn't train the Stage III for colorization
69
+ output_face = net(input_face, w=0, adain=True)[0]
70
+ save_face = tensor2img(output_face, rgb2bgr=True, min_max=(-1, 1))
71
+ del output_face
72
+ torch.cuda.empty_cache()
73
+ except Exception as error:
74
+ print(f'\tFailed inference for CodeFormer: {error}')
75
+ save_face = tensor2img(input_face, rgb2bgr=True, min_max=(-1, 1))
76
+
77
+ save_face = save_face.astype('uint8')
78
+
79
+ # save face
80
+ if args.suffix is not None:
81
+ basename = f'{basename}_{args.suffix}'
82
+ save_restore_path = os.path.join(result_root, f'{basename}.png')
83
+ imwrite(save_face, save_restore_path)
84
+
85
+ print(f'\nAll results are saved in {result_root}')
86
+
CodeFormer/inference_inpainting.py ADDED
@@ -0,0 +1,91 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import os
2
+ import cv2
3
+ import argparse
4
+ import glob
5
+ import torch
6
+ from torchvision.transforms.functional import normalize
7
+ from basicsr.utils import imwrite, img2tensor, tensor2img
8
+ from basicsr.utils.download_util import load_file_from_url
9
+ from basicsr.utils.misc import get_device
10
+ from basicsr.utils.registry import ARCH_REGISTRY
11
+
12
+ pretrain_model_url = 'https://github.com/sczhou/CodeFormer/releases/download/v0.1.0/codeformer_inpainting.pth'
13
+
14
+ if __name__ == '__main__':
15
+ # device = torch.device('cuda' if torch.cuda.is_available() else 'cpu')
16
+ device = get_device()
17
+ parser = argparse.ArgumentParser()
18
+
19
+ parser.add_argument('-i', '--input_path', type=str, default='./inputs/masked_faces',
20
+ help='Input image or folder. Default: inputs/masked_faces')
21
+ parser.add_argument('-o', '--output_path', type=str, default=None,
22
+ help='Output folder. Default: results/<input_name>')
23
+ parser.add_argument('--suffix', type=str, default=None,
24
+ help='Suffix of the restored faces. Default: None')
25
+ args = parser.parse_args()
26
+
27
+ # ------------------------ input & output ------------------------
28
+ print('[NOTE] The input face images should be aligned and cropped to a resolution of 512x512.')
29
+ if args.input_path.endswith(('jpg', 'jpeg', 'png', 'JPG', 'JPEG', 'PNG')): # input single img path
30
+ input_img_list = [args.input_path]
31
+ result_root = f'results/test_inpainting_img'
32
+ else: # input img folder
33
+ if args.input_path.endswith('/'): # solve when path ends with /
34
+ args.input_path = args.input_path[:-1]
35
+ # scan all the jpg and png images
36
+ input_img_list = sorted(glob.glob(os.path.join(args.input_path, '*.[jpJP][pnPN]*[gG]')))
37
+ result_root = f'results/{os.path.basename(args.input_path)}'
38
+
39
+ if not args.output_path is None: # set output path
40
+ result_root = args.output_path
41
+
42
+ test_img_num = len(input_img_list)
43
+
44
+ # ------------------ set up CodeFormer restorer -------------------
45
+ net = ARCH_REGISTRY.get('CodeFormer')(dim_embd=512, codebook_size=512, n_head=8, n_layers=9,
46
+ connect_list=['32', '64', '128']).to(device)
47
+
48
+ # ckpt_path = 'weights/CodeFormer/codeformer.pth'
49
+ ckpt_path = load_file_from_url(url=pretrain_model_url,
50
+ model_dir='weights/CodeFormer', progress=True, file_name=None)
51
+ checkpoint = torch.load(ckpt_path)['params_ema']
52
+ net.load_state_dict(checkpoint)
53
+ net.eval()
54
+
55
+ # -------------------- start to processing ---------------------
56
+ for i, img_path in enumerate(input_img_list):
57
+ img_name = os.path.basename(img_path)
58
+ basename, ext = os.path.splitext(img_name)
59
+ print(f'[{i+1}/{test_img_num}] Processing: {img_name}')
60
+ input_face = cv2.imread(img_path)
61
+ assert input_face.shape[:2] == (512, 512), 'Input resolution must be 512x512 for inpainting.'
62
+ # input_face = cv2.resize(input_face, (512, 512), interpolation=cv2.INTER_LINEAR)
63
+ input_face = img2tensor(input_face / 255., bgr2rgb=True, float32=True)
64
+ normalize(input_face, (0.5, 0.5, 0.5), (0.5, 0.5, 0.5), inplace=True)
65
+ input_face = input_face.unsqueeze(0).to(device)
66
+ try:
67
+ with torch.no_grad():
68
+ mask = torch.zeros(512, 512)
69
+ m_ind = torch.sum(input_face[0], dim=0)
70
+ mask[m_ind==3] = 1.0
71
+ mask = mask.view(1, 1, 512, 512).to(device)
72
+ # w is fixed to 1, adain=False for inpainting
73
+ output_face = net(input_face, w=1, adain=False)[0]
74
+ output_face = (1-mask)*input_face + mask*output_face
75
+ save_face = tensor2img(output_face, rgb2bgr=True, min_max=(-1, 1))
76
+ del output_face
77
+ torch.cuda.empty_cache()
78
+ except Exception as error:
79
+ print(f'\tFailed inference for CodeFormer: {error}')
80
+ save_face = tensor2img(input_face, rgb2bgr=True, min_max=(-1, 1))
81
+
82
+ save_face = save_face.astype('uint8')
83
+
84
+ # save face
85
+ if args.suffix is not None:
86
+ basename = f'{basename}_{args.suffix}'
87
+ save_restore_path = os.path.join(result_root, f'{basename}.png')
88
+ imwrite(save_face, save_restore_path)
89
+
90
+ print(f'\nAll results are saved in {result_root}')
91
+
CodeFormer/options/CodeFormer_colorization.yml ADDED
@@ -0,0 +1,145 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # general settings
2
+ name: CodeFormer_colorization
3
+ model_type: CodeFormerIdxModel
4
+ num_gpu: 8
5
+ manual_seed: 0
6
+
7
+ # dataset and data loader settings
8
+ datasets:
9
+ train:
10
+ name: FFHQ
11
+ type: FFHQBlindDataset
12
+ dataroot_gt: datasets/ffhq/ffhq_512
13
+ filename_tmpl: '{}'
14
+ io_backend:
15
+ type: disk
16
+
17
+ in_size: 512
18
+ gt_size: 512
19
+ mean: [0.5, 0.5, 0.5]
20
+ std: [0.5, 0.5, 0.5]
21
+ use_hflip: true
22
+ use_corrupt: true
23
+
24
+ # large degradation in stageII
25
+ blur_kernel_size: 41
26
+ use_motion_kernel: false
27
+ motion_kernel_prob: 0.001
28
+ kernel_list: ['iso', 'aniso']
29
+ kernel_prob: [0.5, 0.5]
30
+ blur_sigma: [1, 15]
31
+ downsample_range: [4, 30]
32
+ noise_range: [0, 20]
33
+ jpeg_range: [30, 80]
34
+
35
+ # color jitter and gray
36
+ color_jitter_prob: 0.3
37
+ color_jitter_shift: 20
38
+ color_jitter_pt_prob: 0.3
39
+ gray_prob: 0.01
40
+
41
+ latent_gt_path: ~ # without pre-calculated latent code
42
+ # latent_gt_path: './experiments/pretrained_models/VQGAN/latent_gt_code1024.pth'
43
+
44
+ # data loader
45
+ num_worker_per_gpu: 2
46
+ batch_size_per_gpu: 4
47
+ dataset_enlarge_ratio: 100
48
+ prefetch_mode: ~
49
+
50
+ # val:
51
+ # name: CelebA-HQ-512
52
+ # type: PairedImageDataset
53
+ # dataroot_lq: datasets/faces/validation/lq
54
+ # dataroot_gt: datasets/faces/validation/gt
55
+ # io_backend:
56
+ # type: disk
57
+ # mean: [0.5, 0.5, 0.5]
58
+ # std: [0.5, 0.5, 0.5]
59
+ # scale: 1
60
+
61
+ # network structures
62
+ network_g:
63
+ type: CodeFormer
64
+ dim_embd: 512
65
+ n_head: 8
66
+ n_layers: 9
67
+ codebook_size: 1024
68
+ connect_list: ['32', '64', '128', '256']
69
+ fix_modules: ['quantize','generator']
70
+ vqgan_path: './experiments/pretrained_models/vqgan/vqgan_code1024.pth' # pretrained VQGAN
71
+
72
+ network_vqgan: # this config is needed if no pre-calculated latent
73
+ type: VQAutoEncoder
74
+ img_size: 512
75
+ nf: 64
76
+ ch_mult: [1, 2, 2, 4, 4, 8]
77
+ quantizer: 'nearest'
78
+ codebook_size: 1024
79
+
80
+ # path
81
+ path:
82
+ pretrain_network_g: ~
83
+ param_key_g: params_ema
84
+ strict_load_g: false
85
+ pretrain_network_d: ~
86
+ strict_load_d: true
87
+ resume_state: ~
88
+
89
+ # base_lr(4.5e-6)*bach_size(4)
90
+ train:
91
+ use_hq_feat_loss: true
92
+ feat_loss_weight: 1.0
93
+ cross_entropy_loss: true
94
+ entropy_loss_weight: 0.5
95
+ fidelity_weight: 0
96
+
97
+ optim_g:
98
+ type: Adam
99
+ lr: !!float 1e-4
100
+ weight_decay: 0
101
+ betas: [0.9, 0.99]
102
+
103
+ scheduler:
104
+ type: MultiStepLR
105
+ milestones: [400000, 450000]
106
+ gamma: 0.5
107
+
108
+ total_iter: 500000
109
+
110
+ warmup_iter: -1 # no warm up
111
+ ema_decay: 0.995
112
+
113
+ use_adaptive_weight: true
114
+
115
+ net_g_start_iter: 0
116
+ net_d_iters: 1
117
+ net_d_start_iter: 0
118
+ manual_seed: 0
119
+
120
+ # validation settings
121
+ val:
122
+ val_freq: !!float 5e10 # no validation
123
+ save_img: true
124
+
125
+ metrics:
126
+ psnr: # metric name, can be arbitrary
127
+ type: calculate_psnr
128
+ crop_border: 4
129
+ test_y_channel: false
130
+
131
+ # logging settings
132
+ logger:
133
+ print_freq: 100
134
+ save_checkpoint_freq: !!float 1e4
135
+ use_tb_logger: true
136
+ wandb:
137
+ project: ~
138
+ resume_id: ~
139
+
140
+ # dist training settings
141
+ dist_params:
142
+ backend: nccl
143
+ port: 29419
144
+
145
+ find_unused_parameters: true
CodeFormer/options/CodeFormer_inpainting.yml ADDED
@@ -0,0 +1,159 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # general settings
2
+ name: CodeFormer_inpainting
3
+ model_type: CodeFormerModel
4
+ num_gpu: 4
5
+ manual_seed: 0
6
+
7
+ # dataset and data loader settings
8
+ datasets:
9
+ train:
10
+ name: FFHQ
11
+ type: FFHQBlindDataset
12
+ dataroot_gt: datasets/ffhq/ffhq_512
13
+ filename_tmpl: '{}'
14
+ io_backend:
15
+ type: disk
16
+
17
+ in_size: 512
18
+ gt_size: 512
19
+ mean: [0.5, 0.5, 0.5]
20
+ std: [0.5, 0.5, 0.5]
21
+ use_hflip: true
22
+ use_corrupt: false
23
+ gen_inpaint_mask: true
24
+
25
+ latent_gt_path: ~ # without pre-calculated latent code
26
+ # latent_gt_path: './experiments/pretrained_models/VQGAN/latent_gt_code1024.pth'
27
+
28
+ # data loader
29
+ num_worker_per_gpu: 2
30
+ batch_size_per_gpu: 3
31
+ dataset_enlarge_ratio: 100
32
+ prefetch_mode: ~
33
+
34
+ # val:
35
+ # name: CelebA-HQ-512
36
+ # type: PairedImageDataset
37
+ # dataroot_lq: datasets/faces/validation/lq
38
+ # dataroot_gt: datasets/faces/validation/gt
39
+ # io_backend:
40
+ # type: disk
41
+ # mean: [0.5, 0.5, 0.5]
42
+ # std: [0.5, 0.5, 0.5]
43
+ # scale: 1
44
+
45
+ # network structures
46
+ network_g:
47
+ type: CodeFormer
48
+ dim_embd: 512
49
+ n_head: 8
50
+ n_layers: 9
51
+ codebook_size: 1024
52
+ connect_list: ['32', '64', '128']
53
+ fix_modules: ['quantize','generator']
54
+ vqgan_path: './experiments/pretrained_models/vqgan/vqgan_code1024.pth' # pretrained VQGAN
55
+
56
+ network_vqgan: # this config is needed if no pre-calculated latent
57
+ type: VQAutoEncoder
58
+ img_size: 512
59
+ nf: 64
60
+ ch_mult: [1, 2, 2, 4, 4, 8]
61
+ quantizer: 'nearest'
62
+ codebook_size: 1024
63
+
64
+ network_d:
65
+ type: VQGANDiscriminator
66
+ nc: 3
67
+ ndf: 64
68
+ n_layers: 4
69
+ model_path: ~
70
+
71
+ # path
72
+ path:
73
+ pretrain_network_g: ~
74
+ param_key_g: params_ema
75
+ strict_load_g: true
76
+ pretrain_network_d: ~
77
+ strict_load_d: true
78
+ resume_state: ~
79
+
80
+ # base_lr(4.5e-6)*bach_size(4)
81
+ train:
82
+ use_hq_feat_loss: true
83
+ feat_loss_weight: 1.0
84
+ cross_entropy_loss: true
85
+ entropy_loss_weight: 0.5
86
+ scale_adaptive_gan_weight: 0.1
87
+ fidelity_weight: 1.0
88
+
89
+ optim_g:
90
+ type: Adam
91
+ lr: !!float 7e-5
92
+ weight_decay: 0
93
+ betas: [0.9, 0.99]
94
+ optim_d:
95
+ type: Adam
96
+ lr: !!float 7e-5
97
+ weight_decay: 0
98
+ betas: [0.9, 0.99]
99
+
100
+ scheduler:
101
+ type: MultiStepLR
102
+ milestones: [250000, 300000]
103
+ gamma: 0.5
104
+
105
+ total_iter: 300000
106
+
107
+ warmup_iter: -1 # no warm up
108
+ ema_decay: 0.997
109
+
110
+ pixel_opt:
111
+ type: L1Loss
112
+ loss_weight: 1.0
113
+ reduction: mean
114
+
115
+ perceptual_opt:
116
+ type: LPIPSLoss
117
+ loss_weight: 1.0
118
+ use_input_norm: true
119
+ range_norm: true
120
+
121
+ gan_opt:
122
+ type: GANLoss
123
+ gan_type: hinge
124
+ loss_weight: !!float 1.0 # adaptive_weighting
125
+
126
+
127
+ use_adaptive_weight: true
128
+
129
+ net_g_start_iter: 0
130
+ net_d_iters: 1
131
+ net_d_start_iter: 296001
132
+ manual_seed: 0
133
+
134
+ # validation settings
135
+ val:
136
+ val_freq: !!float 5e10 # no validation
137
+ save_img: true
138
+
139
+ metrics:
140
+ psnr: # metric name, can be arbitrary
141
+ type: calculate_psnr
142
+ crop_border: 4
143
+ test_y_channel: false
144
+
145
+ # logging settings
146
+ logger:
147
+ print_freq: 100
148
+ save_checkpoint_freq: !!float 1e4
149
+ use_tb_logger: true
150
+ wandb:
151
+ project: ~
152
+ resume_id: ~
153
+
154
+ # dist training settings
155
+ dist_params:
156
+ backend: nccl
157
+ port: 29420
158
+
159
+ find_unused_parameters: true
CodeFormer/options/CodeFormer_stage2.yml ADDED
@@ -0,0 +1,145 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # general settings
2
+ name: CodeFormer_stage2
3
+ model_type: CodeFormerIdxModel
4
+ num_gpu: 8
5
+ manual_seed: 0
6
+
7
+ # dataset and data loader settings
8
+ datasets:
9
+ train:
10
+ name: FFHQ
11
+ type: FFHQBlindDataset
12
+ dataroot_gt: datasets/ffhq/ffhq_512
13
+ filename_tmpl: '{}'
14
+ io_backend:
15
+ type: disk
16
+
17
+ in_size: 512
18
+ gt_size: 512
19
+ mean: [0.5, 0.5, 0.5]
20
+ std: [0.5, 0.5, 0.5]
21
+ use_hflip: true
22
+ use_corrupt: true
23
+
24
+ # large degradation in stageII
25
+ blur_kernel_size: 41
26
+ use_motion_kernel: false
27
+ motion_kernel_prob: 0.001
28
+ kernel_list: ['iso', 'aniso']
29
+ kernel_prob: [0.5, 0.5]
30
+ blur_sigma: [1, 15]
31
+ downsample_range: [4, 30]
32
+ noise_range: [0, 20]
33
+ jpeg_range: [30, 80]
34
+
35
+ latent_gt_path: ~ # without pre-calculated latent code
36
+ # latent_gt_path: './experiments/pretrained_models/VQGAN/latent_gt_code1024.pth'
37
+
38
+ # data loader
39
+ num_worker_per_gpu: 2
40
+ batch_size_per_gpu: 4
41
+ dataset_enlarge_ratio: 100
42
+ prefetch_mode: ~
43
+
44
+ # val:
45
+ # name: CelebA-HQ-512
46
+ # type: PairedImageDataset
47
+ # dataroot_lq: datasets/faces/validation/lq
48
+ # dataroot_gt: datasets/faces/validation/gt
49
+ # io_backend:
50
+ # type: disk
51
+ # mean: [0.5, 0.5, 0.5]
52
+ # std: [0.5, 0.5, 0.5]
53
+ # scale: 1
54
+
55
+ # network structures
56
+ network_g:
57
+ type: CodeFormer
58
+ dim_embd: 512
59
+ n_head: 8
60
+ n_layers: 9
61
+ codebook_size: 1024
62
+ connect_list: ['32', '64', '128', '256']
63
+ fix_modules: ['quantize','generator']
64
+ vqgan_path: './experiments/pretrained_models/vqgan/vqgan_code1024.pth' # pretrained VQGAN
65
+
66
+ network_vqgan: # this config is needed if no pre-calculated latent
67
+ type: VQAutoEncoder
68
+ img_size: 512
69
+ nf: 64
70
+ ch_mult: [1, 2, 2, 4, 4, 8]
71
+ quantizer: 'nearest'
72
+ codebook_size: 1024
73
+
74
+ # path
75
+ path:
76
+ pretrain_network_g: ~
77
+ param_key_g: params_ema
78
+ strict_load_g: false
79
+ pretrain_network_d: ~
80
+ strict_load_d: true
81
+ resume_state: ~
82
+
83
+ # base_lr(4.5e-6)*bach_size(4)
84
+ train:
85
+ use_hq_feat_loss: true
86
+ feat_loss_weight: 1.0
87
+ cross_entropy_loss: true
88
+ entropy_loss_weight: 0.5
89
+ fidelity_weight: 0
90
+
91
+ optim_g:
92
+ type: Adam
93
+ lr: !!float 1e-4
94
+ weight_decay: 0
95
+ betas: [0.9, 0.99]
96
+
97
+ scheduler:
98
+ type: MultiStepLR
99
+ milestones: [400000, 450000]
100
+ gamma: 0.5
101
+
102
+ # scheduler:
103
+ # type: CosineAnnealingRestartLR
104
+ # periods: [500000]
105
+ # restart_weights: [1]
106
+ # eta_min: !!float 2e-5 # no lr reduce in official vqgan code
107
+
108
+ total_iter: 500000
109
+
110
+ warmup_iter: -1 # no warm up
111
+ ema_decay: 0.995
112
+
113
+ use_adaptive_weight: true
114
+
115
+ net_g_start_iter: 0
116
+ net_d_iters: 1
117
+ net_d_start_iter: 0
118
+ manual_seed: 0
119
+
120
+ # validation settings
121
+ val:
122
+ val_freq: !!float 5e10 # no validation
123
+ save_img: true
124
+
125
+ metrics:
126
+ psnr: # metric name, can be arbitrary
127
+ type: calculate_psnr
128
+ crop_border: 4
129
+ test_y_channel: false
130
+
131
+ # logging settings
132
+ logger:
133
+ print_freq: 100
134
+ save_checkpoint_freq: !!float 1e4
135
+ use_tb_logger: true
136
+ wandb:
137
+ project: ~
138
+ resume_id: ~
139
+
140
+ # dist training settings
141
+ dist_params:
142
+ backend: nccl
143
+ port: 29412
144
+
145
+ find_unused_parameters: true
CodeFormer/options/CodeFormer_stage3.yml ADDED
@@ -0,0 +1,171 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # general settings
2
+ name: CodeFormer_stage3
3
+ model_type: CodeFormerJointModel
4
+ num_gpu: 8
5
+ manual_seed: 0
6
+
7
+ # dataset and data loader settings
8
+ datasets:
9
+ train:
10
+ name: FFHQ
11
+ type: FFHQBlindJointDataset
12
+ dataroot_gt: datasets/ffhq/ffhq_512
13
+ filename_tmpl: '{}'
14
+ io_backend:
15
+ type: disk
16
+
17
+ in_size: 512
18
+ gt_size: 512
19
+ mean: [0.5, 0.5, 0.5]
20
+ std: [0.5, 0.5, 0.5]
21
+ use_hflip: true
22
+ use_corrupt: true
23
+
24
+ blur_kernel_size: 41
25
+ use_motion_kernel: false
26
+ motion_kernel_prob: 0.001
27
+ kernel_list: ['iso', 'aniso']
28
+ kernel_prob: [0.5, 0.5]
29
+ # small degradation in stageIII
30
+ blur_sigma: [0.1, 10]
31
+ downsample_range: [1, 12]
32
+ noise_range: [0, 15]
33
+ jpeg_range: [60, 100]
34
+ # large degradation in stageII
35
+ blur_sigma_large: [1, 15]
36
+ downsample_range_large: [4, 30]
37
+ noise_range_large: [0, 20]
38
+ jpeg_range_large: [30, 80]
39
+
40
+ latent_gt_path: ~ # without pre-calculated latent code
41
+ # latent_gt_path: './experiments/pretrained_models/VQGAN/latent_gt_code1024.pth'
42
+
43
+ # data loader
44
+ num_worker_per_gpu: 1
45
+ batch_size_per_gpu: 3
46
+ dataset_enlarge_ratio: 100
47
+ prefetch_mode: ~
48
+
49
+ # val:
50
+ # name: CelebA-HQ-512
51
+ # type: PairedImageDataset
52
+ # dataroot_lq: datasets/faces/validation/lq
53
+ # dataroot_gt: datasets/faces/validation/gt
54
+ # io_backend:
55
+ # type: disk
56
+ # mean: [0.5, 0.5, 0.5]
57
+ # std: [0.5, 0.5, 0.5]
58
+ # scale: 1
59
+
60
+ # network structures
61
+ network_g:
62
+ type: CodeFormer
63
+ dim_embd: 512
64
+ n_head: 8
65
+ n_layers: 9
66
+ codebook_size: 1024
67
+ connect_list: ['32', '64', '128', '256']
68
+ fix_modules: ['quantize','generator']
69
+
70
+ network_vqgan: # this config is needed if no pre-calculated latent
71
+ type: VQAutoEncoder
72
+ img_size: 512
73
+ nf: 64
74
+ ch_mult: [1, 2, 2, 4, 4, 8]
75
+ quantizer: 'nearest'
76
+ codebook_size: 1024
77
+
78
+ network_d:
79
+ type: VQGANDiscriminator
80
+ nc: 3
81
+ ndf: 64
82
+ n_layers: 4
83
+
84
+ # path
85
+ path:
86
+ pretrain_network_g: './experiments/pretrained_models/CodeFormer_stage2/net_g_latest.pth' # pretrained G model in StageII
87
+ param_key_g: params_ema
88
+ strict_load_g: false
89
+ pretrain_network_d: './experiments/pretrained_models/CodeFormer_stage2/net_d_latest.pth' # pretrained D model in StageII
90
+ resume_state: ~
91
+
92
+ # base_lr(4.5e-6)*bach_size(4)
93
+ train:
94
+ use_hq_feat_loss: true
95
+ feat_loss_weight: 1.0
96
+ cross_entropy_loss: true
97
+ entropy_loss_weight: 0.5
98
+ scale_adaptive_gan_weight: 0.1
99
+
100
+ optim_g:
101
+ type: Adam
102
+ lr: !!float 5e-5
103
+ weight_decay: 0
104
+ betas: [0.9, 0.99]
105
+ optim_d:
106
+ type: Adam
107
+ lr: !!float 5e-5
108
+ weight_decay: 0
109
+ betas: [0.9, 0.99]
110
+
111
+ scheduler:
112
+ type: CosineAnnealingRestartLR
113
+ periods: [150000]
114
+ restart_weights: [1]
115
+ eta_min: !!float 2e-5
116
+
117
+
118
+ total_iter: 150000
119
+
120
+ warmup_iter: -1 # no warm up
121
+ ema_decay: 0.997
122
+
123
+ pixel_opt:
124
+ type: L1Loss
125
+ loss_weight: 1.0
126
+ reduction: mean
127
+
128
+ perceptual_opt:
129
+ type: LPIPSLoss
130
+ loss_weight: 1.0
131
+ use_input_norm: true
132
+ range_norm: true
133
+
134
+ gan_opt:
135
+ type: GANLoss
136
+ gan_type: hinge
137
+ loss_weight: !!float 1.0 # adaptive_weighting
138
+
139
+ use_adaptive_weight: true
140
+
141
+ net_g_start_iter: 0
142
+ net_d_iters: 1
143
+ net_d_start_iter: 5001
144
+ manual_seed: 0
145
+
146
+ # validation settings
147
+ val:
148
+ val_freq: !!float 5e10 # no validation
149
+ save_img: true
150
+
151
+ metrics:
152
+ psnr: # metric name, can be arbitrary
153
+ type: calculate_psnr
154
+ crop_border: 4
155
+ test_y_channel: false
156
+
157
+ # logging settings
158
+ logger:
159
+ print_freq: 100
160
+ save_checkpoint_freq: !!float 5e3
161
+ use_tb_logger: true
162
+ wandb:
163
+ project: ~
164
+ resume_id: ~
165
+
166
+ # dist training settings
167
+ dist_params:
168
+ backend: nccl
169
+ port: 29413
170
+
171
+ find_unused_parameters: true
CodeFormer/options/VQGAN_512_ds32_nearest_stage1.yml ADDED
@@ -0,0 +1,136 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # general settings
2
+ name: VQGAN-512-ds32-nearest-stage1
3
+ model_type: VQGANModel
4
+ num_gpu: 8
5
+ manual_seed: 0
6
+
7
+ # dataset and data loader settings
8
+ datasets:
9
+ train:
10
+ name: FFHQ
11
+ type: FFHQBlindDataset
12
+ dataroot_gt: datasets/ffhq/ffhq_512
13
+ filename_tmpl: '{}'
14
+ io_backend:
15
+ type: disk
16
+
17
+ in_size: 512
18
+ gt_size: 512
19
+ mean: [0.5, 0.5, 0.5]
20
+ std: [0.5, 0.5, 0.5]
21
+ use_hflip: true
22
+ use_corrupt: false # for VQGAN
23
+
24
+ # data loader
25
+ num_worker_per_gpu: 2
26
+ batch_size_per_gpu: 4
27
+ dataset_enlarge_ratio: 100
28
+
29
+ prefetch_mode: cpu
30
+ num_prefetch_queue: 4
31
+
32
+ # val:
33
+ # name: CelebA-HQ-512
34
+ # type: PairedImageDataset
35
+ # dataroot_lq: datasets/faces/validation/gt
36
+ # dataroot_gt: datasets/faces/validation/gt
37
+ # io_backend:
38
+ # type: disk
39
+ # mean: [0.5, 0.5, 0.5]
40
+ # std: [0.5, 0.5, 0.5]
41
+ # scale: 1
42
+
43
+ # network structures
44
+ network_g:
45
+ type: VQAutoEncoder
46
+ img_size: 512
47
+ nf: 64
48
+ ch_mult: [1, 2, 2, 4, 4, 8]
49
+ quantizer: 'nearest'
50
+ codebook_size: 1024
51
+
52
+ network_d:
53
+ type: VQGANDiscriminator
54
+ nc: 3
55
+ ndf: 64
56
+
57
+ # path
58
+ path:
59
+ pretrain_network_g: ~
60
+ param_key_g: params_ema
61
+ strict_load_g: true
62
+ pretrain_network_d: ~
63
+ strict_load_d: true
64
+ resume_state: ~
65
+
66
+ # base_lr(4.5e-6)*bach_size(4)
67
+ train:
68
+ optim_g:
69
+ type: Adam
70
+ lr: !!float 7e-5
71
+ weight_decay: 0
72
+ betas: [0.9, 0.99]
73
+ optim_d:
74
+ type: Adam
75
+ lr: !!float 7e-5
76
+ weight_decay: 0
77
+ betas: [0.9, 0.99]
78
+
79
+ scheduler:
80
+ type: CosineAnnealingRestartLR
81
+ periods: [1600000]
82
+ restart_weights: [1]
83
+ eta_min: !!float 6e-5 # no lr reduce in official vqgan code
84
+
85
+ total_iter: 1600000
86
+
87
+ warmup_iter: -1 # no warm up
88
+ ema_decay: 0.995 # GFPGAN: 0.5**(32 / (10 * 1000) == 0.998; Unleashing: 0.995
89
+
90
+ pixel_opt:
91
+ type: L1Loss
92
+ loss_weight: 1.0
93
+ reduction: mean
94
+
95
+ perceptual_opt:
96
+ type: LPIPSLoss
97
+ loss_weight: 1.0
98
+ use_input_norm: true
99
+ range_norm: true
100
+
101
+ gan_opt:
102
+ type: GANLoss
103
+ gan_type: hinge
104
+ loss_weight: !!float 1.0 # adaptive_weighting
105
+
106
+ net_g_start_iter: 0
107
+ net_d_iters: 1
108
+ net_d_start_iter: 30001
109
+ manual_seed: 0
110
+
111
+ # validation settings
112
+ val:
113
+ val_freq: !!float 5e10 # no validation
114
+ save_img: true
115
+
116
+ metrics:
117
+ psnr: # metric name, can be arbitrary
118
+ type: calculate_psnr
119
+ crop_border: 4
120
+ test_y_channel: false
121
+
122
+ # logging settings
123
+ logger:
124
+ print_freq: 100
125
+ save_checkpoint_freq: !!float 1e4
126
+ use_tb_logger: true
127
+ wandb:
128
+ project: ~
129
+ resume_id: ~
130
+
131
+ # dist training settings
132
+ dist_params:
133
+ backend: nccl
134
+ port: 29411
135
+
136
+ find_unused_parameters: true
CodeFormer/requirements.txt ADDED
@@ -0,0 +1,19 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # addict
2
+ # future
3
+ # lmdb
4
+ # numpy
5
+ # opencv-python
6
+ # Pillow
7
+ # pyyaml
8
+ # requests
9
+ # scikit-image
10
+ # scipy
11
+ # tb-nightly
12
+
13
+ # tqdm
14
+ # yapf
15
+ # lpips
16
+ # gdown # supports downloading the large file from Google Drive
17
+
18
+ # torch>=1.7.1
19
+ # torchvision
CodeFormer/scripts/crop_align_face.py ADDED
@@ -0,0 +1,205 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """
2
+ brief: face alignment with FFHQ method (https://github.com/NVlabs/ffhq-dataset)
3
+ author: lzhbrian (https://lzhbrian.me)
4
+ link: https://gist.github.com/lzhbrian/bde87ab23b499dd02ba4f588258f57d5
5
+ date: 2020.1.5
6
+ note: code is heavily borrowed from
7
+ https://github.com/NVlabs/ffhq-dataset
8
+ http://dlib.net/face_landmark_detection.py.html
9
+ requirements:
10
+ conda install Pillow numpy scipy
11
+ conda install -c conda-forge dlib
12
+ # download face landmark model from:
13
+ # http://dlib.net/files/shape_predictor_68_face_landmarks.dat.bz2
14
+ """
15
+
16
+ import os
17
+ import glob
18
+ import numpy as np
19
+ import PIL
20
+ import PIL.Image
21
+ import scipy
22
+ import scipy.ndimage
23
+ import argparse
24
+ from basicsr.utils.download_util import load_file_from_url
25
+
26
+ try:
27
+ import dlib
28
+ except ImportError:
29
+ print('Please install dlib by running:' 'conda install -c conda-forge dlib')
30
+
31
+ # download model from: http://dlib.net/files/shape_predictor_68_face_landmarks.dat.bz2
32
+ shape_predictor_url = 'https://github.com/sczhou/CodeFormer/releases/download/v0.1.0/shape_predictor_68_face_landmarks-fbdc2cb8.dat'
33
+ ckpt_path = load_file_from_url(url=shape_predictor_url,
34
+ model_dir='weights/dlib', progress=True, file_name=None)
35
+ predictor = dlib.shape_predictor('weights/dlib/shape_predictor_68_face_landmarks-fbdc2cb8.dat')
36
+
37
+
38
+ def get_landmark(filepath, only_keep_largest=True):
39
+ """get landmark with dlib
40
+ :return: np.array shape=(68, 2)
41
+ """
42
+ detector = dlib.get_frontal_face_detector()
43
+
44
+ img = dlib.load_rgb_image(filepath)
45
+ dets = detector(img, 1)
46
+
47
+ # Shangchen modified
48
+ print("\tNumber of faces detected: {}".format(len(dets)))
49
+ if only_keep_largest:
50
+ print('\tOnly keep the largest.')
51
+ face_areas = []
52
+ for k, d in enumerate(dets):
53
+ face_area = (d.right() - d.left()) * (d.bottom() - d.top())
54
+ face_areas.append(face_area)
55
+
56
+ largest_idx = face_areas.index(max(face_areas))
57
+ d = dets[largest_idx]
58
+ shape = predictor(img, d)
59
+ # print("Part 0: {}, Part 1: {} ...".format(
60
+ # shape.part(0), shape.part(1)))
61
+ else:
62
+ for k, d in enumerate(dets):
63
+ # print("Detection {}: Left: {} Top: {} Right: {} Bottom: {}".format(
64
+ # k, d.left(), d.top(), d.right(), d.bottom()))
65
+ # Get the landmarks/parts for the face in box d.
66
+ shape = predictor(img, d)
67
+ # print("Part 0: {}, Part 1: {} ...".format(
68
+ # shape.part(0), shape.part(1)))
69
+
70
+ t = list(shape.parts())
71
+ a = []
72
+ for tt in t:
73
+ a.append([tt.x, tt.y])
74
+ lm = np.array(a)
75
+ # lm is a shape=(68,2) np.array
76
+ return lm
77
+
78
+ def align_face(filepath, out_path):
79
+ """
80
+ :param filepath: str
81
+ :return: PIL Image
82
+ """
83
+ try:
84
+ lm = get_landmark(filepath)
85
+ except:
86
+ print('No landmark ...')
87
+ return
88
+
89
+ lm_chin = lm[0:17] # left-right
90
+ lm_eyebrow_left = lm[17:22] # left-right
91
+ lm_eyebrow_right = lm[22:27] # left-right
92
+ lm_nose = lm[27:31] # top-down
93
+ lm_nostrils = lm[31:36] # top-down
94
+ lm_eye_left = lm[36:42] # left-clockwise
95
+ lm_eye_right = lm[42:48] # left-clockwise
96
+ lm_mouth_outer = lm[48:60] # left-clockwise
97
+ lm_mouth_inner = lm[60:68] # left-clockwise
98
+
99
+ # Calculate auxiliary vectors.
100
+ eye_left = np.mean(lm_eye_left, axis=0)
101
+ eye_right = np.mean(lm_eye_right, axis=0)
102
+ eye_avg = (eye_left + eye_right) * 0.5
103
+ eye_to_eye = eye_right - eye_left
104
+ mouth_left = lm_mouth_outer[0]
105
+ mouth_right = lm_mouth_outer[6]
106
+ mouth_avg = (mouth_left + mouth_right) * 0.5
107
+ eye_to_mouth = mouth_avg - eye_avg
108
+
109
+ # Choose oriented crop rectangle.
110
+ x = eye_to_eye - np.flipud(eye_to_mouth) * [-1, 1]
111
+ x /= np.hypot(*x)
112
+ x *= max(np.hypot(*eye_to_eye) * 2.0, np.hypot(*eye_to_mouth) * 1.8)
113
+ y = np.flipud(x) * [-1, 1]
114
+ c = eye_avg + eye_to_mouth * 0.1
115
+ quad = np.stack([c - x - y, c - x + y, c + x + y, c + x - y])
116
+ qsize = np.hypot(*x) * 2
117
+
118
+ # read image
119
+ img = PIL.Image.open(filepath)
120
+
121
+ output_size = 512
122
+ transform_size = 4096
123
+ enable_padding = False
124
+
125
+ # Shrink.
126
+ shrink = int(np.floor(qsize / output_size * 0.5))
127
+ if shrink > 1:
128
+ rsize = (int(np.rint(float(img.size[0]) / shrink)),
129
+ int(np.rint(float(img.size[1]) / shrink)))
130
+ img = img.resize(rsize, PIL.Image.ANTIALIAS)
131
+ quad /= shrink
132
+ qsize /= shrink
133
+
134
+ # Crop.
135
+ border = max(int(np.rint(qsize * 0.1)), 3)
136
+ crop = (int(np.floor(min(quad[:, 0]))), int(np.floor(min(quad[:, 1]))),
137
+ int(np.ceil(max(quad[:, 0]))), int(np.ceil(max(quad[:, 1]))))
138
+ crop = (max(crop[0] - border, 0), max(crop[1] - border, 0),
139
+ min(crop[2] + border,
140
+ img.size[0]), min(crop[3] + border, img.size[1]))
141
+ if crop[2] - crop[0] < img.size[0] or crop[3] - crop[1] < img.size[1]:
142
+ img = img.crop(crop)
143
+ quad -= crop[0:2]
144
+
145
+ # Pad.
146
+ pad = (int(np.floor(min(quad[:, 0]))), int(np.floor(min(quad[:, 1]))),
147
+ int(np.ceil(max(quad[:, 0]))), int(np.ceil(max(quad[:, 1]))))
148
+ pad = (max(-pad[0] + border,
149
+ 0), max(-pad[1] + border,
150
+ 0), max(pad[2] - img.size[0] + border,
151
+ 0), max(pad[3] - img.size[1] + border, 0))
152
+ if enable_padding and max(pad) > border - 4:
153
+ pad = np.maximum(pad, int(np.rint(qsize * 0.3)))
154
+ img = np.pad(
155
+ np.float32(img), ((pad[1], pad[3]), (pad[0], pad[2]), (0, 0)),
156
+ 'reflect')
157
+ h, w, _ = img.shape
158
+ y, x, _ = np.ogrid[:h, :w, :1]
159
+ mask = np.maximum(
160
+ 1.0 -
161
+ np.minimum(np.float32(x) / pad[0],
162
+ np.float32(w - 1 - x) / pad[2]), 1.0 -
163
+ np.minimum(np.float32(y) / pad[1],
164
+ np.float32(h - 1 - y) / pad[3]))
165
+ blur = qsize * 0.02
166
+ img += (scipy.ndimage.gaussian_filter(img, [blur, blur, 0]) -
167
+ img) * np.clip(mask * 3.0 + 1.0, 0.0, 1.0)
168
+ img += (np.median(img, axis=(0, 1)) - img) * np.clip(mask, 0.0, 1.0)
169
+ img = PIL.Image.fromarray(
170
+ np.uint8(np.clip(np.rint(img), 0, 255)), 'RGB')
171
+ quad += pad[:2]
172
+
173
+ img = img.transform((transform_size, transform_size), PIL.Image.QUAD,
174
+ (quad + 0.5).flatten(), PIL.Image.BILINEAR)
175
+
176
+ if output_size < transform_size:
177
+ img = img.resize((output_size, output_size), PIL.Image.ANTIALIAS)
178
+
179
+ # Save aligned image.
180
+ # print('saveing: ', out_path)
181
+ img.save(out_path)
182
+
183
+ return img, np.max(quad[:, 0]) - np.min(quad[:, 0])
184
+
185
+
186
+ if __name__ == '__main__':
187
+ parser = argparse.ArgumentParser()
188
+ parser.add_argument('-i', '--in_dir', type=str, default='./inputs/whole_imgs')
189
+ parser.add_argument('-o', '--out_dir', type=str, default='./inputs/cropped_faces')
190
+ args = parser.parse_args()
191
+
192
+ if args.out_dir.endswith('/'): # solve when path ends with /
193
+ args.out_dir = args.out_dir[:-1]
194
+ dir_name = os.path.abspath(args.out_dir)
195
+ os.makedirs(dir_name, exist_ok=True)
196
+
197
+ img_list = sorted(glob.glob(os.path.join(args.in_dir, '*.[jpJP][pnPN]*[gG]')))
198
+ test_img_num = len(img_list)
199
+
200
+ for i, in_path in enumerate(img_list):
201
+ img_name = os.path.basename(in_path)
202
+ print(f'[{i+1}/{test_img_num}] Processing: {img_name}')
203
+ out_path = os.path.join(args.out_dir, in_path.split("/")[-1])
204
+ out_path = out_path.replace('.jpg', '.png')
205
+ size_ = align_face(in_path, out_path)
CodeFormer/scripts/download_pretrained_models.py ADDED
@@ -0,0 +1,52 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import argparse
2
+ import os
3
+ from os import path as osp
4
+
5
+ from basicsr.utils.download_util import load_file_from_url
6
+
7
+
8
+ def download_pretrained_models(method, file_urls):
9
+ if method == 'CodeFormer_train':
10
+ method = 'CodeFormer'
11
+ save_path_root = f'./weights/{method}'
12
+ os.makedirs(save_path_root, exist_ok=True)
13
+
14
+ for file_name, file_url in file_urls.items():
15
+ save_path = load_file_from_url(url=file_url, model_dir=save_path_root, progress=True, file_name=file_name)
16
+
17
+
18
+ if __name__ == '__main__':
19
+ parser = argparse.ArgumentParser()
20
+
21
+ parser.add_argument(
22
+ 'method',
23
+ type=str,
24
+ help=("Options: 'CodeFormer' 'facelib' 'dlib'. Set to 'all' to download all the models."))
25
+ args = parser.parse_args()
26
+
27
+ file_urls = {
28
+ 'CodeFormer': {
29
+ 'codeformer.pth': 'https://github.com/sczhou/CodeFormer/releases/download/v0.1.0/codeformer.pth'
30
+ },
31
+ 'CodeFormer_train': {
32
+ 'vqgan_code1024.pth': 'https://github.com/sczhou/CodeFormer/releases/download/v0.1.0/vqgan_code1024.pth',
33
+ 'latent_gt_code1024.pth': 'https://github.com/sczhou/CodeFormer/releases/download/v0.1.0/latent_gt_code1024.pth',
34
+ 'codeformer_stage2.pth': 'https://github.com/sczhou/CodeFormer/releases/download/v0.1.0/codeformer_stage2.pth',
35
+ 'codeformer.pth': 'https://github.com/sczhou/CodeFormer/releases/download/v0.1.0/codeformer.pth'
36
+ },
37
+ 'facelib': {
38
+ # 'yolov5l-face.pth': 'https://github.com/sczhou/CodeFormer/releases/download/v0.1.0/yolov5l-face.pth',
39
+ 'detection_Resnet50_Final.pth': 'https://github.com/sczhou/CodeFormer/releases/download/v0.1.0/detection_Resnet50_Final.pth',
40
+ 'parsing_parsenet.pth': 'https://github.com/sczhou/CodeFormer/releases/download/v0.1.0/parsing_parsenet.pth'
41
+ },
42
+ 'dlib': {
43
+ 'mmod_human_face_detector-4cb19393.dat': 'https://github.com/sczhou/CodeFormer/releases/download/v0.1.0/mmod_human_face_detector-4cb19393.dat',
44
+ 'shape_predictor_5_face_landmarks-c4b1e980.dat': 'https://github.com/sczhou/CodeFormer/releases/download/v0.1.0/shape_predictor_5_face_landmarks-c4b1e980.dat'
45
+ }
46
+ }
47
+
48
+ if args.method == 'all':
49
+ for method in file_urls.keys():
50
+ download_pretrained_models(method, file_urls[method])
51
+ else:
52
+ download_pretrained_models(args.method, file_urls[args.method])
CodeFormer/scripts/download_pretrained_models_from_gdrive.py ADDED
@@ -0,0 +1,60 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import argparse
2
+ import os
3
+ from os import path as osp
4
+
5
+ # from basicsr.utils.download_util import download_file_from_google_drive
6
+ import gdown
7
+
8
+
9
+ def download_pretrained_models(method, file_ids):
10
+ save_path_root = f'./weights/{method}'
11
+ os.makedirs(save_path_root, exist_ok=True)
12
+
13
+ for file_name, file_id in file_ids.items():
14
+ file_url = 'https://drive.google.com/uc?id='+file_id
15
+ save_path = osp.abspath(osp.join(save_path_root, file_name))
16
+ if osp.exists(save_path):
17
+ user_response = input(f'{file_name} already exist. Do you want to cover it? Y/N\n')
18
+ if user_response.lower() == 'y':
19
+ print(f'Covering {file_name} to {save_path}')
20
+ gdown.download(file_url, save_path, quiet=False)
21
+ # download_file_from_google_drive(file_id, save_path)
22
+ elif user_response.lower() == 'n':
23
+ print(f'Skipping {file_name}')
24
+ else:
25
+ raise ValueError('Wrong input. Only accepts Y/N.')
26
+ else:
27
+ print(f'Downloading {file_name} to {save_path}')
28
+ gdown.download(file_url, save_path, quiet=False)
29
+ # download_file_from_google_drive(file_id, save_path)
30
+
31
+ if __name__ == '__main__':
32
+ parser = argparse.ArgumentParser()
33
+
34
+ parser.add_argument(
35
+ 'method',
36
+ type=str,
37
+ help=("Options: 'CodeFormer' 'facelib'. Set to 'all' to download all the models."))
38
+ args = parser.parse_args()
39
+
40
+ # file name: file id
41
+ # 'dlib': {
42
+ # 'mmod_human_face_detector-4cb19393.dat': '1qD-OqY8M6j4PWUP_FtqfwUPFPRMu6ubX',
43
+ # 'shape_predictor_5_face_landmarks-c4b1e980.dat': '1vF3WBUApw4662v9Pw6wke3uk1qxnmLdg',
44
+ # 'shape_predictor_68_face_landmarks-fbdc2cb8.dat': '1tJyIVdCHaU6IDMDx86BZCxLGZfsWB8yq'
45
+ # }
46
+ file_ids = {
47
+ 'CodeFormer': {
48
+ 'codeformer.pth': '1v_E_vZvP-dQPF55Kc5SRCjaKTQXDz-JB'
49
+ },
50
+ 'facelib': {
51
+ 'yolov5l-face.pth': '131578zMA6B2x8VQHyHfa6GEPtulMCNzV',
52
+ 'parsing_parsenet.pth': '16pkohyZZ8ViHGBk3QtVqxLZKzdo466bK'
53
+ }
54
+ }
55
+
56
+ if args.method == 'all':
57
+ for method in file_ids.keys():
58
+ download_pretrained_models(method, file_ids[method])
59
+ else:
60
+ download_pretrained_models(args.method, file_ids[args.method])
CodeFormer/scripts/generate_latent_gt.py ADDED
@@ -0,0 +1,67 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import argparse
2
+ import glob
3
+ import numpy as np
4
+ import os
5
+ import cv2
6
+ import torch
7
+ from torchvision.transforms.functional import normalize
8
+ from basicsr.utils import imwrite, img2tensor, tensor2img
9
+
10
+ from basicsr.utils.registry import ARCH_REGISTRY
11
+
12
+ if __name__ == '__main__':
13
+ parser = argparse.ArgumentParser()
14
+ parser.add_argument('-i', '--test_path', type=str, default='datasets/ffhq/ffhq_512')
15
+ parser.add_argument('-o', '--save_root', type=str, default='./experiments/pretrained_models/vqgan')
16
+ parser.add_argument('--codebook_size', type=int, default=1024)
17
+ parser.add_argument('--ckpt_path', type=str, default='./experiments/pretrained_models/vqgan/net_g.pth')
18
+ args = parser.parse_args()
19
+
20
+ if args.save_root.endswith('/'): # solve when path ends with /
21
+ args.save_root = args.save_root[:-1]
22
+ dir_name = os.path.abspath(args.save_root)
23
+ os.makedirs(dir_name, exist_ok=True)
24
+
25
+ device = torch.device('cuda' if torch.cuda.is_available() else 'cpu')
26
+ test_path = args.test_path
27
+ save_root = args.save_root
28
+ ckpt_path = args.ckpt_path
29
+ codebook_size = args.codebook_size
30
+
31
+ vqgan = ARCH_REGISTRY.get('VQAutoEncoder')(512, 64, [1, 2, 2, 4, 4, 8], 'nearest',
32
+ codebook_size=codebook_size).to(device)
33
+ checkpoint = torch.load(ckpt_path)['params_ema']
34
+
35
+ vqgan.load_state_dict(checkpoint)
36
+ vqgan.eval()
37
+
38
+ sum_latent = np.zeros((codebook_size)).astype('float64')
39
+ size_latent = 16
40
+ latent = {}
41
+ latent['orig'] = {}
42
+ latent['hflip'] = {}
43
+ for i in ['orig', 'hflip']:
44
+ # for i in ['hflip']:
45
+ for img_path in sorted(glob.glob(os.path.join(test_path, '*.[jp][pn]g'))):
46
+ img_name = os.path.basename(img_path)
47
+ img = cv2.imread(img_path)
48
+ if i == 'hflip':
49
+ cv2.flip(img, 1, img)
50
+ img = img2tensor(img / 255., bgr2rgb=True, float32=True)
51
+ normalize(img, (0.5, 0.5, 0.5), (0.5, 0.5, 0.5), inplace=True)
52
+ img = img.unsqueeze(0).to(device)
53
+ with torch.no_grad():
54
+ # output = net(img)[0]
55
+ x, feat_dict = vqgan.encoder(img, True)
56
+ x, _, log = vqgan.quantize(x)
57
+ # del output
58
+ torch.cuda.empty_cache()
59
+
60
+ min_encoding_indices = log['min_encoding_indices']
61
+ min_encoding_indices = min_encoding_indices.view(size_latent,size_latent)
62
+ latent[i][img_name[:-4]] = min_encoding_indices.cpu().numpy()
63
+ print(img_name, latent[i][img_name[:-4]].shape)
64
+
65
+ latent_save_path = os.path.join(save_root, f'latent_gt_code{codebook_size}.pth')
66
+ torch.save(latent, latent_save_path)
67
+ print(f'\nLatent GT code are saved in {save_root}')
CodeFormer/scripts/inference_vqgan.py ADDED
@@ -0,0 +1,59 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import argparse
2
+ import glob
3
+ import numpy as np
4
+ import os
5
+ import cv2
6
+ import torch
7
+ from torchvision.transforms.functional import normalize
8
+ from basicsr.utils import imwrite, img2tensor, tensor2img
9
+
10
+ from basicsr.utils.registry import ARCH_REGISTRY
11
+
12
+ if __name__ == '__main__':
13
+ parser = argparse.ArgumentParser()
14
+ parser.add_argument('-i', '--test_path', type=str, default='datasets/ffhq/ffhq_512')
15
+ parser.add_argument('-o', '--save_root', type=str, default='./results/vqgan_rec')
16
+ parser.add_argument('--codebook_size', type=int, default=1024)
17
+ parser.add_argument('--ckpt_path', type=str, default='./experiments/pretrained_models/vqgan/net_g.pth')
18
+ args = parser.parse_args()
19
+
20
+ if args.save_root.endswith('/'): # solve when path ends with /
21
+ args.save_root = args.save_root[:-1]
22
+ dir_name = os.path.abspath(args.save_root)
23
+ os.makedirs(dir_name, exist_ok=True)
24
+
25
+ device = torch.device('cuda' if torch.cuda.is_available() else 'cpu')
26
+ test_path = args.test_path
27
+ save_root = args.save_root
28
+ ckpt_path = args.ckpt_path
29
+ codebook_size = args.codebook_size
30
+
31
+ vqgan = ARCH_REGISTRY.get('VQAutoEncoder')(512, 64, [1, 2, 2, 4, 4, 8], 'nearest',
32
+ codebook_size=codebook_size).to(device)
33
+ checkpoint = torch.load(ckpt_path)['params_ema']
34
+
35
+ vqgan.load_state_dict(checkpoint)
36
+ vqgan.eval()
37
+
38
+ for img_path in sorted(glob.glob(os.path.join(test_path, '*.[jp][pn]g'))):
39
+ img_name = os.path.basename(img_path)
40
+ print(img_name)
41
+ img = cv2.imread(img_path)
42
+ img = img2tensor(img / 255., bgr2rgb=True, float32=True)
43
+ normalize(img, (0.5, 0.5, 0.5), (0.5, 0.5, 0.5), inplace=True)
44
+ img = img.unsqueeze(0).to(device)
45
+ with torch.no_grad():
46
+ output = vqgan(img)[0]
47
+ output = tensor2img(output, min_max=[-1,1])
48
+ img = tensor2img(img, min_max=[-1,1])
49
+ restored_img = np.concatenate([img, output], axis=1)
50
+ restored_img = output
51
+ del output
52
+ torch.cuda.empty_cache()
53
+
54
+ path = os.path.splitext(os.path.join(save_root, img_name))[0]
55
+ save_path = f'{path}.png'
56
+ imwrite(restored_img, save_path)
57
+
58
+ print(f'\nAll results are saved in {save_root}')
59
+
CodeFormer/web-demos/hugging_face/app.py ADDED
@@ -0,0 +1,283 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """
2
+ This file is used for deploying hugging face demo:
3
+ https://huggingface.co/spaces/sczhou/CodeFormer
4
+ """
5
+
6
+ import sys
7
+ sys.path.append('CodeFormer')
8
+ import os
9
+ import cv2
10
+ import torch
11
+ import torch.nn.functional as F
12
+ import gradio as gr
13
+
14
+ from torchvision.transforms.functional import normalize
15
+
16
+ from basicsr.archs.rrdbnet_arch import RRDBNet
17
+ from basicsr.utils import imwrite, img2tensor, tensor2img
18
+ from basicsr.utils.download_util import load_file_from_url
19
+ from basicsr.utils.misc import gpu_is_available, get_device
20
+ from basicsr.utils.realesrgan_utils import RealESRGANer
21
+ from basicsr.utils.registry import ARCH_REGISTRY
22
+
23
+ from facelib.utils.face_restoration_helper import FaceRestoreHelper
24
+ from facelib.utils.misc import is_gray
25
+
26
+
27
+ os.system("pip freeze")
28
+
29
+ pretrain_model_url = {
30
+ 'codeformer': 'https://github.com/sczhou/CodeFormer/releases/download/v0.1.0/codeformer.pth',
31
+ 'detection': 'https://github.com/sczhou/CodeFormer/releases/download/v0.1.0/detection_Resnet50_Final.pth',
32
+ 'parsing': 'https://github.com/sczhou/CodeFormer/releases/download/v0.1.0/parsing_parsenet.pth',
33
+ 'realesrgan': 'https://github.com/sczhou/CodeFormer/releases/download/v0.1.0/RealESRGAN_x2plus.pth'
34
+ }
35
+ # download weights
36
+ if not os.path.exists('CodeFormer/weights/CodeFormer/codeformer.pth'):
37
+ load_file_from_url(url=pretrain_model_url['codeformer'], model_dir='CodeFormer/weights/CodeFormer', progress=True, file_name=None)
38
+ if not os.path.exists('CodeFormer/weights/facelib/detection_Resnet50_Final.pth'):
39
+ load_file_from_url(url=pretrain_model_url['detection'], model_dir='CodeFormer/weights/facelib', progress=True, file_name=None)
40
+ if not os.path.exists('CodeFormer/weights/facelib/parsing_parsenet.pth'):
41
+ load_file_from_url(url=pretrain_model_url['parsing'], model_dir='CodeFormer/weights/facelib', progress=True, file_name=None)
42
+ if not os.path.exists('CodeFormer/weights/realesrgan/RealESRGAN_x2plus.pth'):
43
+ load_file_from_url(url=pretrain_model_url['realesrgan'], model_dir='CodeFormer/weights/realesrgan', progress=True, file_name=None)
44
+
45
+ # download images
46
+ torch.hub.download_url_to_file(
47
+ 'https://replicate.com/api/models/sczhou/codeformer/files/fa3fe3d1-76b0-4ca8-ac0d-0a925cb0ff54/06.png',
48
+ '01.png')
49
+ torch.hub.download_url_to_file(
50
+ 'https://replicate.com/api/models/sczhou/codeformer/files/a1daba8e-af14-4b00-86a4-69cec9619b53/04.jpg',
51
+ '02.jpg')
52
+ torch.hub.download_url_to_file(
53
+ 'https://replicate.com/api/models/sczhou/codeformer/files/542d64f9-1712-4de7-85f7-3863009a7c3d/03.jpg',
54
+ '03.jpg')
55
+ torch.hub.download_url_to_file(
56
+ 'https://replicate.com/api/models/sczhou/codeformer/files/a11098b0-a18a-4c02-a19a-9a7045d68426/010.jpg',
57
+ '04.jpg')
58
+ torch.hub.download_url_to_file(
59
+ 'https://replicate.com/api/models/sczhou/codeformer/files/7cf19c2c-e0cf-4712-9af8-cf5bdbb8d0ee/012.jpg',
60
+ '05.jpg')
61
+
62
+ def imread(img_path):
63
+ img = cv2.imread(img_path)
64
+ img = cv2.cvtColor(img, cv2.COLOR_BGR2RGB)
65
+ return img
66
+
67
+ # set enhancer with RealESRGAN
68
+ def set_realesrgan():
69
+ # half = True if torch.cuda.is_available() else False
70
+ half = True if gpu_is_available() else False
71
+ model = RRDBNet(
72
+ num_in_ch=3,
73
+ num_out_ch=3,
74
+ num_feat=64,
75
+ num_block=23,
76
+ num_grow_ch=32,
77
+ scale=2,
78
+ )
79
+ upsampler = RealESRGANer(
80
+ scale=2,
81
+ model_path="CodeFormer/weights/realesrgan/RealESRGAN_x2plus.pth",
82
+ model=model,
83
+ tile=400,
84
+ tile_pad=40,
85
+ pre_pad=0,
86
+ half=half,
87
+ )
88
+ return upsampler
89
+
90
+ upsampler = set_realesrgan()
91
+ # device = torch.device('cuda' if torch.cuda.is_available() else 'cpu')
92
+ device = get_device()
93
+ codeformer_net = ARCH_REGISTRY.get("CodeFormer")(
94
+ dim_embd=512,
95
+ codebook_size=1024,
96
+ n_head=8,
97
+ n_layers=9,
98
+ connect_list=["32", "64", "128", "256"],
99
+ ).to(device)
100
+ ckpt_path = "CodeFormer/weights/CodeFormer/codeformer.pth"
101
+ checkpoint = torch.load(ckpt_path)["params_ema"]
102
+ codeformer_net.load_state_dict(checkpoint)
103
+ codeformer_net.eval()
104
+
105
+ os.makedirs('output', exist_ok=True)
106
+
107
+ def inference(image, background_enhance, face_upsample, upscale, codeformer_fidelity):
108
+ """Run a single prediction on the model"""
109
+ try: # global try
110
+ # take the default setting for the demo
111
+ has_aligned = False
112
+ only_center_face = False
113
+ draw_box = False
114
+ detection_model = "retinaface_resnet50"
115
+ print('Inp:', image, background_enhance, face_upsample, upscale, codeformer_fidelity)
116
+
117
+ img = cv2.imread(str(image), cv2.IMREAD_COLOR)
118
+ print('\timage size:', img.shape)
119
+
120
+ upscale = int(upscale) # convert type to int
121
+ if upscale > 4: # avoid memory exceeded due to too large upscale
122
+ upscale = 4
123
+ if upscale > 2 and max(img.shape[:2])>1000: # avoid memory exceeded due to too large img resolution
124
+ upscale = 2
125
+ if max(img.shape[:2]) > 1500: # avoid memory exceeded due to too large img resolution
126
+ upscale = 1
127
+ background_enhance = False
128
+ face_upsample = False
129
+
130
+ face_helper = FaceRestoreHelper(
131
+ upscale,
132
+ face_size=512,
133
+ crop_ratio=(1, 1),
134
+ det_model=detection_model,
135
+ save_ext="png",
136
+ use_parse=True,
137
+ device=device,
138
+ )
139
+ bg_upsampler = upsampler if background_enhance else None
140
+ face_upsampler = upsampler if face_upsample else None
141
+
142
+ if has_aligned:
143
+ # the input faces are already cropped and aligned
144
+ img = cv2.resize(img, (512, 512), interpolation=cv2.INTER_LINEAR)
145
+ face_helper.is_gray = is_gray(img, threshold=5)
146
+ if face_helper.is_gray:
147
+ print('\tgrayscale input: True')
148
+ face_helper.cropped_faces = [img]
149
+ else:
150
+ face_helper.read_image(img)
151
+ # get face landmarks for each face
152
+ num_det_faces = face_helper.get_face_landmarks_5(
153
+ only_center_face=only_center_face, resize=640, eye_dist_threshold=5
154
+ )
155
+ print(f'\tdetect {num_det_faces} faces')
156
+ # align and warp each face
157
+ face_helper.align_warp_face()
158
+
159
+ # face restoration for each cropped face
160
+ for idx, cropped_face in enumerate(face_helper.cropped_faces):
161
+ # prepare data
162
+ cropped_face_t = img2tensor(
163
+ cropped_face / 255.0, bgr2rgb=True, float32=True
164
+ )
165
+ normalize(cropped_face_t, (0.5, 0.5, 0.5), (0.5, 0.5, 0.5), inplace=True)
166
+ cropped_face_t = cropped_face_t.unsqueeze(0).to(device)
167
+
168
+ try:
169
+ with torch.no_grad():
170
+ output = codeformer_net(
171
+ cropped_face_t, w=codeformer_fidelity, adain=True
172
+ )[0]
173
+ restored_face = tensor2img(output, rgb2bgr=True, min_max=(-1, 1))
174
+ del output
175
+ torch.cuda.empty_cache()
176
+ except RuntimeError as error:
177
+ print(f"Failed inference for CodeFormer: {error}")
178
+ restored_face = tensor2img(
179
+ cropped_face_t, rgb2bgr=True, min_max=(-1, 1)
180
+ )
181
+
182
+ restored_face = restored_face.astype("uint8")
183
+ face_helper.add_restored_face(restored_face)
184
+
185
+ # paste_back
186
+ if not has_aligned:
187
+ # upsample the background
188
+ if bg_upsampler is not None:
189
+ # Now only support RealESRGAN for upsampling background
190
+ bg_img = bg_upsampler.enhance(img, outscale=upscale)[0]
191
+ else:
192
+ bg_img = None
193
+ face_helper.get_inverse_affine(None)
194
+ # paste each restored face to the input image
195
+ if face_upsample and face_upsampler is not None:
196
+ restored_img = face_helper.paste_faces_to_input_image(
197
+ upsample_img=bg_img,
198
+ draw_box=draw_box,
199
+ face_upsampler=face_upsampler,
200
+ )
201
+ else:
202
+ restored_img = face_helper.paste_faces_to_input_image(
203
+ upsample_img=bg_img, draw_box=draw_box
204
+ )
205
+
206
+ # save restored img
207
+ save_path = f'output/out.png'
208
+ imwrite(restored_img, str(save_path))
209
+
210
+ restored_img = cv2.cvtColor(restored_img, cv2.COLOR_BGR2RGB)
211
+ return restored_img, save_path
212
+ except Exception as error:
213
+ print('Global exception', error)
214
+ return None, None
215
+
216
+
217
+ title = "CodeFormer: Robust Face Restoration and Enhancement Network"
218
+ description = r"""<center><img src='https://user-images.githubusercontent.com/14334509/189166076-94bb2cac-4f4e-40fb-a69f-66709e3d98f5.png' alt='CodeFormer logo'></center>
219
+ <b>Official Gradio demo</b> for <a href='https://github.com/sczhou/CodeFormer' target='_blank'><b>Towards Robust Blind Face Restoration with Codebook Lookup Transformer (NeurIPS 2022)</b></a>.<br>
220
+ 🔥 CodeFormer is a robust face restoration algorithm for old photos or AI-generated faces.<br>
221
+ 🤗 Try CodeFormer for improved stable-diffusion generation!<br>
222
+ """
223
+ article = r"""
224
+ If CodeFormer is helpful, please help to ⭐ the <a href='https://github.com/sczhou/CodeFormer' target='_blank'>Github Repo</a>. Thanks!
225
+ [![GitHub Stars](https://img.shields.io/github/stars/sczhou/CodeFormer?style=social)](https://github.com/sczhou/CodeFormer)
226
+
227
+ ---
228
+
229
+ 📝 **Citation**
230
+
231
+ If our work is useful for your research, please consider citing:
232
+ ```bibtex
233
+ @inproceedings{zhou2022codeformer,
234
+ author = {Zhou, Shangchen and Chan, Kelvin C.K. and Li, Chongyi and Loy, Chen Change},
235
+ title = {Towards Robust Blind Face Restoration with Codebook Lookup TransFormer},
236
+ booktitle = {NeurIPS},
237
+ year = {2022}
238
+ }
239
+ ```
240
+
241
+ 📋 **License**
242
+
243
+ This project is licensed under <a rel="license" href="https://github.com/sczhou/CodeFormer/blob/master/LICENSE">S-Lab License 1.0</a>.
244
+ Redistribution and use for non-commercial purposes should follow this license.
245
+
246
+ �� **Contact**
247
+
248
+ If you have any questions, please feel free to reach me out at <b>[email protected]</b>.
249
+
250
+ <div>
251
+ 🤗 Find Me:
252
+ <a href="https://twitter.com/ShangchenZhou"><img style="margin-top:0.5em; margin-bottom:0.5em" src="https://img.shields.io/twitter/follow/ShangchenZhou?label=%40ShangchenZhou&style=social" alt="Twitter Follow"></a>
253
+ <a href="https://github.com/sczhou"><img style="margin-top:0.5em; margin-bottom:2em" src="https://img.shields.io/github/followers/sczhou?style=social" alt="Github Follow"></a>
254
+ </div>
255
+
256
+ <center><img src='https://visitor-badge-sczhou.glitch.me/badge?page_id=sczhou/CodeFormer' alt='visitors'></center>
257
+ """
258
+
259
+ demo = gr.Interface(
260
+ inference, [
261
+ gr.inputs.Image(type="filepath", label="Input"),
262
+ gr.inputs.Checkbox(default=True, label="Background_Enhance"),
263
+ gr.inputs.Checkbox(default=True, label="Face_Upsample"),
264
+ gr.inputs.Number(default=2, label="Rescaling_Factor (up to 4)"),
265
+ gr.Slider(0, 1, value=0.5, step=0.01, label='Codeformer_Fidelity (0 for better quality, 1 for better identity)')
266
+ ], [
267
+ gr.outputs.Image(type="numpy", label="Output"),
268
+ gr.outputs.File(label="Download the output")
269
+ ],
270
+ title=title,
271
+ description=description,
272
+ article=article,
273
+ examples=[
274
+ ['01.png', True, True, 2, 0.7],
275
+ ['02.jpg', True, True, 2, 0.7],
276
+ ['03.jpg', True, True, 2, 0.7],
277
+ ['04.jpg', True, True, 2, 0.1],
278
+ ['05.jpg', True, True, 2, 0.1]
279
+ ]
280
+ )
281
+
282
+ demo.queue(concurrency_count=2)
283
+ demo.launch()
CodeFormer/web-demos/replicate/cog.yaml ADDED
@@ -0,0 +1,30 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """
2
+ This file is used for deploying replicate demo:
3
+ https://replicate.com/sczhou/codeformer
4
+ """
5
+
6
+ build:
7
+ gpu: true
8
+ cuda: "11.3"
9
+ python_version: "3.8"
10
+ system_packages:
11
+ - "libgl1-mesa-glx"
12
+ - "libglib2.0-0"
13
+ python_packages:
14
+ - "ipython==8.4.0"
15
+ - "future==0.18.2"
16
+ - "lmdb==1.3.0"
17
+ - "scikit-image==0.19.3"
18
+ - "torch==1.11.0 --extra-index-url=https://download.pytorch.org/whl/cu113"
19
+ - "torchvision==0.12.0 --extra-index-url=https://download.pytorch.org/whl/cu113"
20
+ - "scipy==1.9.0"
21
+ - "gdown==4.5.1"
22
+ - "pyyaml==6.0"
23
+ - "tb-nightly==2.11.0a20220906"
24
+ - "tqdm==4.64.1"
25
+ - "yapf==0.32.0"
26
+ - "lpips==0.1.4"
27
+ - "Pillow==9.2.0"
28
+ - "opencv-python==4.6.0.66"
29
+
30
+ predict: "predict.py:Predictor"
CodeFormer/web-demos/replicate/predict.py ADDED
@@ -0,0 +1,191 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """
2
+ This file is used for deploying replicate demo:
3
+ https://replicate.com/sczhou/codeformer
4
+ running: cog predict -i image=@inputs/whole_imgs/04.jpg -i codeformer_fidelity=0.5 -i upscale=2
5
+ push: cog push r8.im/sczhou/codeformer
6
+ """
7
+
8
+ import tempfile
9
+ import cv2
10
+ import torch
11
+ from torchvision.transforms.functional import normalize
12
+ try:
13
+ from cog import BasePredictor, Input, Path
14
+ except Exception:
15
+ print('please install cog package')
16
+
17
+ from basicsr.archs.rrdbnet_arch import RRDBNet
18
+ from basicsr.utils import imwrite, img2tensor, tensor2img
19
+ from basicsr.utils.realesrgan_utils import RealESRGANer
20
+ from basicsr.utils.misc import gpu_is_available
21
+ from basicsr.utils.registry import ARCH_REGISTRY
22
+
23
+ from facelib.utils.face_restoration_helper import FaceRestoreHelper
24
+
25
+ class Predictor(BasePredictor):
26
+ def setup(self):
27
+ """Load the model into memory to make running multiple predictions efficient"""
28
+ self.device = "cuda:0"
29
+ self.upsampler = set_realesrgan()
30
+ self.net = ARCH_REGISTRY.get("CodeFormer")(
31
+ dim_embd=512,
32
+ codebook_size=1024,
33
+ n_head=8,
34
+ n_layers=9,
35
+ connect_list=["32", "64", "128", "256"],
36
+ ).to(self.device)
37
+ ckpt_path = "weights/CodeFormer/codeformer.pth"
38
+ checkpoint = torch.load(ckpt_path)[
39
+ "params_ema"
40
+ ] # update file permission if cannot load
41
+ self.net.load_state_dict(checkpoint)
42
+ self.net.eval()
43
+
44
+ def predict(
45
+ self,
46
+ image: Path = Input(description="Input image"),
47
+ codeformer_fidelity: float = Input(
48
+ default=0.5,
49
+ ge=0,
50
+ le=1,
51
+ description="Balance the quality (lower number) and fidelity (higher number).",
52
+ ),
53
+ background_enhance: bool = Input(
54
+ description="Enhance background image with Real-ESRGAN", default=True
55
+ ),
56
+ face_upsample: bool = Input(
57
+ description="Upsample restored faces for high-resolution AI-created images",
58
+ default=True,
59
+ ),
60
+ upscale: int = Input(
61
+ description="The final upsampling scale of the image",
62
+ default=2,
63
+ ),
64
+ ) -> Path:
65
+ """Run a single prediction on the model"""
66
+
67
+ # take the default setting for the demo
68
+ has_aligned = False
69
+ only_center_face = False
70
+ draw_box = False
71
+ detection_model = "retinaface_resnet50"
72
+
73
+ self.face_helper = FaceRestoreHelper(
74
+ upscale,
75
+ face_size=512,
76
+ crop_ratio=(1, 1),
77
+ det_model=detection_model,
78
+ save_ext="png",
79
+ use_parse=True,
80
+ device=self.device,
81
+ )
82
+
83
+ bg_upsampler = self.upsampler if background_enhance else None
84
+ face_upsampler = self.upsampler if face_upsample else None
85
+
86
+ img = cv2.imread(str(image), cv2.IMREAD_COLOR)
87
+
88
+ if has_aligned:
89
+ # the input faces are already cropped and aligned
90
+ img = cv2.resize(img, (512, 512), interpolation=cv2.INTER_LINEAR)
91
+ self.face_helper.cropped_faces = [img]
92
+ else:
93
+ self.face_helper.read_image(img)
94
+ # get face landmarks for each face
95
+ num_det_faces = self.face_helper.get_face_landmarks_5(
96
+ only_center_face=only_center_face, resize=640, eye_dist_threshold=5
97
+ )
98
+ print(f"\tdetect {num_det_faces} faces")
99
+ # align and warp each face
100
+ self.face_helper.align_warp_face()
101
+
102
+ # face restoration for each cropped face
103
+ for idx, cropped_face in enumerate(self.face_helper.cropped_faces):
104
+ # prepare data
105
+ cropped_face_t = img2tensor(
106
+ cropped_face / 255.0, bgr2rgb=True, float32=True
107
+ )
108
+ normalize(cropped_face_t, (0.5, 0.5, 0.5), (0.5, 0.5, 0.5), inplace=True)
109
+ cropped_face_t = cropped_face_t.unsqueeze(0).to(self.device)
110
+
111
+ try:
112
+ with torch.no_grad():
113
+ output = self.net(
114
+ cropped_face_t, w=codeformer_fidelity, adain=True
115
+ )[0]
116
+ restored_face = tensor2img(output, rgb2bgr=True, min_max=(-1, 1))
117
+ del output
118
+ torch.cuda.empty_cache()
119
+ except Exception as error:
120
+ print(f"\tFailed inference for CodeFormer: {error}")
121
+ restored_face = tensor2img(
122
+ cropped_face_t, rgb2bgr=True, min_max=(-1, 1)
123
+ )
124
+
125
+ restored_face = restored_face.astype("uint8")
126
+ self.face_helper.add_restored_face(restored_face)
127
+
128
+ # paste_back
129
+ if not has_aligned:
130
+ # upsample the background
131
+ if bg_upsampler is not None:
132
+ # Now only support RealESRGAN for upsampling background
133
+ bg_img = bg_upsampler.enhance(img, outscale=upscale)[0]
134
+ else:
135
+ bg_img = None
136
+ self.face_helper.get_inverse_affine(None)
137
+ # paste each restored face to the input image
138
+ if face_upsample and face_upsampler is not None:
139
+ restored_img = self.face_helper.paste_faces_to_input_image(
140
+ upsample_img=bg_img,
141
+ draw_box=draw_box,
142
+ face_upsampler=face_upsampler,
143
+ )
144
+ else:
145
+ restored_img = self.face_helper.paste_faces_to_input_image(
146
+ upsample_img=bg_img, draw_box=draw_box
147
+ )
148
+
149
+ # save restored img
150
+ out_path = Path(tempfile.mkdtemp()) / 'output.png'
151
+ imwrite(restored_img, str(out_path))
152
+
153
+ return out_path
154
+
155
+
156
+ def imread(img_path):
157
+ img = cv2.imread(img_path)
158
+ img = cv2.cvtColor(img, cv2.COLOR_BGR2RGB)
159
+ return img
160
+
161
+
162
+ def set_realesrgan():
163
+ # if not torch.cuda.is_available(): # CPU
164
+ if not gpu_is_available(): # CPU
165
+ import warnings
166
+
167
+ warnings.warn(
168
+ "The unoptimized RealESRGAN is slow on CPU. We do not use it. "
169
+ "If you really want to use it, please modify the corresponding codes.",
170
+ category=RuntimeWarning,
171
+ )
172
+ upsampler = None
173
+ else:
174
+ model = RRDBNet(
175
+ num_in_ch=3,
176
+ num_out_ch=3,
177
+ num_feat=64,
178
+ num_block=23,
179
+ num_grow_ch=32,
180
+ scale=2,
181
+ )
182
+ upsampler = RealESRGANer(
183
+ scale=2,
184
+ model_path="./weights/realesrgan/RealESRGAN_x2plus.pth",
185
+ model=model,
186
+ tile=400,
187
+ tile_pad=40,
188
+ pre_pad=0,
189
+ half=True,
190
+ )
191
+ return upsampler