├── .gitignore
├── LICENSE
├── README.md
├── configs
├── __init__.py
├── data_configs.py
├── paths_config.py
└── transforms_config.py
├── criteria
├── .ipynb_checkpoints
│ └── id_loss-checkpoint.py
├── __init__.py
├── id_loss.py
├── lpips
│ ├── __init__.py
│ ├── lpips.py
│ ├── networks.py
│ └── utils.py
├── moco_loss.py
└── w_norm.py
├── demo.py
├── docs
├── custom-color-edits.png
├── prog-synthesis.png
└── watercolor-synthesis.png
├── environment
└── paint2pix_env.yml
├── input-images
├── 143.jpg
├── 20.jpg
├── 214.jpg
├── 262.jpg
└── 823.jpg
├── licenses
├── LICENSE_S-aiueo32
├── LICENSE_TreB1eN
├── LICENSE_alaluf
├── LICENSE_eladrich
├── LICENSE_lessw2020
├── LICENSE_omertov
└── LICENSE_rosinality
├── models
├── .ipynb_checkpoints
│ └── e4e-checkpoint.py
├── __init__.py
├── e4e.py
├── e4e_modules
│ ├── __init__.py
│ ├── discriminator.py
│ └── latent_codes_pool.py
├── encoders
│ ├── .ipynb_checkpoints
│ │ ├── map2style-checkpoint.py
│ │ └── restyle_e4e_encoders-checkpoint.py
│ ├── __init__.py
│ ├── fpn_encoders.py
│ ├── helpers.py
│ ├── map2style.py
│ ├── model_irse.py
│ ├── restyle_e4e_encoders.py
│ └── restyle_psp_encoders.py
├── mtcnn
│ ├── __init__.py
│ ├── mtcnn.py
│ └── mtcnn_pytorch
│ │ ├── __init__.py
│ │ └── src
│ │ ├── __init__.py
│ │ ├── align_trans.py
│ │ ├── box_utils.py
│ │ ├── detector.py
│ │ ├── first_stage.py
│ │ ├── get_nets.py
│ │ ├── matlab_cp2tform.py
│ │ ├── visualization_utils.py
│ │ └── weights
│ │ ├── onet.npy
│ │ ├── pnet.npy
│ │ └── rnet.npy
├── psp.py
└── stylegan2
│ ├── .ipynb_checkpoints
│ └── model-checkpoint.py
│ ├── __init__.py
│ ├── model.py
│ └── op
│ ├── __init__.py
│ ├── fused_act.py
│ ├── fused_bias_act.cpp
│ ├── fused_bias_act_kernel.cu
│ ├── upfirdn2d.cpp
│ ├── upfirdn2d.py
│ └── upfirdn2d_kernel.cu
├── output
├── result_0.png
└── result_mask_0.png
├── predict.py
└── utils
├── .ipynb_checkpoints
├── id_utils-checkpoint.py
└── inference_utils-checkpoint.py
├── __init__.py
├── common.py
├── data_utils.py
├── id_utils.py
├── inference_utils.py
├── model_utils.py
└── train_utils.py
/.gitignore:
--------------------------------------------------------------------------------
1 | notebooks
2 | data
3 | face_seg
4 | intellipaint
5 | files
6 | __pycache__
7 | outputs
8 | pretrained_models
9 | *.dat
--------------------------------------------------------------------------------
/LICENSE:
--------------------------------------------------------------------------------
1 | MIT License
2 |
3 | Copyright (c) 2022 Jaskirat Singh
4 |
5 | Permission is hereby granted, free of charge, to any person obtaining a copy
6 | of this software and associated documentation files (the "Software"), to deal
7 | in the Software without restriction, including without limitation the rights
8 | to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9 | copies of the Software, and to permit persons to whom the Software is
10 | furnished to do so, subject to the following conditions:
11 |
12 | The above copyright notice and this permission notice shall be included in all
13 | copies or substantial portions of the Software.
14 |
15 | THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16 | IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17 | FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18 | AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19 | LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20 | OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21 | SOFTWARE.
22 |
--------------------------------------------------------------------------------
/README.md:
--------------------------------------------------------------------------------
1 | # Paint2Pix: Interactive Painting based Progressive Image Synthesis and Editing (ECCV 2022)
2 |
3 | > Jaskirat Singh, Liang Zheng, Cameron Smith, Jose Echevarria
4 | >
5 | > Controllable image synthesis with user scribbles is a topic of keen interest in the computer vision community. In this paper, for the first time we study the problem of photorealistic image synthesis from incomplete and primitive human paintings. In particular, we propose a novel approach paint2pix, which learns to predict (and adapt) “what a user wants to draw” from rudimentary brushstroke inputs, by learning a mapping from the manifold of incomplete human paintings to their realistic renderings. When used in conjunction with recent works in autonomous painting agents, we show that paint2pix can be used for progressive image synthesis from scratch. During this process, paint2pix allows a novice user to progressively synthesize the desired image output, while requiring just few coarse user scribbles to accurately steer the trajectory of the synthesis process. Furthermore, we find that our approach also forms a surprisingly convenient approach for real image editing, and allows the user to perform a diverse range of custom fine-grained edits through the addition of only a few well-placed brushstrokes.
6 |
7 |
8 |
9 |
10 |
11 |
12 |
13 |
14 |
15 |
16 |
17 |
18 |
19 | We propose paint2pix which helps the user directly express his/her ideas in visual form by learning to predict user-intention from a few rudimentary brushstrokes. The proposed approach can be used for (a) synthesizing a desired image output directly from scratch
20 | wherein it allows the user to control the overall synthesis trajectory using just few coarse brushstrokes (blue arrows) at key points,
21 | or, (b) performing a diverse range of custom edits directly on real image inputs.
22 |
23 |
24 | ## Description
25 | Official implementation of our Paint2pix paper with streamlit demo. By using autonomous painting agents as a proxy for the human painting process, Paint2pix learns to predict *user-intention* ("what a user wants to draw") from fairly rudimentary paintings and user-scribbles.
26 |
27 | ## Updates
28 |
29 | * **(19/08/22)** Our [project demo](http://exposition.cecs.anu.edu.au:6009/) is online. Try generating amazing artwork or realistic image media right from your browser!
30 |
31 | https://user-images.githubusercontent.com/25987491/185323657-a71c239c-892c-4202-b753-a84c0bf19a30.mp4
32 |
33 |
34 |
35 |
36 |
37 | ## Table of Contents
38 | - [Getting Started](#getting-started)
39 | * [Prerequisites](#prerequisites)
40 | * [Installation](#installation)
41 | - [Pretrained Models](#pretrained-models)
42 | * [Paint2pix models](#paint2pix-models)
43 | - [Using the Demo](#using-the-demo)
44 | - [Example Results](#example-results)
45 | * [Progressive Image Synthesis](#progressive-image-synthesis)
46 | * [Real Image Editing](#real-image-editing)
47 | * [Artistic Content Generation](#artistic-content-generation)
48 | - [Acknowledgments](#acknowledgments)
49 | - [Citation](#citation)
50 |
51 | Table of contents generated with markdown-toc
52 |
53 |
54 |
55 | ## Getting Started
56 | ### Prerequisites
57 | - Linux or macOS
58 | - NVIDIA GPU + CUDA CuDNN (CPU may be possible with some modifications, but is not inherently supported)
59 | - Python 3
60 | - Tested on Ubuntu 20.04, Nvidia RTX 3090 and CUDA 11.5
61 |
62 | ### Installation
63 | - Dependencies:
64 | We recommend running this repository using [Anaconda](https://docs.anaconda.com/anaconda/install/).
65 | All dependencies for defining the environment are provided in `environment/paint2pix_env.yaml`.
66 |
67 | ## Pretrained Models
68 | Please download the following pretrained models essential for running the provided demo.
69 |
70 | ### Paint2pix models
71 | | Path | Description
72 | | :--- | :----------
73 | |[Canvas Encoder - ReStyle](https://drive.google.com/file/d/1ufKEtDXEG6o96KjLh-i6EL7Ir9TlwPcs/view?usp=sharing) | Paint2pix Canvas Encoder trained with a ReStyle architecture.
74 | |[Identity Encoder - ReStyle](https://drive.google.com/file/d/1KT3YmSHgMJM3b7Ox9zciyo3FSELtJsyS/view?usp=sharing) | Paint2pix Identity Encoder trained with a ReStyle architecture.
75 | |[StyleGAN - Watercolor Painting](https://drive.google.com/file/d/1WW_a589lv7R9-PNvKlVkVxITIZnW7xlv/view?usp=sharing) | StyleGAN decoder network trained to generate watercolor paintings. Used for artistic content generation with paint2pix.
76 | |[IR-SE50 Model](https://drive.google.com/file/d/1U4q_o20uGMozSetOkMGddUcAWf_ons2-/view?usp=sharing) | Pretrained IR-SE50 model taken from [TreB1eN](https://github.com/TreB1eN/InsightFace_Pytorch) for use in ID loss and id-encoder training.
77 |
78 |
79 | Please download and save the above models to the directory `pretrained_models`.
80 |
81 |
82 | ## Using the Demo
83 |
84 | We provide a streamlit-drawble canvas based demo for trying out different features of the Paint2pix model. To start the demo use,
85 |
86 | ```
87 | CUDA_VISIBLE_DEVICES=2 streamlit run demo.py --server.port 6009
88 | ```
89 |
90 | The demo can then be accessed on the local machine or ssh client via [localhost](http://localhost:6009).
91 |
92 | The demo has been divided into 3 convenient sections:
93 |
94 | 1. **Real Image Editing**: Allows the user to edit real images using coarse user scribbles
95 | 2. **Progressive Image Synthesis**: Start from an empty canvas and design your desired image output using just coarse scribbles.
96 | 3. **Artistic Content Generation**: Unleash your inner artist! create highly artistic portraits using just coarse scribbles.
97 |
98 |
99 | ## Example Results
100 |
101 | ### Progressive Image Synthesis
102 |
103 |
104 |
105 |
106 | Paint2pix for progressive image synthesis
107 |
108 |
109 | ### Real Image Editing
110 |
111 |
112 |
113 |
114 | Paint2pix for achieving diverse custom real-image edits
115 |
116 |
117 | ### Artistic Content Generation
118 |
119 |
120 |
121 |
122 |
123 | Paint2pix for generating highly artistic content using coarse scribbles
124 |
125 |
126 | ## Acknowledgments
127 | This code borrows heavily from [pixel2style2pixel](https://github.com/eladrich/pixel2style2pixel),
128 | [encoder4editing](https://github.com/omertov/encoder4editing) and [restyle-encoder](https://github.com/yuval-alaluf/restyle-encoder).
129 |
130 | ## Citation
131 | If you use this code for your research, please cite the following works:
132 | ```
133 | @inproceedings{singh2022paint2pix,
134 | title={Paint2Pix: Interactive Painting based Progressive
135 | Image Synthesis and Editing},
136 | author={Singh, Jaskirat and Zheng, Liang and Smith, Cameron and Echevarria, Jose},
137 | booktitle={European conference on computer vision},
138 | year={2022},
139 | organization={Springer}
140 | }
141 | ```
142 | ```
143 | @inproceedings{singh2022intelli,
144 | title={Intelli-Paint: Towards Developing Human-like Painting Agents},
145 | author={Singh, Jaskirat and Smith, Cameron and Echevarria, Jose and Zheng, Liang},
146 | booktitle={European conference on computer vision},
147 | year={2022},
148 | organization={Springer}
149 | }
150 | ```
151 |
152 |
--------------------------------------------------------------------------------
/configs/__init__.py:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/1jsingh/paint2pix/971d1ea06ef6cbcc555ad09a365bf1621ce13f08/configs/__init__.py
--------------------------------------------------------------------------------
/configs/data_configs.py:
--------------------------------------------------------------------------------
1 | from configs import transforms_config
2 | from configs.paths_config import dataset_paths
3 |
4 |
5 | DATASETS = {
6 | 'ffhq_encode': {
7 | 'transforms': transforms_config.EncodeTransforms,
8 | 'train_source_root': dataset_paths['ffhq'],
9 | 'train_target_root': dataset_paths['ffhq'],
10 | 'test_source_root': dataset_paths['celeba_test'],
11 | 'test_target_root': dataset_paths['celeba_test']
12 | },
13 | "cars_encode_prev": {
14 | 'transforms': transforms_config.CarsEncodeTransforms,
15 | 'train_source_root': dataset_paths['cars_train'],
16 | 'train_target_root': dataset_paths['cars_train'],
17 | 'test_source_root': dataset_paths['cars_test'],
18 | 'test_target_root': dataset_paths['cars_test']
19 | },
20 | "church_encode": {
21 | 'transforms': transforms_config.EncodeTransforms,
22 | 'train_source_root': dataset_paths['church_train'],
23 | 'train_target_root': dataset_paths['church_train'],
24 | 'test_source_root': dataset_paths['church_test'],
25 | 'test_target_root': dataset_paths['church_test']
26 | },
27 | "horse_encode": {
28 | 'transforms': transforms_config.EncodeTransforms,
29 | 'train_source_root': dataset_paths['horse_train'],
30 | 'train_target_root': dataset_paths['horse_train'],
31 | 'test_source_root': dataset_paths['horse_test'],
32 | 'test_target_root': dataset_paths['horse_test']
33 | },
34 | "afhq_wild_encode": {
35 | 'transforms': transforms_config.EncodeTransforms,
36 | 'train_source_root': dataset_paths['afhq_wild_train'],
37 | 'train_target_root': dataset_paths['afhq_wild_train'],
38 | 'test_source_root': dataset_paths['afhq_wild_test'],
39 | 'test_target_root': dataset_paths['afhq_wild_test']
40 | },
41 | "toonify": {
42 | 'transforms': transforms_config.EncodeTransforms,
43 | 'train_source_root': dataset_paths['ffhq'],
44 | 'train_target_root': dataset_paths['ffhq'],
45 | 'test_source_root': dataset_paths['celeba_test'],
46 | 'test_target_root': dataset_paths['celeba_test']
47 | },
48 | 'paint_ffhq_encode': {
49 | 'transforms': transforms_config.EncodeTransforms,
50 | 'train_source_root': dataset_paths['paint_train_source_ffhq'],
51 | 'train_target_root': dataset_paths['paint_train_target_ffhq'],
52 | 'test_source_root': dataset_paths['paint_test_source_ffhq'],
53 | 'test_target_root': dataset_paths['paint_test_target_ffhq'],
54 | },
55 | 'paint_ffhq_encode2': {
56 | 'transforms': transforms_config.EncodeTransforms,
57 | 'train_source_root': dataset_paths['paint_train_source_ffhq2'],
58 | 'train_target_root': dataset_paths['paint_train_target_ffhq2'],
59 | 'test_source_root': dataset_paths['paint_test_source_ffhq2'],
60 | 'test_target_root': dataset_paths['paint_test_target_ffhq2'],
61 | },
62 | 'paint_ffhq_encode_id': {
63 | 'transforms': transforms_config.EncodeTransforms,
64 | 'train_source_root': dataset_paths['paint_train_target_ffhq2'],
65 | 'train_target_root': dataset_paths['paint_train_source_ffhq2'],
66 | 'test_source_root': dataset_paths['paint_test_target_ffhq2'],
67 | 'test_target_root': dataset_paths['paint_test_source_ffhq2'],
68 | },
69 | 'cars_encode': {
70 | 'transforms': transforms_config.CarsEncodeTransforms,
71 | 'train_source_root': dataset_paths['paint_train_source'],
72 | 'train_target_root': dataset_paths['paint_train_target'],
73 | 'test_source_root': dataset_paths['paint_test_source'],
74 | 'test_target_root': dataset_paths['paint_test_target'],
75 | },
76 | }
--------------------------------------------------------------------------------
/configs/paths_config.py:
--------------------------------------------------------------------------------
1 | dataset_paths = {
2 | 'celeba': '',
3 | 'celeba_test': '',
4 |
5 | 'cars_train': '',
6 | 'cars_test': '',
7 |
8 | 'church_train': '',
9 | 'church_test': '',
10 |
11 | 'horse_train': '',
12 | 'horse_test': '',
13 |
14 | 'afhq_wild_train': '',
15 | 'afhq_wild_test': '',
16 |
17 | # Painting completion ffhq
18 | 'paint_train_source_ffhq': 'data/celeba/intelli-paint/train/painting',
19 | 'paint_train_target_ffhq': 'data/celeba/intelli-paint/train/target',
20 | 'paint_test_source_ffhq': 'data/celeba/intelli-paint/test/painting',
21 | 'paint_test_target_ffhq': 'data/celeba/intelli-paint/test/target',
22 |
23 | # Painting completion cars
24 | 'paint_train_source': 'data/intelli-paint/train/painting',
25 | 'paint_train_target': 'data/intelli-paint/train/target',
26 | 'paint_test_source': 'data/intelli-paint/test/painting',
27 | 'paint_test_target': 'data/intelli-paint/test/target',
28 | }
29 |
30 | model_paths = {
31 | 'ir_se50': 'pretrained_models/model_ir_se50.pth',
32 | 'resnet34': 'pretrained_models/resnet34-333f7ec4.pth',
33 | 'stylegan_celeba': 'pretrained_models/stylegan2-celeba-config-f.pt',
34 | 'stylegan_cars': 'pretrained_models/stylegan2-car-config-f.pt',
35 | 'stylegan_church': 'pretrained_models/stylegan2-church-config-f.pt',
36 | 'stylegan_horse': 'pretrained_models/stylegan2-horse-config-f.pt',
37 | 'stylegan_ada_wild': 'pretrained_models/afhqwild.pt',
38 | 'stylegan_toonify': 'pretrained_models/celeba_cartoon_blended.pt',
39 | 'shape_predictor': 'pretrained_models/shape_predictor_68_face_landmarks.dat',
40 | 'circular_face': 'pretrained_models/CurricularFace_Backbone.pth',
41 | 'mtcnn_pnet': 'pretrained_models/mtcnn/pnet.npy',
42 | 'mtcnn_rnet': 'pretrained_models/mtcnn/rnet.npy',
43 | 'mtcnn_onet': 'pretrained_models/mtcnn/onet.npy',
44 | 'moco': 'pretrained_models/moco_v2_800ep_pretrain.pth',
45 | 'id_encoder': 'pretrained_models/id-encoder.pt',
46 | 'canvas_encoder': 'pretrained_models/canvas-encoder.pt',
47 | 'stylegan_watercolor': 'pretrained_models/stylegan2-watercolor.pt',
48 | }
49 |
--------------------------------------------------------------------------------
/configs/transforms_config.py:
--------------------------------------------------------------------------------
1 | from abc import abstractmethod
2 | import torchvision.transforms as transforms
3 |
4 |
5 | class TransformsConfig(object):
6 |
7 | def __init__(self, opts):
8 | self.opts = opts
9 |
10 | @abstractmethod
11 | def get_transforms(self):
12 | pass
13 |
14 |
15 | class EncodeTransforms(TransformsConfig):
16 |
17 | def __init__(self, opts):
18 | super(EncodeTransforms, self).__init__(opts)
19 |
20 | def get_transforms(self):
21 | transforms_dict = {
22 | 'transform_gt_train': transforms.Compose([
23 | transforms.Resize((256, 256)),
24 | #transforms.RandomHorizontalFlip(0.5),
25 | transforms.ToTensor(),
26 | transforms.Normalize([0.5, 0.5, 0.5], [0.5, 0.5, 0.5])]),
27 | #'transform_source': None,
28 | 'transform_source': transforms.Compose([
29 | transforms.Resize((256, 256)),
30 | #transforms.RandomHorizontalFlip(0.5),
31 | transforms.ToTensor(),
32 | transforms.Normalize([0.5, 0.5, 0.5], [0.5, 0.5, 0.5])]),
33 | 'transform_test': transforms.Compose([
34 | transforms.Resize((256, 256)),
35 | transforms.ToTensor(),
36 | transforms.Normalize([0.5, 0.5, 0.5], [0.5, 0.5, 0.5])]),
37 | 'transform_inference': transforms.Compose([
38 | transforms.Resize((256, 256)),
39 | transforms.ToTensor(),
40 | transforms.Normalize([0.5, 0.5, 0.5], [0.5, 0.5, 0.5])])
41 | }
42 | return transforms_dict
43 |
44 |
45 | class CarsEncodeTransforms(TransformsConfig):
46 |
47 | def __init__(self, opts):
48 | super(CarsEncodeTransforms, self).__init__(opts)
49 |
50 | def get_transforms(self):
51 | transforms_dict = {
52 | 'transform_gt_train': transforms.Compose([
53 | transforms.Resize((192, 256)),
54 | #transforms.RandomHorizontalFlip(0.5),
55 | transforms.ToTensor(),
56 | transforms.Normalize([0.5, 0.5, 0.5], [0.5, 0.5, 0.5])]),
57 | 'transform_source': transforms.Compose([
58 | transforms.Resize((192, 256)),
59 | #transforms.RandomHorizontalFlip(0.5),
60 | transforms.ToTensor(),
61 | transforms.Normalize([0.5, 0.5, 0.5], [0.5, 0.5, 0.5])]),
62 | 'transform_test': transforms.Compose([
63 | transforms.Resize((192, 256)),
64 | transforms.ToTensor(),
65 | transforms.Normalize([0.5, 0.5, 0.5], [0.5, 0.5, 0.5])]),
66 | 'transform_inference': transforms.Compose([
67 | transforms.Resize((192, 256)),
68 | transforms.ToTensor(),
69 | transforms.Normalize([0.5, 0.5, 0.5], [0.5, 0.5, 0.5])])
70 | }
71 | return transforms_dict
72 |
--------------------------------------------------------------------------------
/criteria/.ipynb_checkpoints/id_loss-checkpoint.py:
--------------------------------------------------------------------------------
1 | import torch
2 | from torch import nn
3 | from configs.paths_config import model_paths
4 | from models.encoders.model_irse import Backbone
5 |
6 |
7 | class IDLoss(nn.Module):
8 | def __init__(self):
9 | super(IDLoss, self).__init__()
10 | print('Loading ResNet ArcFace')
11 | self.facenet = Backbone(input_size=112, num_layers=50, drop_ratio=0.6, mode='ir_se')
12 | self.facenet.load_state_dict(torch.load(model_paths['ir_se50']))
13 | self.face_pool = torch.nn.AdaptiveAvgPool2d((112, 112))
14 | self.facenet.eval()
15 |
16 | def extract_feats(self, x):
17 | x = x[:, :, 35:223, 32:220] # Crop interesting region
18 | x = self.face_pool(x)
19 | x_feats = self.facenet(x)
20 | return x_feats
21 |
22 | def forward(self, y_hat, y, x, target_id_feat=None):
23 | n_samples = x.shape[0]
24 | x_feats = self.extract_feats(x)
25 |
26 | if target_id_feat is not None:
27 | y_feats = target_id_feat#self.extract_feats(id_x)
28 | else:
29 | y_feats = self.extract_feats(y) # Otherwise use the feature from there
30 |
31 | y_hat_feats = self.extract_feats(y_hat)
32 | y_feats = y_feats.detach()
33 | loss = 0
34 | sim_improvement = 0
35 | id_logs = []
36 | count = 0
37 | for i in range(n_samples):
38 | diff_target = y_hat_feats[i].dot(y_feats[i])
39 | diff_input = y_hat_feats[i].dot(x_feats[i])
40 | diff_views = y_feats[i].dot(x_feats[i])
41 | id_logs.append({'diff_target': float(diff_target),
42 | 'diff_input': float(diff_input),
43 | 'diff_views': float(diff_views)})
44 | loss += 1 - diff_target
45 | id_diff = float(diff_target) - float(diff_views)
46 | sim_improvement += id_diff
47 | count += 1
48 |
49 | return loss / count, sim_improvement / count, id_logs
50 |
--------------------------------------------------------------------------------
/criteria/__init__.py:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/1jsingh/paint2pix/971d1ea06ef6cbcc555ad09a365bf1621ce13f08/criteria/__init__.py
--------------------------------------------------------------------------------
/criteria/id_loss.py:
--------------------------------------------------------------------------------
1 | import torch
2 | from torch import nn
3 | from configs.paths_config import model_paths
4 | from models.encoders.model_irse import Backbone
5 |
6 |
7 | class IDLoss(nn.Module):
8 | def __init__(self):
9 | super(IDLoss, self).__init__()
10 | print('Loading ResNet ArcFace')
11 | self.facenet = Backbone(input_size=112, num_layers=50, drop_ratio=0.6, mode='ir_se')
12 | self.facenet.load_state_dict(torch.load(model_paths['ir_se50']))
13 | self.face_pool = torch.nn.AdaptiveAvgPool2d((112, 112))
14 | self.facenet.eval()
15 |
16 | def extract_feats(self, x):
17 | x = x[:, :, 35:223, 32:220] # Crop interesting region
18 | x = self.face_pool(x)
19 | x_feats = self.facenet(x)
20 | return x_feats
21 |
22 | def forward(self, y_hat, y, x, target_id_feat=None):
23 | n_samples = x.shape[0]
24 | x_feats = self.extract_feats(x)
25 |
26 | if target_id_feat is not None:
27 | y_feats = target_id_feat#self.extract_feats(id_x)
28 | else:
29 | y_feats = self.extract_feats(y) # Otherwise use the feature from there
30 |
31 | y_hat_feats = self.extract_feats(y_hat)
32 | y_feats = y_feats.detach()
33 | loss = 0
34 | sim_improvement = 0
35 | id_logs = []
36 | count = 0
37 | for i in range(n_samples):
38 | diff_target = y_hat_feats[i].dot(y_feats[i])
39 | diff_input = y_hat_feats[i].dot(x_feats[i])
40 | diff_views = y_feats[i].dot(x_feats[i])
41 | id_logs.append({'diff_target': float(diff_target),
42 | 'diff_input': float(diff_input),
43 | 'diff_views': float(diff_views)})
44 | loss += 1 - diff_target
45 | id_diff = float(diff_target) - float(diff_views)
46 | sim_improvement += id_diff
47 | count += 1
48 |
49 | return loss / count, sim_improvement / count, id_logs
50 |
--------------------------------------------------------------------------------
/criteria/lpips/__init__.py:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/1jsingh/paint2pix/971d1ea06ef6cbcc555ad09a365bf1621ce13f08/criteria/lpips/__init__.py
--------------------------------------------------------------------------------
/criteria/lpips/lpips.py:
--------------------------------------------------------------------------------
1 | import torch
2 | import torch.nn as nn
3 |
4 | from criteria.lpips.networks import get_network, LinLayers
5 | from criteria.lpips.utils import get_state_dict
6 |
7 |
8 | class LPIPS(nn.Module):
9 | r"""Creates a criterion that measures
10 | Learned Perceptual Image Patch Similarity (LPIPS).
11 | Arguments:
12 | net_type (str): the network type to compare the features:
13 | 'alex' | 'squeeze' | 'vgg'. Default: 'alex'.
14 | version (str): the version of LPIPS. Default: 0.1.
15 | """
16 | def __init__(self, net_type: str = 'alex', version: str = '0.1'):
17 |
18 | assert version in ['0.1'], 'v0.1 is only supported now'
19 |
20 | super(LPIPS, self).__init__()
21 |
22 | # pretrained network
23 | self.net = get_network(net_type).to("cuda")
24 |
25 | # linear layers
26 | self.lin = LinLayers(self.net.n_channels_list).to("cuda")
27 | self.lin.load_state_dict(get_state_dict(net_type, version))
28 |
29 | def forward(self, x: torch.Tensor, y: torch.Tensor):
30 | feat_x, feat_y = self.net(x), self.net(y)
31 |
32 | diff = [(fx - fy) ** 2 for fx, fy in zip(feat_x, feat_y)]
33 | res = [l(d).mean((2, 3), True) for d, l in zip(diff, self.lin)]
34 |
35 | return torch.sum(torch.cat(res, 0)) / x.shape[0]
36 |
--------------------------------------------------------------------------------
/criteria/lpips/networks.py:
--------------------------------------------------------------------------------
1 | from typing import Sequence
2 |
3 | from itertools import chain
4 |
5 | import torch
6 | import torch.nn as nn
7 | from torchvision import models
8 |
9 | from criteria.lpips.utils import normalize_activation
10 |
11 |
12 | def get_network(net_type: str):
13 | if net_type == 'alex':
14 | return AlexNet()
15 | elif net_type == 'squeeze':
16 | return SqueezeNet()
17 | elif net_type == 'vgg':
18 | return VGG16()
19 | else:
20 | raise NotImplementedError('choose net_type from [alex, squeeze, vgg].')
21 |
22 |
23 | class LinLayers(nn.ModuleList):
24 | def __init__(self, n_channels_list: Sequence[int]):
25 | super(LinLayers, self).__init__([
26 | nn.Sequential(
27 | nn.Identity(),
28 | nn.Conv2d(nc, 1, 1, 1, 0, bias=False)
29 | ) for nc in n_channels_list
30 | ])
31 |
32 | for param in self.parameters():
33 | param.requires_grad = False
34 |
35 |
36 | class BaseNet(nn.Module):
37 | def __init__(self):
38 | super(BaseNet, self).__init__()
39 |
40 | # register buffer
41 | self.register_buffer(
42 | 'mean', torch.Tensor([-.030, -.088, -.188])[None, :, None, None])
43 | self.register_buffer(
44 | 'std', torch.Tensor([.458, .448, .450])[None, :, None, None])
45 |
46 | def set_requires_grad(self, state: bool):
47 | for param in chain(self.parameters(), self.buffers()):
48 | param.requires_grad = state
49 |
50 | def z_score(self, x: torch.Tensor):
51 | return (x - self.mean) / self.std
52 |
53 | def forward(self, x: torch.Tensor):
54 | x = self.z_score(x)
55 |
56 | output = []
57 | for i, (_, layer) in enumerate(self.layers._modules.items(), 1):
58 | x = layer(x)
59 | if i in self.target_layers:
60 | output.append(normalize_activation(x))
61 | if len(output) == len(self.target_layers):
62 | break
63 | return output
64 |
65 |
66 | class SqueezeNet(BaseNet):
67 | def __init__(self):
68 | super(SqueezeNet, self).__init__()
69 |
70 | self.layers = models.squeezenet1_1(True).features
71 | self.target_layers = [2, 5, 8, 10, 11, 12, 13]
72 | self.n_channels_list = [64, 128, 256, 384, 384, 512, 512]
73 |
74 | self.set_requires_grad(False)
75 |
76 |
77 | class AlexNet(BaseNet):
78 | def __init__(self):
79 | super(AlexNet, self).__init__()
80 |
81 | self.layers = models.alexnet(True).features
82 | self.target_layers = [2, 5, 8, 10, 12]
83 | self.n_channels_list = [64, 192, 384, 256, 256]
84 |
85 | self.set_requires_grad(False)
86 |
87 |
88 | class VGG16(BaseNet):
89 | def __init__(self):
90 | super(VGG16, self).__init__()
91 |
92 | self.layers = models.vgg16(True).features
93 | self.target_layers = [4, 9, 16, 23, 30]
94 | self.n_channels_list = [64, 128, 256, 512, 512]
95 |
96 | self.set_requires_grad(False)
--------------------------------------------------------------------------------
/criteria/lpips/utils.py:
--------------------------------------------------------------------------------
1 | from collections import OrderedDict
2 |
3 | import torch
4 |
5 |
6 | def normalize_activation(x, eps=1e-10):
7 | norm_factor = torch.sqrt(torch.sum(x ** 2, dim=1, keepdim=True))
8 | return x / (norm_factor + eps)
9 |
10 |
11 | def get_state_dict(net_type: str = 'alex', version: str = '0.1'):
12 | # build url
13 | url = 'https://raw.githubusercontent.com/richzhang/PerceptualSimilarity/' \
14 | + f'master/lpips/weights/v{version}/{net_type}.pth'
15 |
16 | # download
17 | old_state_dict = torch.hub.load_state_dict_from_url(
18 | url, progress=True,
19 | map_location=None if torch.cuda.is_available() else torch.device('cpu')
20 | )
21 |
22 | # rename keys
23 | new_state_dict = OrderedDict()
24 | for key, val in old_state_dict.items():
25 | new_key = key
26 | new_key = new_key.replace('lin', '')
27 | new_key = new_key.replace('model.', '')
28 | new_state_dict[new_key] = val
29 |
30 | return new_state_dict
31 |
--------------------------------------------------------------------------------
/criteria/moco_loss.py:
--------------------------------------------------------------------------------
1 | import torch
2 | from torch import nn
3 | import torch.nn.functional as F
4 | from configs.paths_config import model_paths
5 |
6 |
7 | class MocoLoss(nn.Module):
8 |
9 | def __init__(self):
10 | super(MocoLoss, self).__init__()
11 | print("Loading MOCO model from path: {}".format(model_paths["moco"]))
12 | self.model = self.__load_model()
13 | self.model.cuda()
14 | self.model.eval()
15 |
16 | @staticmethod
17 | def __load_model():
18 | import torchvision.models as models
19 | model = models.__dict__["resnet50"]()
20 | # freeze all layers but the last fc
21 | for name, param in model.named_parameters():
22 | if name not in ['fc.weight', 'fc.bias']:
23 | param.requires_grad = False
24 | checkpoint = torch.load(model_paths['moco'], map_location="cpu")
25 | state_dict = checkpoint['state_dict']
26 | # rename moco pre-trained keys
27 | for k in list(state_dict.keys()):
28 | # retain only encoder_q up to before the embedding layer
29 | if k.startswith('module.encoder_q') and not k.startswith('module.encoder_q.fc'):
30 | # remove prefix
31 | state_dict[k[len("module.encoder_q."):]] = state_dict[k]
32 | # delete renamed or unused k
33 | del state_dict[k]
34 | msg = model.load_state_dict(state_dict, strict=False)
35 | assert set(msg.missing_keys) == {"fc.weight", "fc.bias"}
36 | # remove output layer
37 | model = nn.Sequential(*list(model.children())[:-1]).cuda()
38 | return model
39 |
40 | def extract_feats(self, x):
41 | x = F.interpolate(x, size=224)
42 | x_feats = self.model(x)
43 | x_feats = nn.functional.normalize(x_feats, dim=1)
44 | x_feats = x_feats.squeeze()
45 | return x_feats
46 |
47 | def forward(self, y_hat, y, x):
48 | n_samples = x.shape[0]
49 | x_feats = self.extract_feats(x)
50 | y_feats = self.extract_feats(y)
51 | y_hat_feats = self.extract_feats(y_hat)
52 | y_feats = y_feats.detach()
53 | loss = 0
54 | sim_improvement = 0
55 | sim_logs = []
56 | count = 0
57 | for i in range(n_samples):
58 | diff_target = y_hat_feats[i].dot(y_feats[i])
59 | diff_input = y_hat_feats[i].dot(x_feats[i])
60 | diff_views = y_feats[i].dot(x_feats[i])
61 | sim_logs.append({'diff_target': float(diff_target),
62 | 'diff_input': float(diff_input),
63 | 'diff_views': float(diff_views)})
64 | loss += 1 - diff_target
65 | sim_diff = float(diff_target) - float(diff_views)
66 | sim_improvement += sim_diff
67 | count += 1
68 |
69 | return loss / count, sim_improvement / count, sim_logs
70 |
--------------------------------------------------------------------------------
/criteria/w_norm.py:
--------------------------------------------------------------------------------
1 | import torch
2 | from torch import nn
3 |
4 |
5 | class WNormLoss(nn.Module):
6 |
7 | def __init__(self, start_from_latent_avg=True):
8 | super(WNormLoss, self).__init__()
9 | self.start_from_latent_avg = start_from_latent_avg
10 |
11 | def forward(self, latent, latent_avg=None):
12 | if self.start_from_latent_avg:
13 | latent = latent - latent_avg
14 | return torch.sum(latent.norm(2, dim=(1, 2))) / latent.shape[0]
15 |
--------------------------------------------------------------------------------
/docs/custom-color-edits.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/1jsingh/paint2pix/971d1ea06ef6cbcc555ad09a365bf1621ce13f08/docs/custom-color-edits.png
--------------------------------------------------------------------------------
/docs/prog-synthesis.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/1jsingh/paint2pix/971d1ea06ef6cbcc555ad09a365bf1621ce13f08/docs/prog-synthesis.png
--------------------------------------------------------------------------------
/docs/watercolor-synthesis.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/1jsingh/paint2pix/971d1ea06ef6cbcc555ad09a365bf1621ce13f08/docs/watercolor-synthesis.png
--------------------------------------------------------------------------------
/environment/paint2pix_env.yml:
--------------------------------------------------------------------------------
1 | name: intelli-paint
2 | channels:
3 | - conda-forge
4 | - defaults
5 | dependencies:
6 | - _libgcc_mutex=0.1=main
7 | - _openmp_mutex=4.5=1_gnu
8 | - anyio=2.2.0=py36h5fab9bb_0
9 | - async_generator=1.10=py_0
10 | - babel=2.9.1=pyh44b312d_0
11 | - backcall=0.2.0=pyhd3eb1b0_0
12 | - blas=1.0=mkl
13 | - brotlipy=0.7.0=py36he6145b8_1001
14 | - bzip2=1.0.8=h7b6447c_0
15 | - ca-certificates=2021.10.8=ha878542_0
16 | - certifi=2021.5.30=py36h5fab9bb_0
17 | - charset-normalizer=2.0.0=pyhd8ed1ab_0
18 | - contextvars=2.4=py_0
19 | - cryptography=3.1=py36h45558ae_0
20 | - cudatoolkit=11.0.221=h6bb024c_0
21 | - cudatoolkit-dev=11.0.3=py36h8f6f2f9_2
22 | - dataclasses=0.8=pyh4f3eec9_6
23 | - entrypoints=0.3=pyhd8ed1ab_1003
24 | - filelock=3.0.12=pyh9f0ad1d_0
25 | - freetype=2.10.2=h5ab3b9f_0
26 | - gdown=3.13.0=pyhd8ed1ab_0
27 | - gmp=6.1.2=h6c8ec71_1
28 | - gnutls=3.6.5=h71b1129_1002
29 | - htop=2.2.0=hf8c457e_1000
30 | - immutables=0.16=py36h7f8727e_0
31 | - intel-openmp=2021.2.0=h06a4308_610
32 | - ipython_genutils=0.2.0=pyhd3eb1b0_1
33 | - jedi=0.17.2=py36h5fab9bb_1
34 | - jpeg=9b=h024ee3a_2
35 | - json5=0.9.5=pyh9f0ad1d_0
36 | - jsonschema=3.2.0=pyhd8ed1ab_3
37 | - jupyter_client=6.1.12=pyhd3eb1b0_0
38 | - jupyter_core=4.7.1=py36h06a4308_0
39 | - jupyter_server=1.4.1=py36h06a4308_0
40 | - jupyterlab=3.2.5=pyhd8ed1ab_0
41 | - jupyterlab_server=2.8.2=pyhd8ed1ab_0
42 | - jupyterlab_widgets=1.0.2=pyhd8ed1ab_0
43 | - lame=3.100=h7b6447c_0
44 | - lcms2=2.12=h3be6417_0
45 | - ld_impl_linux-64=2.33.1=h53a641e_7
46 | - libblas=3.8.0=21_mkl
47 | - libcblas=3.8.0=21_mkl
48 | - libedit=3.1.20191231=h14c3975_1
49 | - libffi=3.3=he6710b0_2
50 | - libgcc-ng=9.1.0=hdf63c60_0
51 | - libgomp=9.3.0=h5101ec6_17
52 | - libiconv=1.16=h516909a_0
53 | - liblapack=3.8.0=21_mkl
54 | - libopus=1.3.1=h7b6447c_0
55 | - libpng=1.6.37=hbc83047_0
56 | - libsodium=1.0.18=h7b6447c_0
57 | - libstdcxx-ng=9.1.0=hdf63c60_0
58 | - libtiff=4.2.0=h85742a9_0
59 | - libuv=1.40.0=h7b6447c_0
60 | - libvpx=1.7.0=h439df22_0
61 | - libwebp-base=1.2.0=h27cfd23_0
62 | - lz4-c=1.9.3=h2531618_0
63 | - mistune=0.8.4=py36h1d69622_1002
64 | - mkl=2020.2=256
65 | - mkl-service=2.3.0=py36he8ac12f_0
66 | - mkl_fft=1.3.0=py36h54f3939_0
67 | - mkl_random=1.1.1=py36h0573a6f_0
68 | - nano=2.9.8=hddfc1eb_1001
69 | - nbclassic=0.2.6=pyhd3eb1b0_0
70 | - nbconvert=5.6.1=pyhd8ed1ab_2
71 | - ncurses=6.2=he6710b0_1
72 | - nest-asyncio=1.5.1=pyhd3eb1b0_0
73 | - nettle=3.4.1=hbb512f6_0
74 | - ninja=1.10.2=hff7bd54_1
75 | - numpy-base=1.19.2=py36hfa32c7d_0
76 | - olefile=0.46=py36_0
77 | - openh264=2.1.0=hd408876_0
78 | - openssl=1.1.1h=h516909a_0
79 | - parso=0.7.1=pyh9f0ad1d_0
80 | - pexpect=4.8.0=pyhd3eb1b0_3
81 | - pickleshare=0.7.5=pyhd3eb1b0_1003
82 | - pillow=7.2.0=py36hb39fc2d_0
83 | - pip=20.2.2=py36_0
84 | - prometheus_client=0.12.0=pyhd8ed1ab_0
85 | - prompt_toolkit=1.0.15=py_1
86 | - pycparser=2.20=pyh9f0ad1d_2
87 | - pyopenssl=19.1.0=py_1
88 | - pysocks=1.7.1=py36h5fab9bb_3
89 | - python=3.6.10=h7579374_2
90 | - python-dateutil=2.8.1=pyhd3eb1b0_0
91 | - python_abi=3.6=1_cp36m
92 | - readline=8.0=h7b6447c_0
93 | - screen=4.8.0=he28a2e2_0
94 | - setuptools=49.6.0=py36_0
95 | - sniffio=1.2.0=py36h5fab9bb_1
96 | - sqlite=3.32.3=h62c20be_0
97 | - tk=8.6.10=hbc83047_0
98 | - tqdm=4.61.1=pyhd8ed1ab_0
99 | - traitlets=4.3.3=py36h9f0ad1d_1
100 | - typing_extensions=3.10.0.2=pyh06a4308_0
101 | - unzip=6.0=h611a1e1_0
102 | - wcwidth=0.2.5=py_0
103 | - wheel=0.37.0=pyhd8ed1ab_1
104 | - widgetsnbextension=3.5.1=py36h5fab9bb_4
105 | - x264=1!157.20191217=h7b6447c_0
106 | - xz=5.2.5=h7b6447c_0
107 | - zeromq=4.3.4=h2531618_0
108 | - zlib=1.2.11=h7b6447c_3
109 | - zstd=1.4.9=haebb681_0
110 | - pip:
111 | - absl-py==0.10.0
112 | - altair==4.1.0
113 | - argon2-cffi==20.1.0
114 | - astor==0.8.1
115 | - astunparse==1.6.3
116 | - attrs==20.1.0
117 | - backports-entry-points-selectable==1.1.0
118 | - backports-zoneinfo==0.2.1
119 | - base58==2.1.0
120 | - bce-python-sdk==0.8.62
121 | - bleach==3.1.5
122 | - blinker==1.4
123 | - boto3==1.18.27
124 | - botocore==1.21.27
125 | - cached-property==1.5.2
126 | - cachetools==4.1.1
127 | - cffi==1.14.2
128 | - cfgv==3.3.0
129 | - chardet==3.0.4
130 | - clang==5.0
131 | - click==7.1.2
132 | - clip==1.0
133 | - clipboard==0.0.4
134 | - cloudpickle==1.2.2
135 | - colorama==0.4.4
136 | - colorlog==5.0.1
137 | - cycler==0.10.0
138 | - cython==0.29.21
139 | - decorator==4.4.2
140 | - defusedxml==0.6.0
141 | - deprecation==2.1.0
142 | - dill==0.3.4
143 | - distlib==0.3.2
144 | - dlib==19.22.1
145 | - dm-control==0.0.364896371
146 | - dm-env==1.5
147 | - dm-tree==0.1.7
148 | - dnnlib==0.0.1
149 | - dominate==2.6.0
150 | - easydict==1.9
151 | - efficientnet-pytorch==0.7.0
152 | - et-xmlfile==1.1.0
153 | - ffmpeg==1.4
154 | - ffmpeg-python==0.2.0
155 | - flake8==3.9.2
156 | - flask==2.0.1
157 | - flask-babel==2.0.0
158 | - flatbuffers==1.12
159 | - ftfy==6.0.3
160 | - future==0.18.2
161 | - fuzzywuzzy==0.18.0
162 | - gast==0.2.2
163 | - gevent==21.8.0
164 | - gitdb==4.0.7
165 | - gitpython==3.1.18
166 | - giturlparse==0.10.0
167 | - glcontext==2.3.5
168 | - glfw==1.12.0
169 | - google-api-core==2.3.1
170 | - google-api-python-client==2.33.0
171 | - google-auth==2.3.3
172 | - google-auth-httplib2==0.1.0
173 | - google-auth-oauthlib==0.4.1
174 | - google-pasta==0.2.0
175 | - googleapis-common-protos==1.54.0
176 | - greenlet==1.1.2
177 | - grpcio==1.39.0
178 | - gunicorn==20.1.0
179 | - gym==0.15.7
180 | - gym3==0.3.3
181 | - h5py==3.1.0
182 | - httplib2==0.20.2
183 | - hvac==0.11.2
184 | - identify==2.2.13
185 | - idna==2.8
186 | - imageio==2.9.0
187 | - imageio-ffmpeg==0.3.0
188 | - imagenetv2-pytorch==0.1
189 | - importlib-metadata==4.8.3
190 | - importlib-resources==5.2.2
191 | - ipykernel==4.6.1
192 | - ipython==5.5.0
193 | - ipywebrtc==0.6.0
194 | - ipywidgets==7.5.1
195 | - itsdangerous==2.0.1
196 | - jieba==0.42.1
197 | - jinja2==3.0.1
198 | - jmespath==0.10.0
199 | - joblib==0.16.0
200 | - jsonpatch==1.32
201 | - jsonpointer==2.3
202 | - jupyter==1.0.0
203 | - jupyter-client==6.1.6
204 | - jupyter-console==6.1.0
205 | - jupyter-core==4.6.3
206 | - keras==2.6.0
207 | - keras-applications==1.0.8
208 | - keras-preprocessing==1.1.2
209 | - kiwisolver==1.2.0
210 | - kornia==0.5.8
211 | - labmaze==1.0.5
212 | - lpips==0.1.4
213 | - lxml==4.8.0
214 | - markdown==3.2.2
215 | - markupsafe==2.0.1
216 | - matplotlib==3.3.1
217 | - mccabe==0.6.1
218 | - mock==4.0.3
219 | - moderngl==5.6.4
220 | - multiprocess==0.70.12.2
221 | - munch==2.5.0
222 | - nbformat==5.0.7
223 | - networkx==2.5.1
224 | - neuralgym==0.0.1
225 | - nodeenv==1.6.0
226 | - notebook==5.2.2
227 | - numpy==1.19.5
228 | - nvidia-htop==1.0.5
229 | - oauth2client==4.1.3
230 | - oauthlib==3.1.0
231 | - opencv-python==4.4.0.42
232 | - openpyxl==3.0.9
233 | - opt-einsum==3.3.0
234 | - packaging==20.4
235 | - paddle2onnx==0.7
236 | - paddlehub==2.1.0
237 | - paddlenlp==2.0.7
238 | - paddlepaddle==2.1.2
239 | - paddlepaddle-gpu==2.2.1
240 | - pandas==0.24.2
241 | - pandocfilters==1.4.2
242 | - platformdirs==2.2.0
243 | - portpicker==1.2.0
244 | - pre-commit==2.14.0
245 | - procgen==0.10.4
246 | - prometheus-client==0.8.0
247 | - prompt-toolkit==1.0.18
248 | - protobuf==3.19.4
249 | - ptyprocess==0.6.0
250 | - pyarrow==5.0.0
251 | - pyasn1==0.4.8
252 | - pyasn1-modules==0.2.8
253 | - pycodestyle==2.7.0
254 | - pycryptodome==3.10.1
255 | - pydeck==0.6.2
256 | - pydrive==1.3.1
257 | - pydrive2==1.10.0
258 | - pyflakes==2.3.1
259 | - pyglet==1.5.0
260 | - pygments==2.6.1
261 | - pyopengl==3.1.6
262 | - pyparsing==2.4.7
263 | - pyperclip==1.8.2
264 | - pyrsistent==0.16.0
265 | - python-levenshtein==0.12.2
266 | - pytorch-fid==0.2.1
267 | - pytz==2020.1
268 | - pytz-deprecation-shim==0.1.0.post0
269 | - pywavelets==1.1.1
270 | - pyyaml==5.4.1
271 | - pyzmq==20.0.0
272 | - qtconsole==4.7.6
273 | - qtpy==1.9.0
274 | - rarfile==4.0
275 | - regex==2021.7.6
276 | - requests==2.21.0
277 | - requests-oauthlib==1.3.0
278 | - rsa==4.6
279 | - ruamel-yaml==0.17.4
280 | - ruamel-yaml-clib==0.2.6
281 | - s3transfer==0.5.0
282 | - scikit-image==0.17.2
283 | - scikit-learn==0.23.2
284 | - scipy==1.2.0
285 | - seaborn==0.10.1
286 | - send2trash==1.5.0
287 | - seqeval==1.2.2
288 | - shellcheck-py==0.7.2.1
289 | - simplegeneric==0.8.1
290 | - six==1.12.0
291 | - smmap==4.0.0
292 | - streamlit==1.0.0
293 | - streamlit-drawable-canvas==0.8.0
294 | - tabulate==0.8.9
295 | - tensorboard==1.15.0
296 | - tensorboard-data-server==0.6.1
297 | - tensorboard-plugin-wit==1.7.0
298 | - tensorboardx==2.1
299 | - tensorflow-estimator==1.15.1
300 | - tensorflow-gpu==1.15.0
301 | - termcolor==1.1.0
302 | - terminado==0.8.3
303 | - testpath==0.4.4
304 | - threadpoolctl==2.1.0
305 | - tifffile==2020.9.3
306 | - timm==0.4.12
307 | - toml==0.10.2
308 | - toolz==0.11.1
309 | - torch==1.7.1+cu110
310 | - torchaudio==0.7.2
311 | - torchfile==0.1.0
312 | - torchgeometry==0.1.2
313 | - torchvision==0.8.2+cu110
314 | - tornado==4.5.3
315 | - typing-extensions==3.7.4.3
316 | - tzdata==2021.4
317 | - tzlocal==4.0.1
318 | - uritemplate==4.1.1
319 | - urllib3==1.25.10
320 | - validators==0.18.2
321 | - virtualenv==20.7.2
322 | - visdom==0.1.8.9
323 | - visualdl==2.2.0
324 | - watchdog==2.1.6
325 | - webencodings==0.5.1
326 | - websocket-client==1.3.1
327 | - werkzeug==2.0.1
328 | - wrapt==1.12.1
329 | - zipp==3.1.0
330 | - zope-event==4.5.0
331 | - zope-interface==5.4.0
332 | prefix: /home/jsingh/anaconda3/envs/intelli-paint
333 |
--------------------------------------------------------------------------------
/input-images/143.jpg:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/1jsingh/paint2pix/971d1ea06ef6cbcc555ad09a365bf1621ce13f08/input-images/143.jpg
--------------------------------------------------------------------------------
/input-images/20.jpg:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/1jsingh/paint2pix/971d1ea06ef6cbcc555ad09a365bf1621ce13f08/input-images/20.jpg
--------------------------------------------------------------------------------
/input-images/214.jpg:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/1jsingh/paint2pix/971d1ea06ef6cbcc555ad09a365bf1621ce13f08/input-images/214.jpg
--------------------------------------------------------------------------------
/input-images/262.jpg:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/1jsingh/paint2pix/971d1ea06ef6cbcc555ad09a365bf1621ce13f08/input-images/262.jpg
--------------------------------------------------------------------------------
/input-images/823.jpg:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/1jsingh/paint2pix/971d1ea06ef6cbcc555ad09a365bf1621ce13f08/input-images/823.jpg
--------------------------------------------------------------------------------
/licenses/LICENSE_S-aiueo32:
--------------------------------------------------------------------------------
1 | BSD 2-Clause License
2 |
3 | Copyright (c) 2020, Sou Uchida
4 | All rights reserved.
5 |
6 | Redistribution and use in source and binary forms, with or without
7 | modification, are permitted provided that the following conditions are met:
8 |
9 | 1. Redistributions of source code must retain the above copyright notice, this
10 | list of conditions and the following disclaimer.
11 |
12 | 2. Redistributions in binary form must reproduce the above copyright notice,
13 | this list of conditions and the following disclaimer in the documentation
14 | and/or other materials provided with the distribution.
15 |
16 | THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
17 | AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
18 | IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
19 | DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE
20 | FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
21 | DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
22 | SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
23 | CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
24 | OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
25 | OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
--------------------------------------------------------------------------------
/licenses/LICENSE_TreB1eN:
--------------------------------------------------------------------------------
1 | MIT License
2 |
3 | Copyright (c) 2018 TreB1eN
4 |
5 | Permission is hereby granted, free of charge, to any person obtaining a copy
6 | of this software and associated documentation files (the "Software"), to deal
7 | in the Software without restriction, including without limitation the rights
8 | to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9 | copies of the Software, and to permit persons to whom the Software is
10 | furnished to do so, subject to the following conditions:
11 |
12 | The above copyright notice and this permission notice shall be included in all
13 | copies or substantial portions of the Software.
14 |
15 | THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16 | IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17 | FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18 | AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19 | LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20 | OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21 | SOFTWARE.
--------------------------------------------------------------------------------
/licenses/LICENSE_alaluf:
--------------------------------------------------------------------------------
1 | MIT License
2 |
3 | Copyright (c) 2022 Yuval Alaluf
4 |
5 | Permission is hereby granted, free of charge, to any person obtaining a copy
6 | of this software and associated documentation files (the "Software"), to deal
7 | in the Software without restriction, including without limitation the rights
8 | to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9 | copies of the Software, and to permit persons to whom the Software is
10 | furnished to do so, subject to the following conditions:
11 |
12 | The above copyright notice and this permission notice shall be included in all
13 | copies or substantial portions of the Software.
14 |
15 | THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16 | IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17 | FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18 | AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19 | LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20 | OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21 | SOFTWARE.
22 |
--------------------------------------------------------------------------------
/licenses/LICENSE_eladrich:
--------------------------------------------------------------------------------
1 | MIT License
2 |
3 | Copyright (c) 2020 Elad Richardson, Yuval Alaluf
4 |
5 | Permission is hereby granted, free of charge, to any person obtaining a copy
6 | of this software and associated documentation files (the "Software"), to deal
7 | in the Software without restriction, including without limitation the rights
8 | to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9 | copies of the Software, and to permit persons to whom the Software is
10 | furnished to do so, subject to the following conditions:
11 |
12 | The above copyright notice and this permission notice shall be included in all
13 | copies or substantial portions of the Software.
14 |
15 | THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16 | IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17 | FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18 | AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19 | LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20 | OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21 | SOFTWARE.
--------------------------------------------------------------------------------
/licenses/LICENSE_lessw2020:
--------------------------------------------------------------------------------
1 | Apache License
2 | Version 2.0, January 2004
3 | http://www.apache.org/licenses/
4 |
5 | TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
6 |
7 | 1. Definitions.
8 |
9 | "License" shall mean the terms and conditions for use, reproduction,
10 | and distribution as defined by Sections 1 through 9 of this document.
11 |
12 | "Licensor" shall mean the copyright owner or entity authorized by
13 | the copyright owner that is granting the License.
14 |
15 | "Legal Entity" shall mean the union of the acting entity and all
16 | other entities that control, are controlled by, or are under common
17 | control with that entity. For the purposes of this definition,
18 | "control" means (i) the power, direct or indirect, to cause the
19 | direction or management of such entity, whether by contract or
20 | otherwise, or (ii) ownership of fifty percent (50%) or more of the
21 | outstanding shares, or (iii) beneficial ownership of such entity.
22 |
23 | "You" (or "Your") shall mean an individual or Legal Entity
24 | exercising permissions granted by this License.
25 |
26 | "Source" form shall mean the preferred form for making modifications,
27 | including but not limited to software source code, documentation
28 | source, and configuration files.
29 |
30 | "Object" form shall mean any form resulting from mechanical
31 | transformation or translation of a Source form, including but
32 | not limited to compiled object code, generated documentation,
33 | and conversions to other media types.
34 |
35 | "Work" shall mean the work of authorship, whether in Source or
36 | Object form, made available under the License, as indicated by a
37 | copyright notice that is included in or attached to the work
38 | (an example is provided in the Appendix below).
39 |
40 | "Derivative Works" shall mean any work, whether in Source or Object
41 | form, that is based on (or derived from) the Work and for which the
42 | editorial revisions, annotations, elaborations, or other modifications
43 | represent, as a whole, an original work of authorship. For the purposes
44 | of this License, Derivative Works shall not include works that remain
45 | separable from, or merely link (or bind by name) to the interfaces of,
46 | the Work and Derivative Works thereof.
47 |
48 | "Contribution" shall mean any work of authorship, including
49 | the original version of the Work and any modifications or additions
50 | to that Work or Derivative Works thereof, that is intentionally
51 | submitted to Licensor for inclusion in the Work by the copyright owner
52 | or by an individual or Legal Entity authorized to submit on behalf of
53 | the copyright owner. For the purposes of this definition, "submitted"
54 | means any form of electronic, verbal, or written communication sent
55 | to the Licensor or its representatives, including but not limited to
56 | communication on electronic mailing lists, source code control systems,
57 | and issue tracking systems that are managed by, or on behalf of, the
58 | Licensor for the purpose of discussing and improving the Work, but
59 | excluding communication that is conspicuously marked or otherwise
60 | designated in writing by the copyright owner as "Not a Contribution."
61 |
62 | "Contributor" shall mean Licensor and any individual or Legal Entity
63 | on behalf of whom a Contribution has been received by Licensor and
64 | subsequently incorporated within the Work.
65 |
66 | 2. Grant of Copyright License. Subject to the terms and conditions of
67 | this License, each Contributor hereby grants to You a perpetual,
68 | worldwide, non-exclusive, no-charge, royalty-free, irrevocable
69 | copyright license to reproduce, prepare Derivative Works of,
70 | publicly display, publicly perform, sublicense, and distribute the
71 | Work and such Derivative Works in Source or Object form.
72 |
73 | 3. Grant of Patent License. Subject to the terms and conditions of
74 | this License, each Contributor hereby grants to You a perpetual,
75 | worldwide, non-exclusive, no-charge, royalty-free, irrevocable
76 | (except as stated in this section) patent license to make, have made,
77 | use, offer to sell, sell, import, and otherwise transfer the Work,
78 | where such license applies only to those patent claims licensable
79 | by such Contributor that are necessarily infringed by their
80 | Contribution(s) alone or by combination of their Contribution(s)
81 | with the Work to which such Contribution(s) was submitted. If You
82 | institute patent litigation against any entity (including a
83 | cross-claim or counterclaim in a lawsuit) alleging that the Work
84 | or a Contribution incorporated within the Work constitutes direct
85 | or contributory patent infringement, then any patent licenses
86 | granted to You under this License for that Work shall terminate
87 | as of the date such litigation is filed.
88 |
89 | 4. Redistribution. You may reproduce and distribute copies of the
90 | Work or Derivative Works thereof in any medium, with or without
91 | modifications, and in Source or Object form, provided that You
92 | meet the following conditions:
93 |
94 | (a) You must give any other recipients of the Work or
95 | Derivative Works a copy of this License; and
96 |
97 | (b) You must cause any modified files to carry prominent notices
98 | stating that You changed the files; and
99 |
100 | (c) You must retain, in the Source form of any Derivative Works
101 | that You distribute, all copyright, patent, trademark, and
102 | attribution notices from the Source form of the Work,
103 | excluding those notices that do not pertain to any part of
104 | the Derivative Works; and
105 |
106 | (d) If the Work includes a "NOTICE" text file as part of its
107 | distribution, then any Derivative Works that You distribute must
108 | include a readable copy of the attribution notices contained
109 | within such NOTICE file, excluding those notices that do not
110 | pertain to any part of the Derivative Works, in at least one
111 | of the following places: within a NOTICE text file distributed
112 | as part of the Derivative Works; within the Source form or
113 | documentation, if provided along with the Derivative Works; or,
114 | within a display generated by the Derivative Works, if and
115 | wherever such third-party notices normally appear. The contents
116 | of the NOTICE file are for informational purposes only and
117 | do not modify the License. You may add Your own attribution
118 | notices within Derivative Works that You distribute, alongside
119 | or as an addendum to the NOTICE text from the Work, provided
120 | that such additional attribution notices cannot be construed
121 | as modifying the License.
122 |
123 | You may add Your own copyright statement to Your modifications and
124 | may provide additional or different license terms and conditions
125 | for use, reproduction, or distribution of Your modifications, or
126 | for any such Derivative Works as a whole, provided Your use,
127 | reproduction, and distribution of the Work otherwise complies with
128 | the conditions stated in this License.
129 |
130 | 5. Submission of Contributions. Unless You explicitly state otherwise,
131 | any Contribution intentionally submitted for inclusion in the Work
132 | by You to the Licensor shall be under the terms and conditions of
133 | this License, without any additional terms or conditions.
134 | Notwithstanding the above, nothing herein shall supersede or modify
135 | the terms of any separate license agreement you may have executed
136 | with Licensor regarding such Contributions.
137 |
138 | 6. Trademarks. This License does not grant permission to use the trade
139 | names, trademarks, service marks, or product names of the Licensor,
140 | except as required for reasonable and customary use in describing the
141 | origin of the Work and reproducing the content of the NOTICE file.
142 |
143 | 7. Disclaimer of Warranty. Unless required by applicable law or
144 | agreed to in writing, Licensor provides the Work (and each
145 | Contributor provides its Contributions) on an "AS IS" BASIS,
146 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
147 | implied, including, without limitation, any warranties or conditions
148 | of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
149 | PARTICULAR PURPOSE. You are solely responsible for determining the
150 | appropriateness of using or redistributing the Work and assume any
151 | risks associated with Your exercise of permissions under this License.
152 |
153 | 8. Limitation of Liability. In no event and under no legal theory,
154 | whether in tort (including negligence), contract, or otherwise,
155 | unless required by applicable law (such as deliberate and grossly
156 | negligent acts) or agreed to in writing, shall any Contributor be
157 | liable to You for damages, including any direct, indirect, special,
158 | incidental, or consequential damages of any character arising as a
159 | result of this License or out of the use or inability to use the
160 | Work (including but not limited to damages for loss of goodwill,
161 | work stoppage, computer failure or malfunction, or any and all
162 | other commercial damages or losses), even if such Contributor
163 | has been advised of the possibility of such damages.
164 |
165 | 9. Accepting Warranty or Additional Liability. While redistributing
166 | the Work or Derivative Works thereof, You may choose to offer,
167 | and charge a fee for, acceptance of support, warranty, indemnity,
168 | or other liability obligations and/or rights consistent with this
169 | License. However, in accepting such obligations, You may act only
170 | on Your own behalf and on Your sole responsibility, not on behalf
171 | of any other Contributor, and only if You agree to indemnify,
172 | defend, and hold each Contributor harmless for any liability
173 | incurred by, or claims asserted against, such Contributor by reason
174 | of your accepting any such warranty or additional liability.
175 |
176 | END OF TERMS AND CONDITIONS
177 |
178 | APPENDIX: How to apply the Apache License to your work.
179 |
180 | To apply the Apache License to your work, attach the following
181 | boilerplate notice, with the fields enclosed by brackets "[]"
182 | replaced with your own identifying information. (Don't include
183 | the brackets!) The text should be enclosed in the appropriate
184 | comment syntax for the file format. We also recommend that a
185 | file or class name and description of purpose be included on the
186 | same "printed page" as the copyright notice for easier
187 | identification within third-party archives.
188 |
189 | Copyright [yyyy] [name of copyright owner]
190 |
191 | Licensed under the Apache License, Version 2.0 (the "License");
192 | you may not use this file except in compliance with the License.
193 | You may obtain a copy of the License at
194 |
195 | http://www.apache.org/licenses/LICENSE-2.0
196 |
197 | Unless required by applicable law or agreed to in writing, software
198 | distributed under the License is distributed on an "AS IS" BASIS,
199 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
200 | See the License for the specific language governing permissions and
201 | limitations under the License.
--------------------------------------------------------------------------------
/licenses/LICENSE_omertov:
--------------------------------------------------------------------------------
1 | MIT License
2 |
3 | Copyright (c) 2021 omertov
4 |
5 | Permission is hereby granted, free of charge, to any person obtaining a copy
6 | of this software and associated documentation files (the "Software"), to deal
7 | in the Software without restriction, including without limitation the rights
8 | to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9 | copies of the Software, and to permit persons to whom the Software is
10 | furnished to do so, subject to the following conditions:
11 |
12 | The above copyright notice and this permission notice shall be included in all
13 | copies or substantial portions of the Software.
14 |
15 | THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16 | IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17 | FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18 | AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19 | LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20 | OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21 | SOFTWARE.
--------------------------------------------------------------------------------
/licenses/LICENSE_rosinality:
--------------------------------------------------------------------------------
1 | MIT License
2 |
3 | Copyright (c) 2019 Kim Seonghyeon
4 |
5 | Permission is hereby granted, free of charge, to any person obtaining a copy
6 | of this software and associated documentation files (the "Software"), to deal
7 | in the Software without restriction, including without limitation the rights
8 | to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9 | copies of the Software, and to permit persons to whom the Software is
10 | furnished to do so, subject to the following conditions:
11 |
12 | The above copyright notice and this permission notice shall be included in all
13 | copies or substantial portions of the Software.
14 |
15 | THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16 | IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17 | FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18 | AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19 | LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20 | OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21 | SOFTWARE.
--------------------------------------------------------------------------------
/models/.ipynb_checkpoints/e4e-checkpoint.py:
--------------------------------------------------------------------------------
1 | """
2 | This file defines the core research contribution
3 | """
4 | import math
5 | import torch
6 | from torch import nn
7 |
8 | from models.stylegan2.model import Generator
9 | from configs.paths_config import model_paths
10 | from models.encoders import restyle_e4e_encoders
11 | from utils.model_utils import RESNET_MAPPING
12 |
13 | from models.stylegan2.model import EqualLinear
14 |
15 | class e4e(nn.Module):
16 |
17 | def __init__(self, opts):
18 | super(e4e, self).__init__()
19 | self.set_opts(opts)
20 | self.n_styles = int(math.log(self.opts.output_size, 2)) * 2 - 2
21 | # Define architecture
22 | self.encoder = self.set_encoder()
23 | self.decoder = Generator(self.opts.output_size, 512, 8, channel_multiplier=2)
24 | self.face_pool = torch.nn.AdaptiveAvgPool2d((256, 256))
25 | # Load weights if needed
26 | self.load_weights()
27 |
28 | def set_encoder(self):
29 | if self.opts.encoder_type == 'ProgressiveBackboneEncoder':
30 | encoder = restyle_e4e_encoders.ProgressiveBackboneEncoder(50, 'ir_se', self.n_styles, self.opts)
31 | elif self.opts.encoder_type == 'ResNetProgressiveBackboneEncoder':
32 | encoder = restyle_e4e_encoders.ResNetProgressiveBackboneEncoder(self.n_styles, self.opts)
33 | else:
34 | raise Exception(f'{self.opts.encoder_type} is not a valid encoders')
35 | return encoder
36 |
37 | def load_weights(self):
38 | if self.opts.checkpoint_path is not None:
39 | print(f'Loading ReStyle e4e from checkpoint: {self.opts.checkpoint_path}')
40 | ckpt = torch.load(self.opts.checkpoint_path, map_location='cpu')
41 | self.encoder.load_state_dict(self.__get_keys(ckpt, 'encoder'), strict=False)
42 | self.decoder.load_state_dict(self.__get_keys(ckpt, 'decoder'), strict=True)
43 | self.__load_latent_avg(ckpt)
44 | else:
45 | encoder_ckpt = self.__get_encoder_checkpoint()
46 | self.encoder.load_state_dict(encoder_ckpt, strict=False)
47 | print(f'Loading decoder weights from pretrained path: {self.opts.stylegan_weights}')
48 | ckpt = torch.load(self.opts.stylegan_weights)
49 | self.decoder.load_state_dict(ckpt['g_ema'], strict=True)
50 | self.__load_latent_avg(ckpt, repeat=self.n_styles)
51 |
52 | def forward(self, x, target_id_feat=None, latent=None, resize=True, latent_mask=None, input_code=False, randomize_noise=True,
53 | inject_latent=None, return_latents=False, alpha=None, average_code=False, input_is_full=False):
54 | if input_code:
55 | codes = x
56 | else:
57 | codes = self.encoder(x,target_id_feat)
58 | # residual step
59 | if x.shape[1] == self.opts.input_nc and latent is not None:
60 | # learn error with respect to previous iteration
61 | codes = codes + latent
62 | else:
63 | # first iteration is with respect to the avg latent code
64 | codes = codes + self.latent_avg.repeat(codes.shape[0], 1, 1)
65 |
66 | if latent_mask is not None:
67 | for i in latent_mask:
68 | if inject_latent is not None:
69 | if alpha is not None:
70 | codes[:, i] = alpha * inject_latent[:, i] + (1 - alpha) * codes[:, i]
71 | else:
72 | codes[:, i] = inject_latent[:, i]
73 | else:
74 | codes[:, i] = 0
75 |
76 | if average_code:
77 | input_is_latent = True
78 | else:
79 | input_is_latent = (not input_code) or (input_is_full)
80 |
81 | images, result_latent = self.decoder([codes],
82 | input_is_latent=input_is_latent,
83 | randomize_noise=randomize_noise,
84 | return_latents=return_latents)
85 |
86 | if resize:
87 | images = self.face_pool(images)
88 |
89 | if return_latents:
90 | return images, result_latent
91 | else:
92 | return images
93 |
94 | def set_opts(self, opts):
95 | self.opts = opts
96 |
97 | def __load_latent_avg(self, ckpt, repeat=None):
98 | if 'latent_avg' in ckpt:
99 | self.latent_avg = ckpt['latent_avg'].to(self.opts.device)
100 | if repeat is not None:
101 | self.latent_avg = self.latent_avg.repeat(repeat, 1)
102 | else:
103 | self.latent_avg = None
104 |
105 | def __get_encoder_checkpoint(self):
106 | if "ffhq" in self.opts.dataset_type:
107 | print('Loading encoders weights from irse50!')
108 | encoder_ckpt = torch.load(model_paths['ir_se50'])
109 | # Transfer the RGB input of the irse50 network to the first 3 input channels of pSp's encoder
110 | if self.opts.input_nc != 3:
111 | shape = encoder_ckpt['input_layer.0.weight'].shape
112 | altered_input_layer = torch.randn(shape[0], self.opts.input_nc, shape[2], shape[3], dtype=torch.float32)
113 | altered_input_layer[:, :3, :, :] = encoder_ckpt['input_layer.0.weight']
114 | encoder_ckpt['input_layer.0.weight'] = altered_input_layer
115 | return encoder_ckpt
116 | else:
117 | print('Loading encoders weights from resnet34!')
118 | encoder_ckpt = torch.load(model_paths['resnet34'])
119 | # Transfer the RGB input of the resnet34 network to the first 3 input channels of pSp's encoder
120 | if self.opts.input_nc != 3:
121 | shape = encoder_ckpt['conv1.weight'].shape
122 | altered_input_layer = torch.randn(shape[0], self.opts.input_nc, shape[2], shape[3], dtype=torch.float32)
123 | altered_input_layer[:, :3, :, :] = encoder_ckpt['conv1.weight']
124 | encoder_ckpt['conv1.weight'] = altered_input_layer
125 | mapped_encoder_ckpt = dict(encoder_ckpt)
126 | for p, v in encoder_ckpt.items():
127 | for original_name, psp_name in RESNET_MAPPING.items():
128 | if original_name in p:
129 | mapped_encoder_ckpt[p.replace(original_name, psp_name)] = v
130 | mapped_encoder_ckpt.pop(p)
131 | return encoder_ckpt
132 |
133 | @staticmethod
134 | def __get_keys(d, name):
135 | if 'state_dict' in d:
136 | d = d['state_dict']
137 | d_filt = {k[len(name) + 1:]: v for k, v in d.items() if k[:len(name)] == name}
138 | return d_filt
139 |
--------------------------------------------------------------------------------
/models/__init__.py:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/1jsingh/paint2pix/971d1ea06ef6cbcc555ad09a365bf1621ce13f08/models/__init__.py
--------------------------------------------------------------------------------
/models/e4e.py:
--------------------------------------------------------------------------------
1 | """
2 | This file defines the core research contribution
3 | """
4 | import math
5 | import torch
6 | from torch import nn
7 |
8 | from models.stylegan2.model import Generator
9 | from configs.paths_config import model_paths
10 | from models.encoders import restyle_e4e_encoders
11 | from utils.model_utils import RESNET_MAPPING
12 |
13 | from models.stylegan2.model import EqualLinear
14 | import streamlit as st
15 |
16 | class e4e(nn.Module):
17 |
18 | def __init__(self, opts):
19 | super(e4e, self).__init__()
20 | self.set_opts(opts)
21 | self.n_styles = int(math.log(self.opts.output_size, 2)) * 2 - 2
22 | # Define architecture
23 | self.encoder = self.set_encoder()
24 | self.decoder = Generator(self.opts.output_size, 512, 8, channel_multiplier=2)
25 | self.face_pool = torch.nn.AdaptiveAvgPool2d((256, 256))
26 | # Load weights if needed
27 | self.load_weights()
28 |
29 | def set_encoder(self):
30 | if self.opts.encoder_type == 'ProgressiveBackboneEncoder':
31 | encoder = restyle_e4e_encoders.ProgressiveBackboneEncoder(50, 'ir_se', self.n_styles, self.opts)
32 | elif self.opts.encoder_type == 'ResNetProgressiveBackboneEncoder':
33 | encoder = restyle_e4e_encoders.ResNetProgressiveBackboneEncoder(self.n_styles, self.opts)
34 | else:
35 | raise Exception(f'{self.opts.encoder_type} is not a valid encoders')
36 | return encoder
37 |
38 | def load_weights(self):
39 | if self.opts.checkpoint_path is not None:
40 | print(f'Loading ReStyle e4e from checkpoint: {self.opts.checkpoint_path}')
41 | ckpt = torch.load(self.opts.checkpoint_path, map_location='cpu')
42 | encoder_ckpt = self.__get_keys(ckpt, 'encoder')
43 |
44 | # if self.opts.input_nc != 6:
45 | # print ("here ...")
46 | # shape = encoder_ckpt['input_layer.0.weight'].shape
47 | # altered_input_layer1 = 0.*torch.randn(shape[0], self.opts.input_nc, shape[2], shape[3], dtype=torch.float32)
48 | # altered_input_layer1[:, :6, :, :] = encoder_ckpt['input_layer.0.weight']
49 |
50 | # altered_input_layer2 = 0.*torch.randn(shape[0], self.opts.input_nc, shape[2], shape[3], dtype=torch.float32)
51 | # altered_input_layer2[:, 6:, :, :] = encoder_ckpt['input_layer.0.weight']
52 | # encoder_ckpt['input_layer_updated_canvas.0.weight'] = altered_input_layer2
53 | # encoder_ckpt['input_layer.0.weight'] = altered_input_layer1
54 |
55 | self.encoder.load_state_dict(encoder_ckpt, strict=False)
56 | # self.encoder.load_state_dict(self.__get_keys(ckpt, 'encoder'), strict=False)
57 | self.decoder.load_state_dict(self.__get_keys(ckpt, 'decoder'), strict=True)
58 | self.__load_latent_avg(ckpt)
59 | else:
60 | encoder_ckpt = self.__get_encoder_checkpoint()
61 | self.encoder.load_state_dict(encoder_ckpt, strict=False)
62 | print(f'Loading decoder weights from pretrained path: {self.opts.stylegan_weights}')
63 | ckpt = torch.load(self.opts.stylegan_weights)
64 | self.decoder.load_state_dict(ckpt['g_ema'], strict=True)
65 | self.__load_latent_avg(ckpt, repeat=self.n_styles)
66 |
67 | def forward(self, x, target_id_feat=None, latent=None, resize=True, latent_mask=None, input_code=False, randomize_noise=True,
68 | inject_latent=None, return_latents=False, alpha=None, average_code=False, input_is_full=False, get_multiple_codes=False):
69 |
70 | if input_code:
71 | codes = x
72 | else:
73 | if get_multiple_codes:
74 | codes_canvas0, codes_canvas1 = self.encoder(x,target_id_feat,get_multiple_codes)
75 | codes = torch.cat([codes_canvas0, codes_canvas1],axis=0)
76 | else:
77 | codes = self.encoder(x,target_id_feat)
78 | # print (codes.shape,self.latent_avg.shape,self.latent_avg.repeat(codes.shape[0], 1, 1).shape)
79 | # residual step
80 | if x.shape[1] == self.opts.input_nc and latent is not None:
81 | # learn error with respect to previous iteration
82 | codes = codes + latent
83 | else:
84 | # first iteration is with respect to the avg latent code
85 | codes = codes + self.latent_avg.repeat(codes.shape[0], 1, 1)
86 |
87 | if latent_mask is not None:
88 | for i in latent_mask:
89 | if inject_latent is not None:
90 | if alpha is not None:
91 | codes[:, i] = alpha * inject_latent[:, i] + (1 - alpha) * codes[:, i]
92 | else:
93 | codes[:, i] = inject_latent[:, i]
94 | else:
95 | codes[:, i] = 0
96 |
97 | if average_code:
98 | input_is_latent = True
99 | else:
100 | input_is_latent = (not input_code) or (input_is_full)
101 |
102 | images, result_latent = self.decoder([codes],
103 | input_is_latent=input_is_latent,
104 | randomize_noise=randomize_noise,
105 | return_latents=return_latents)
106 |
107 | if resize:
108 | images = self.face_pool(images)
109 |
110 | if return_latents:
111 | return images, result_latent
112 | else:
113 | return images
114 |
115 | def set_opts(self, opts):
116 | self.opts = opts
117 |
118 | def __load_latent_avg(self, ckpt, repeat=None):
119 | if 'latent_avg' in ckpt:
120 | self.latent_avg = ckpt['latent_avg'].to(self.opts.device)
121 | if repeat is not None:
122 | self.latent_avg = self.latent_avg.repeat(repeat, 1)
123 | else:
124 | self.latent_avg = None
125 |
126 | def __get_encoder_checkpoint(self):
127 | if "ffhq" in self.opts.dataset_type:
128 | print('Loading encoders weights from irse50!')
129 | encoder_ckpt = torch.load(model_paths['ir_se50'])
130 | # Transfer the RGB input of the irse50 network to the first 3 input channels of pSp's encoder
131 | if self.opts.input_nc != 3:
132 | shape = encoder_ckpt['input_layer.0.weight'].shape
133 | altered_input_layer = torch.randn(shape[0], self.opts.input_nc, shape[2], shape[3], dtype=torch.float32)
134 | altered_input_layer[:, :3, :, :] = encoder_ckpt['input_layer.0.weight']
135 | encoder_ckpt['input_layer.0.weight'] = altered_input_layer
136 | return encoder_ckpt
137 | else:
138 | print('Loading encoders weights from resnet34!')
139 | encoder_ckpt = torch.load(model_paths['resnet34'])
140 | # Transfer the RGB input of the resnet34 network to the first 3 input channels of pSp's encoder
141 | if self.opts.input_nc != 3:
142 | shape = encoder_ckpt['conv1.weight'].shape
143 | altered_input_layer = torch.randn(shape[0], self.opts.input_nc, shape[2], shape[3], dtype=torch.float32)
144 | altered_input_layer[:, :3, :, :] = encoder_ckpt['conv1.weight']
145 | encoder_ckpt['conv1.weight'] = altered_input_layer
146 | mapped_encoder_ckpt = dict(encoder_ckpt)
147 | for p, v in encoder_ckpt.items():
148 | for original_name, psp_name in RESNET_MAPPING.items():
149 | if original_name in p:
150 | mapped_encoder_ckpt[p.replace(original_name, psp_name)] = v
151 | mapped_encoder_ckpt.pop(p)
152 | return encoder_ckpt
153 |
154 | @staticmethod
155 | def __get_keys(d, name):
156 | if 'state_dict' in d:
157 | d = d['state_dict']
158 | d_filt = {k[len(name) + 1:]: v for k, v in d.items() if k[:len(name)] == name}
159 | return d_filt
160 |
--------------------------------------------------------------------------------
/models/e4e_modules/__init__.py:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/1jsingh/paint2pix/971d1ea06ef6cbcc555ad09a365bf1621ce13f08/models/e4e_modules/__init__.py
--------------------------------------------------------------------------------
/models/e4e_modules/discriminator.py:
--------------------------------------------------------------------------------
1 | from torch import nn
2 |
3 |
4 | class LatentCodesDiscriminator(nn.Module):
5 | def __init__(self, style_dim, n_mlp):
6 | super().__init__()
7 |
8 | self.style_dim = style_dim
9 |
10 | layers = []
11 | for i in range(n_mlp-1):
12 | layers.append(
13 | nn.Linear(style_dim, style_dim)
14 | )
15 | layers.append(nn.LeakyReLU(0.2))
16 | layers.append(nn.Linear(512, 1))
17 | self.mlp = nn.Sequential(*layers)
18 |
19 | def forward(self, w):
20 | return self.mlp(w)
21 |
--------------------------------------------------------------------------------
/models/e4e_modules/latent_codes_pool.py:
--------------------------------------------------------------------------------
1 | import random
2 | import torch
3 |
4 |
5 | class LatentCodesPool:
6 | """This class implements latent codes buffer that stores previously generated w latent codes.
7 | This buffer enables us to update discriminators using a history of generated w's
8 | rather than the ones produced by the latest encoder.
9 | """
10 |
11 | def __init__(self, pool_size):
12 | """Initialize the ImagePool class
13 | Parameters:
14 | pool_size (int) -- the size of image buffer, if pool_size=0, no buffer will be created
15 | """
16 | self.pool_size = pool_size
17 | if self.pool_size > 0: # create an empty pool
18 | self.num_ws = 0
19 | self.ws = []
20 |
21 | def query(self, ws):
22 | """Return w's from the pool.
23 | Parameters:
24 | ws: the latest generated w's from the generator
25 | Returns w's from the buffer.
26 | By 50/100, the buffer will return input w's.
27 | By 50/100, the buffer will return w's previously stored in the buffer,
28 | and insert the current w's to the buffer.
29 | """
30 | if self.pool_size == 0: # if the buffer size is 0, do nothing
31 | return ws
32 | return_ws = []
33 | for w in ws: # ws.shape: (batch, 512) or (batch, n_latent, 512)
34 | # w = torch.unsqueeze(image.data, 0)
35 | if w.ndim == 2:
36 | i = random.randint(0, len(w) - 1) # apply a random latent index as a candidate
37 | w = w[i]
38 | self.handle_w(w, return_ws)
39 | return_ws = torch.stack(return_ws, 0) # collect all the images and return
40 | return return_ws
41 |
42 | def handle_w(self, w, return_ws):
43 | if self.num_ws < self.pool_size: # if the buffer is not full; keep inserting current codes to the buffer
44 | self.num_ws = self.num_ws + 1
45 | self.ws.append(w)
46 | return_ws.append(w)
47 | else:
48 | p = random.uniform(0, 1)
49 | if p > 0.5: # by 50% chance, the buffer will return a previously stored latent code, and insert the current code into the buffer
50 | random_id = random.randint(0, self.pool_size - 1) # randint is inclusive
51 | tmp = self.ws[random_id].clone()
52 | self.ws[random_id] = w
53 | return_ws.append(tmp)
54 | else: # by another 50% chance, the buffer will return the current image
55 | return_ws.append(w)
56 |
--------------------------------------------------------------------------------
/models/encoders/.ipynb_checkpoints/map2style-checkpoint.py:
--------------------------------------------------------------------------------
1 | import numpy as np
2 | from torch import nn
3 | from torch.nn import Conv2d, Module
4 |
5 | from models.stylegan2.model import EqualLinear
6 |
7 |
8 | class GradualStyleBlock(Module):
9 | def __init__(self, in_c, out_c, spatial):
10 | super(GradualStyleBlock, self).__init__()
11 | self.out_c = out_c
12 | self.spatial = spatial
13 | num_pools = int(np.log2(spatial))
14 | modules = []
15 | modules += [Conv2d(in_c, out_c, kernel_size=3, stride=2, padding=1),
16 | nn.LeakyReLU()]
17 | for i in range(num_pools - 1):
18 | modules += [
19 | Conv2d(out_c, out_c, kernel_size=3, stride=2, padding=1),
20 | nn.LeakyReLU()
21 | ]
22 | self.convs = nn.Sequential(*modules)
23 | self.linear = EqualLinear(out_c, out_c, lr_mul=1)
24 |
25 | def forward(self, x):
26 | x = self.convs(x)
27 | x = x.view(-1, self.out_c)
28 | x = self.linear(x)
29 | return x
30 |
--------------------------------------------------------------------------------
/models/encoders/.ipynb_checkpoints/restyle_e4e_encoders-checkpoint.py:
--------------------------------------------------------------------------------
1 | from enum import Enum
2 | from torch import nn
3 | from torch.nn import Conv2d, BatchNorm2d, PReLU, Sequential, Module
4 | from torchvision.models import resnet34
5 |
6 | from models.encoders.helpers import get_blocks, bottleneck_IR, bottleneck_IR_SE
7 | from models.encoders.map2style import GradualStyleBlock
8 |
9 | from models.stylegan2.model import EqualLinear
10 |
11 | class ProgressiveStage(Enum):
12 | WTraining = 0
13 | Delta1Training = 1
14 | Delta2Training = 2
15 | Delta3Training = 3
16 | Delta4Training = 4
17 | Delta5Training = 5
18 | Delta6Training = 6
19 | Delta7Training = 7
20 | Delta8Training = 8
21 | Delta9Training = 9
22 | Delta10Training = 10
23 | Delta11Training = 11
24 | Delta12Training = 12
25 | Delta13Training = 13
26 | Delta14Training = 14
27 | Delta15Training = 15
28 | Delta16Training = 16
29 | Delta17Training = 17
30 | Inference = 18
31 |
32 |
33 | class ProgressiveBackboneEncoder(Module):
34 | """
35 | The simpler backbone architecture used by ReStyle where all style vectors are extracted from the final 16x16 feature
36 | map of the encoder. This classes uses the simplified architecture applied over an ResNet IRSE50 backbone with the
37 | progressive training scheme from e4e_modules.
38 | Note this class is designed to be used for the human facial domain.
39 | """
40 | def __init__(self, num_layers, mode='ir', n_styles=18, opts=None):
41 | super(ProgressiveBackboneEncoder, self).__init__()
42 | assert num_layers in [50, 100, 152], 'num_layers should be 50,100, or 152'
43 | assert mode in ['ir', 'ir_se'], 'mode should be ir or ir_se'
44 | blocks = get_blocks(num_layers)
45 | if mode == 'ir':
46 | unit_module = bottleneck_IR
47 | elif mode == 'ir_se':
48 | unit_module = bottleneck_IR_SE
49 |
50 | self.input_layer = Sequential(Conv2d(opts.input_nc, 64, (3, 3), 1, 1, bias=False),
51 | BatchNorm2d(64),
52 | PReLU(64))
53 | modules = []
54 | for block in blocks:
55 | for bottleneck in block:
56 | modules.append(unit_module(bottleneck.in_channel,
57 | bottleneck.depth,
58 | bottleneck.stride))
59 | self.body = Sequential(*modules)
60 |
61 | self.styles = nn.ModuleList()
62 | self.style_count = n_styles
63 | for i in range(self.style_count):
64 | style = GradualStyleBlock(512, 512, 16)
65 | self.styles.append(style)
66 | self.progressive_stage = ProgressiveStage.Inference
67 |
68 | self.id_layers = nn.ModuleList()
69 | for i in range(self.style_count):
70 | id_layer = EqualLinear(512, 512, lr_mul=1)
71 | self.id_layers.append(id_layer)
72 |
73 | def get_deltas_starting_dimensions(self):
74 | ''' Get a list of the initial dimension of every delta from which it is applied '''
75 | return list(range(self.style_count)) # Each dimension has a delta applied to
76 |
77 | def set_progressive_stage(self, new_stage: ProgressiveStage):
78 | # In this encoder we train all the pyramid (At least as a first stage experiment
79 | self.progressive_stage = new_stage
80 | print('Changed progressive stage to: ', new_stage)
81 |
82 | def forward(self, x, target_id_feat=None):
83 | x = self.input_layer(x)
84 | x = self.body(x)
85 |
86 | # get initial w0 from first map2style layer
87 | w0 = self.styles[0](x)
88 | if target_id_feat is not None:
89 | w0 += self.id_layers[0](target_id_feat)
90 | w = w0.repeat(self.style_count, 1, 1).permute(1, 0, 2)
91 |
92 | # learn the deltas up to the current stage
93 | stage = self.progressive_stage.value
94 | for i in range(1, min(stage + 1, self.style_count)):
95 | delta_i = self.styles[i](x)
96 | if target_id_feat is not None:
97 | delta_i += self.id_layers[i](target_id_feat)
98 | w[:, i] += delta_i
99 | return w
100 |
101 |
102 | class ResNetProgressiveBackboneEncoder(Module):
103 | """
104 | The simpler backbone architecture used by ReStyle where all style vectors are extracted from the final 16x16 feature
105 | map of the encoder. This classes uses the simplified architecture applied over an ResNet34 backbone with the
106 | progressive training scheme from e4e_modules.
107 | """
108 | def __init__(self, n_styles=18, opts=None):
109 | super(ResNetProgressiveBackboneEncoder, self).__init__()
110 |
111 | self.conv1 = nn.Conv2d(opts.input_nc, 64, kernel_size=7, stride=2, padding=3, bias=False)
112 | self.bn1 = BatchNorm2d(64)
113 | self.relu = PReLU(64)
114 |
115 | resnet_basenet = resnet34(pretrained=True)
116 | blocks = [
117 | resnet_basenet.layer1,
118 | resnet_basenet.layer2,
119 | resnet_basenet.layer3,
120 | resnet_basenet.layer4
121 | ]
122 | modules = []
123 | for block in blocks:
124 | for bottleneck in block:
125 | modules.append(bottleneck)
126 | self.body = Sequential(*modules)
127 |
128 | self.styles = nn.ModuleList()
129 | self.style_count = n_styles
130 | for i in range(self.style_count):
131 | style = GradualStyleBlock(512, 512, 16)
132 | self.styles.append(style)
133 | self.progressive_stage = ProgressiveStage.Inference
134 |
135 | def get_deltas_starting_dimensions(self):
136 | ''' Get a list of the initial dimension of every delta from which it is applied '''
137 | return list(range(self.style_count)) # Each dimension has a delta applied to
138 |
139 | def set_progressive_stage(self, new_stage: ProgressiveStage):
140 | # In this encoder we train all the pyramid (At least as a first stage experiment
141 | self.progressive_stage = new_stage
142 | print('Changed progressive stage to: ', new_stage)
143 |
144 | def forward(self, x):
145 | x = self.conv1(x)
146 | x = self.bn1(x)
147 | x = self.relu(x)
148 | x = self.body(x)
149 |
150 | # get initial w0 from first map2style layer
151 | w0 = self.styles[0](x)
152 | w = w0.repeat(self.style_count, 1, 1).permute(1, 0, 2)
153 |
154 | # learn the deltas up to the current stage
155 | stage = self.progressive_stage.value
156 | for i in range(1, min(stage + 1, self.style_count)):
157 | delta_i = self.styles[i](x)
158 | w[:, i] += delta_i
159 | return w
160 |
--------------------------------------------------------------------------------
/models/encoders/__init__.py:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/1jsingh/paint2pix/971d1ea06ef6cbcc555ad09a365bf1621ce13f08/models/encoders/__init__.py
--------------------------------------------------------------------------------
/models/encoders/fpn_encoders.py:
--------------------------------------------------------------------------------
1 | import torch
2 | import torch.nn.functional as F
3 | from torch import nn
4 | from torch.nn import Conv2d, BatchNorm2d, PReLU, Sequential, Module
5 | from torchvision.models.resnet import resnet34
6 |
7 | from models.encoders.helpers import get_blocks, bottleneck_IR, bottleneck_IR_SE
8 | from models.encoders.map2style import GradualStyleBlock
9 |
10 |
11 | class GradualStyleEncoder(Module):
12 | """
13 | Original encoder architecture from pixel2style2pixel. This classes uses an FPN-based architecture applied over
14 | an ResNet IRSE-50 backbone.
15 | Note this class is designed to be used for the human facial domain.
16 | """
17 | def __init__(self, num_layers, mode='ir', n_styles=18, opts=None):
18 | super(GradualStyleEncoder, self).__init__()
19 | assert num_layers in [50, 100, 152], 'num_layers should be 50,100, or 152'
20 | assert mode in ['ir', 'ir_se'], 'mode should be ir or ir_se'
21 | blocks = get_blocks(num_layers)
22 | if mode == 'ir':
23 | unit_module = bottleneck_IR
24 | elif mode == 'ir_se':
25 | unit_module = bottleneck_IR_SE
26 | self.input_layer = Sequential(Conv2d(opts.input_nc, 64, (3, 3), 1, 1, bias=False),
27 | BatchNorm2d(64),
28 | PReLU(64))
29 | modules = []
30 | for block in blocks:
31 | for bottleneck in block:
32 | modules.append(unit_module(bottleneck.in_channel,
33 | bottleneck.depth,
34 | bottleneck.stride))
35 | self.body = Sequential(*modules)
36 |
37 | self.styles = nn.ModuleList()
38 | self.style_count = n_styles
39 | self.coarse_ind = 3
40 | self.middle_ind = 7
41 | for i in range(self.style_count):
42 | if i < self.coarse_ind:
43 | style = GradualStyleBlock(512, 512, 16)
44 | elif i < self.middle_ind:
45 | style = GradualStyleBlock(512, 512, 32)
46 | else:
47 | style = GradualStyleBlock(512, 512, 64)
48 | self.styles.append(style)
49 | self.latlayer1 = nn.Conv2d(256, 512, kernel_size=1, stride=1, padding=0)
50 | self.latlayer2 = nn.Conv2d(128, 512, kernel_size=1, stride=1, padding=0)
51 |
52 | def _upsample_add(self, x, y):
53 | _, _, H, W = y.size()
54 | return F.interpolate(x, size=(H, W), mode='bilinear', align_corners=True) + y
55 |
56 | def forward(self, x):
57 | x = self.input_layer(x)
58 |
59 | latents = []
60 | modulelist = list(self.body._modules.values())
61 | for i, l in enumerate(modulelist):
62 | x = l(x)
63 | if i == 6:
64 | c1 = x
65 | elif i == 20:
66 | c2 = x
67 | elif i == 23:
68 | c3 = x
69 |
70 | for j in range(self.coarse_ind):
71 | latents.append(self.styles[j](c3))
72 |
73 | p2 = self._upsample_add(c3, self.latlayer1(c2))
74 | for j in range(self.coarse_ind, self.middle_ind):
75 | latents.append(self.styles[j](p2))
76 |
77 | p1 = self._upsample_add(p2, self.latlayer2(c1))
78 | for j in range(self.middle_ind, self.style_count):
79 | latents.append(self.styles[j](p1))
80 |
81 | out = torch.stack(latents, dim=1)
82 | return out
83 |
84 |
85 | class ResNetGradualStyleEncoder(Module):
86 | """
87 | Original encoder architecture from pixel2style2pixel. This classes uses an FPN-based architecture applied over
88 | an ResNet34 backbone.
89 | """
90 | def __init__(self, n_styles=18, opts=None):
91 | super(ResNetGradualStyleEncoder, self).__init__()
92 |
93 | self.conv1 = nn.Conv2d(opts.input_nc, 64, kernel_size=7, stride=2, padding=3, bias=False)
94 | self.bn1 = BatchNorm2d(64)
95 | self.relu = PReLU(64)
96 |
97 | resnet_basenet = resnet34(pretrained=True)
98 | blocks = [
99 | resnet_basenet.layer1,
100 | resnet_basenet.layer2,
101 | resnet_basenet.layer3,
102 | resnet_basenet.layer4
103 | ]
104 |
105 | modules = []
106 | for block in blocks:
107 | for bottleneck in block:
108 | modules.append(bottleneck)
109 |
110 | self.body = Sequential(*modules)
111 |
112 | self.styles = nn.ModuleList()
113 | self.style_count = n_styles
114 | self.coarse_ind = 3
115 | self.middle_ind = 7
116 | for i in range(self.style_count):
117 | if i < self.coarse_ind:
118 | style = GradualStyleBlock(512, 512, 16)
119 | elif i < self.middle_ind:
120 | style = GradualStyleBlock(512, 512, 32)
121 | else:
122 | style = GradualStyleBlock(512, 512, 64)
123 | self.styles.append(style)
124 | self.latlayer1 = nn.Conv2d(256, 512, kernel_size=1, stride=1, padding=0)
125 | self.latlayer2 = nn.Conv2d(128, 512, kernel_size=1, stride=1, padding=0)
126 |
127 | def _upsample_add(self, x, y):
128 | _, _, H, W = y.size()
129 | return F.interpolate(x, size=(H, W), mode='bilinear', align_corners=True) + y
130 |
131 | def forward(self, x):
132 | x = self.conv1(x)
133 | x = self.bn1(x)
134 | x = self.relu(x)
135 |
136 | latents = []
137 | modulelist = list(self.body._modules.values())
138 | for i, l in enumerate(modulelist):
139 | x = l(x)
140 | if i == 6:
141 | c1 = x
142 | elif i == 12:
143 | c2 = x
144 | elif i == 15:
145 | c3 = x
146 |
147 | for j in range(self.coarse_ind):
148 | latents.append(self.styles[j](c3))
149 |
150 | p2 = self._upsample_add(c3, self.latlayer1(c2))
151 | for j in range(self.coarse_ind, self.middle_ind):
152 | latents.append(self.styles[j](p2))
153 |
154 | p1 = self._upsample_add(p2, self.latlayer2(c1))
155 | for j in range(self.middle_ind, self.style_count):
156 | latents.append(self.styles[j](p1))
157 |
158 | out = torch.stack(latents, dim=1)
159 | return out
160 |
--------------------------------------------------------------------------------
/models/encoders/helpers.py:
--------------------------------------------------------------------------------
1 | from collections import namedtuple
2 | import torch
3 | from torch.nn import Conv2d, BatchNorm2d, PReLU, ReLU, Sigmoid, MaxPool2d, AdaptiveAvgPool2d, Sequential, Module
4 |
5 | """
6 | ArcFace implementation from [TreB1eN](https://github.com/TreB1eN/InsightFace_Pytorch)
7 | """
8 |
9 |
10 | class Flatten(Module):
11 | def forward(self, input):
12 | return input.view(input.size(0), -1)
13 |
14 |
15 | def l2_norm(input, axis=1):
16 | norm = torch.norm(input, 2, axis, True)
17 | output = torch.div(input, norm)
18 | return output
19 |
20 |
21 | class Bottleneck(namedtuple('Block', ['in_channel', 'depth', 'stride'])):
22 | """ A named tuple describing a ResNet block. """
23 |
24 |
25 | def get_block(in_channel, depth, num_units, stride=2):
26 | return [Bottleneck(in_channel, depth, stride)] + [Bottleneck(depth, depth, 1) for i in range(num_units - 1)]
27 |
28 |
29 | def get_blocks(num_layers):
30 | if num_layers == 50:
31 | blocks = [
32 | get_block(in_channel=64, depth=64, num_units=3),
33 | get_block(in_channel=64, depth=128, num_units=4),
34 | get_block(in_channel=128, depth=256, num_units=14),
35 | get_block(in_channel=256, depth=512, num_units=3)
36 | ]
37 | elif num_layers == 100:
38 | blocks = [
39 | get_block(in_channel=64, depth=64, num_units=3),
40 | get_block(in_channel=64, depth=128, num_units=13),
41 | get_block(in_channel=128, depth=256, num_units=30),
42 | get_block(in_channel=256, depth=512, num_units=3)
43 | ]
44 | elif num_layers == 152:
45 | blocks = [
46 | get_block(in_channel=64, depth=64, num_units=3),
47 | get_block(in_channel=64, depth=128, num_units=8),
48 | get_block(in_channel=128, depth=256, num_units=36),
49 | get_block(in_channel=256, depth=512, num_units=3)
50 | ]
51 | else:
52 | raise ValueError("Invalid number of layers: {}. Must be one of [50, 100, 152]".format(num_layers))
53 | return blocks
54 |
55 |
56 | class SEModule(Module):
57 | def __init__(self, channels, reduction):
58 | super(SEModule, self).__init__()
59 | self.avg_pool = AdaptiveAvgPool2d(1)
60 | self.fc1 = Conv2d(channels, channels // reduction, kernel_size=1, padding=0, bias=False)
61 | self.relu = ReLU(inplace=True)
62 | self.fc2 = Conv2d(channels // reduction, channels, kernel_size=1, padding=0, bias=False)
63 | self.sigmoid = Sigmoid()
64 |
65 | def forward(self, x):
66 | module_input = x
67 | x = self.avg_pool(x)
68 | x = self.fc1(x)
69 | x = self.relu(x)
70 | x = self.fc2(x)
71 | x = self.sigmoid(x)
72 | return module_input * x
73 |
74 |
75 | class bottleneck_IR(Module):
76 | def __init__(self, in_channel, depth, stride):
77 | super(bottleneck_IR, self).__init__()
78 | if in_channel == depth:
79 | self.shortcut_layer = MaxPool2d(1, stride)
80 | else:
81 | self.shortcut_layer = Sequential(
82 | Conv2d(in_channel, depth, (1, 1), stride, bias=False),
83 | BatchNorm2d(depth)
84 | )
85 | self.res_layer = Sequential(
86 | BatchNorm2d(in_channel),
87 | Conv2d(in_channel, depth, (3, 3), (1, 1), 1, bias=False), PReLU(depth),
88 | Conv2d(depth, depth, (3, 3), stride, 1, bias=False), BatchNorm2d(depth)
89 | )
90 |
91 | def forward(self, x):
92 | shortcut = self.shortcut_layer(x)
93 | res = self.res_layer(x)
94 | return res + shortcut
95 |
96 |
97 | class bottleneck_IR_SE(Module):
98 | def __init__(self, in_channel, depth, stride):
99 | super(bottleneck_IR_SE, self).__init__()
100 | if in_channel == depth:
101 | self.shortcut_layer = MaxPool2d(1, stride)
102 | else:
103 | self.shortcut_layer = Sequential(
104 | Conv2d(in_channel, depth, (1, 1), stride, bias=False),
105 | BatchNorm2d(depth)
106 | )
107 | self.res_layer = Sequential(
108 | BatchNorm2d(in_channel),
109 | Conv2d(in_channel, depth, (3, 3), (1, 1), 1, bias=False),
110 | PReLU(depth),
111 | Conv2d(depth, depth, (3, 3), stride, 1, bias=False),
112 | BatchNorm2d(depth),
113 | SEModule(depth, 16)
114 | )
115 |
116 | def forward(self, x):
117 | shortcut = self.shortcut_layer(x)
118 | res = self.res_layer(x)
119 | return res + shortcut
120 |
--------------------------------------------------------------------------------
/models/encoders/map2style.py:
--------------------------------------------------------------------------------
1 | import numpy as np
2 | from torch import nn
3 | from torch.nn import Conv2d, Module
4 |
5 | from models.stylegan2.model import EqualLinear
6 |
7 |
8 | class GradualStyleBlock(Module):
9 | def __init__(self, in_c, out_c, spatial):
10 | super(GradualStyleBlock, self).__init__()
11 | self.out_c = out_c
12 | self.spatial = spatial
13 | num_pools = int(np.log2(spatial))
14 | modules = []
15 | modules += [Conv2d(in_c, out_c, kernel_size=3, stride=2, padding=1),
16 | nn.LeakyReLU()]
17 | for i in range(num_pools - 1):
18 | modules += [
19 | Conv2d(out_c, out_c, kernel_size=3, stride=2, padding=1),
20 | nn.LeakyReLU()
21 | ]
22 | self.convs = nn.Sequential(*modules)
23 | self.linear = EqualLinear(out_c, out_c, lr_mul=1)
24 |
25 | def forward(self, x):
26 | x = self.convs(x)
27 | x = x.view(-1, self.out_c)
28 | x = self.linear(x)
29 | return x
30 |
--------------------------------------------------------------------------------
/models/encoders/model_irse.py:
--------------------------------------------------------------------------------
1 | from torch.nn import Linear, Conv2d, BatchNorm1d, BatchNorm2d, PReLU, Dropout, Sequential, Module
2 | from models.encoders.helpers import get_blocks, Flatten, bottleneck_IR, bottleneck_IR_SE, l2_norm
3 |
4 | """
5 | Modified Backbone implementation from [TreB1eN](https://github.com/TreB1eN/InsightFace_Pytorch)
6 | """
7 |
8 |
9 | class Backbone(Module):
10 | def __init__(self, input_size, num_layers, mode='ir', drop_ratio=0.4, affine=True):
11 | super(Backbone, self).__init__()
12 | assert input_size in [112, 224], "input_size should be 112 or 224"
13 | assert num_layers in [50, 100, 152], "num_layers should be 50, 100 or 152"
14 | assert mode in ['ir', 'ir_se'], "mode should be ir or ir_se"
15 | blocks = get_blocks(num_layers)
16 | if mode == 'ir':
17 | unit_module = bottleneck_IR
18 | elif mode == 'ir_se':
19 | unit_module = bottleneck_IR_SE
20 | self.input_layer = Sequential(Conv2d(3, 64, (3, 3), 1, 1, bias=False),
21 | BatchNorm2d(64),
22 | PReLU(64))
23 | if input_size == 112:
24 | self.output_layer = Sequential(BatchNorm2d(512),
25 | Dropout(drop_ratio),
26 | Flatten(),
27 | Linear(512 * 7 * 7, 512),
28 | BatchNorm1d(512, affine=affine))
29 | else:
30 | self.output_layer = Sequential(BatchNorm2d(512),
31 | Dropout(drop_ratio),
32 | Flatten(),
33 | Linear(512 * 14 * 14, 512),
34 | BatchNorm1d(512, affine=affine))
35 |
36 | modules = []
37 | for block in blocks:
38 | for bottleneck in block:
39 | modules.append(unit_module(bottleneck.in_channel,
40 | bottleneck.depth,
41 | bottleneck.stride))
42 | self.body = Sequential(*modules)
43 |
44 | def forward(self, x):
45 | x = self.input_layer(x)
46 | x = self.body(x)
47 | x = self.output_layer(x)
48 | return l2_norm(x)
49 |
50 |
51 | def IR_50(input_size):
52 | """Constructs a ir-50 model."""
53 | model = Backbone(input_size, num_layers=50, mode='ir', drop_ratio=0.4, affine=False)
54 | return model
55 |
56 |
57 | def IR_101(input_size):
58 | """Constructs a ir-101 model."""
59 | model = Backbone(input_size, num_layers=100, mode='ir', drop_ratio=0.4, affine=False)
60 | return model
61 |
62 |
63 | def IR_152(input_size):
64 | """Constructs a ir-152 model."""
65 | model = Backbone(input_size, num_layers=152, mode='ir', drop_ratio=0.4, affine=False)
66 | return model
67 |
68 |
69 | def IR_SE_50(input_size):
70 | """Constructs a ir_se-50 model."""
71 | model = Backbone(input_size, num_layers=50, mode='ir_se', drop_ratio=0.4, affine=False)
72 | return model
73 |
74 |
75 | def IR_SE_101(input_size):
76 | """Constructs a ir_se-101 model."""
77 | model = Backbone(input_size, num_layers=100, mode='ir_se', drop_ratio=0.4, affine=False)
78 | return model
79 |
80 |
81 | def IR_SE_152(input_size):
82 | """Constructs a ir_se-152 model."""
83 | model = Backbone(input_size, num_layers=152, mode='ir_se', drop_ratio=0.4, affine=False)
84 | return model
85 |
--------------------------------------------------------------------------------
/models/encoders/restyle_e4e_encoders.py:
--------------------------------------------------------------------------------
1 | from enum import Enum
2 | from torch import nn
3 | from torch.nn import Conv2d, BatchNorm2d, PReLU, Sequential, Module
4 | from torchvision.models import resnet34
5 |
6 | from models.encoders.helpers import get_blocks, bottleneck_IR, bottleneck_IR_SE
7 | from models.encoders.map2style import GradualStyleBlock
8 |
9 | from models.stylegan2.model import EqualLinear
10 |
11 | class ProgressiveStage(Enum):
12 | WTraining = 0
13 | Delta1Training = 1
14 | Delta2Training = 2
15 | Delta3Training = 3
16 | Delta4Training = 4
17 | Delta5Training = 5
18 | Delta6Training = 6
19 | Delta7Training = 7
20 | Delta8Training = 8
21 | Delta9Training = 9
22 | Delta10Training = 10
23 | Delta11Training = 11
24 | Delta12Training = 12
25 | Delta13Training = 13
26 | Delta14Training = 14
27 | Delta15Training = 15
28 | Delta16Training = 16
29 | Delta17Training = 17
30 | Inference = 18
31 |
32 |
33 | class ProgressiveBackboneEncoder(Module):
34 | """
35 | Paint2pix uses a Restyle-like architecture for building the canvas and identity encoder.
36 | This is a combined class which can be used as either the canvas or identity encoders
37 | depending on the input arguements 'is_canvas_encoder=False'
38 | """
39 | def __init__(self, num_layers, mode='ir', n_styles=18, opts=None, is_canvas_encoder=False):
40 | super(ProgressiveBackboneEncoder, self).__init__()
41 | assert num_layers in [50, 100, 152], 'num_layers should be 50,100, or 152'
42 | assert mode in ['ir', 'ir_se'], 'mode should be ir or ir_se'
43 | blocks = get_blocks(num_layers)
44 | if mode == 'ir':
45 | unit_module = bottleneck_IR
46 | elif mode == 'ir_se':
47 | unit_module = bottleneck_IR_SE
48 |
49 | self.input_layer = Sequential(Conv2d(opts.input_nc, 64, (3, 3), 1, 1, bias=False),
50 | BatchNorm2d(64),
51 | PReLU(64))
52 |
53 | self.is_canvas_encoder = opts.is_canvas_encoder
54 | if self.is_canvas_encoder:
55 | self.input_layer_updated_canvas = Sequential(Conv2d(opts.input_nc, 64, (3, 3), 1, 1, bias=False),
56 | BatchNorm2d(64),
57 | PReLU(64))
58 |
59 | modules = []
60 | for block in blocks:
61 | for bottleneck in block:
62 | modules.append(unit_module(bottleneck.in_channel,
63 | bottleneck.depth,
64 | bottleneck.stride))
65 | self.body = Sequential(*modules)
66 |
67 | self.styles = nn.ModuleList()
68 | self.style_count = n_styles
69 | for i in range(self.style_count):
70 | style = GradualStyleBlock(512, 512, 16)
71 | self.styles.append(style)
72 | self.progressive_stage = ProgressiveStage.Inference
73 |
74 | self.id_layers = nn.ModuleList()
75 | for i in range(self.style_count):
76 | id_layer = EqualLinear(512, 512, lr_mul=1)
77 | self.id_layers.append(id_layer)
78 |
79 | def get_deltas_starting_dimensions(self):
80 | ''' Get a list of the initial dimension of every delta from which it is applied '''
81 | return list(range(self.style_count)) # Each dimension has a delta applied to
82 |
83 | def set_progressive_stage(self, new_stage: ProgressiveStage):
84 | # In this encoder we train all the pyramid (At least as a first stage experiment
85 | self.progressive_stage = new_stage
86 | print('Changed progressive stage to: ', new_stage)
87 |
88 | def forward(self, x_, target_id_feat=None, get_multiple_codes=False):
89 | x = self.input_layer(x_)
90 | x = self.body(x)
91 |
92 | # get initial w0 from first map2style layer
93 | w0 = self.styles[0](x)
94 | if target_id_feat is not None:
95 | w0 += self.id_layers[0](target_id_feat)
96 | w = w0.repeat(self.style_count, 1, 1).permute(1, 0, 2)
97 |
98 | # learn the deltas up to the current stage
99 | stage = self.progressive_stage.value
100 | for i in range(1, min(stage + 1, self.style_count)):
101 | delta_i = self.styles[i](x)
102 | if target_id_feat is not None:
103 | delta_i += self.id_layers[i](target_id_feat)
104 | w[:, i] += delta_i
105 |
106 | if self.is_canvas_encoder and get_multiple_codes:
107 | w_canvas0 = w
108 | x = self.input_layer_updated_canvas(x_)
109 | x = self.body(x)
110 |
111 | # get initial w0 from first map2style layer
112 | w0 = self.styles[0](x)
113 | if target_id_feat is not None:
114 | w0 += self.id_layers[0](target_id_feat)
115 | w = w0.repeat(self.style_count, 1, 1).permute(1, 0, 2)
116 |
117 | # learn the deltas up to the current stage
118 | stage = self.progressive_stage.value
119 | for i in range(1, min(stage + 1, self.style_count)):
120 | delta_i = self.styles[i](x)
121 | if target_id_feat is not None:
122 | delta_i += self.id_layers[i](target_id_feat)
123 | w[:, i] += delta_i
124 | w_canvas1 = w
125 | return w_canvas0, w_canvas1
126 | else:
127 | return w
--------------------------------------------------------------------------------
/models/encoders/restyle_psp_encoders.py:
--------------------------------------------------------------------------------
1 | import torch
2 | from torch import nn
3 | from torch.nn import Conv2d, BatchNorm2d, PReLU, Sequential, Module
4 | from torchvision.models.resnet import resnet34
5 |
6 | from models.encoders.helpers import get_blocks, bottleneck_IR, bottleneck_IR_SE
7 | from models.encoders.map2style import GradualStyleBlock
8 |
9 |
10 | class BackboneEncoder(Module):
11 | """
12 | The simpler backbone architecture used by ReStyle where all style vectors are extracted from the final 16x16 feature
13 | map of the encoder. This classes uses the simplified architecture applied over an ResNet IRSE-50 backbone.
14 | Note this class is designed to be used for the human facial domain.
15 | """
16 | def __init__(self, num_layers, mode='ir', n_styles=18, opts=None):
17 | super(BackboneEncoder, self).__init__()
18 | assert num_layers in [50, 100, 152], 'num_layers should be 50,100, or 152'
19 | assert mode in ['ir', 'ir_se'], 'mode should be ir or ir_se'
20 | blocks = get_blocks(num_layers)
21 | if mode == 'ir':
22 | unit_module = bottleneck_IR
23 | elif mode == 'ir_se':
24 | unit_module = bottleneck_IR_SE
25 |
26 | self.input_layer = Sequential(Conv2d(opts.input_nc, 64, (3, 3), 1, 1, bias=False),
27 | BatchNorm2d(64),
28 | PReLU(64))
29 | modules = []
30 | for block in blocks:
31 | for bottleneck in block:
32 | modules.append(unit_module(bottleneck.in_channel,
33 | bottleneck.depth,
34 | bottleneck.stride))
35 | self.body = Sequential(*modules)
36 |
37 | self.styles = nn.ModuleList()
38 | self.style_count = n_styles
39 | for i in range(self.style_count):
40 | style = GradualStyleBlock(512, 512, 16)
41 | self.styles.append(style)
42 |
43 | def forward(self, x):
44 | x = self.input_layer(x)
45 | x = self.body(x)
46 | latents = []
47 | for j in range(self.style_count):
48 | latents.append(self.styles[j](x))
49 | out = torch.stack(latents, dim=1)
50 | return out
51 |
52 |
53 | class ResNetBackboneEncoder(Module):
54 | """
55 | The simpler backbone architecture used by ReStyle where all style vectors are extracted from the final 16x16 feature
56 | map of the encoder. This classes uses the simplified architecture applied over an ResNet34 backbone.
57 | """
58 | def __init__(self, n_styles=18, opts=None):
59 | super(ResNetBackboneEncoder, self).__init__()
60 |
61 | self.conv1 = nn.Conv2d(opts.input_nc, 64, kernel_size=7, stride=2, padding=3, bias=False)
62 | self.bn1 = BatchNorm2d(64)
63 | self.relu = PReLU(64)
64 |
65 | resnet_basenet = resnet34(pretrained=True)
66 | blocks = [
67 | resnet_basenet.layer1,
68 | resnet_basenet.layer2,
69 | resnet_basenet.layer3,
70 | resnet_basenet.layer4
71 | ]
72 | modules = []
73 | for block in blocks:
74 | for bottleneck in block:
75 | modules.append(bottleneck)
76 | self.body = Sequential(*modules)
77 |
78 | self.styles = nn.ModuleList()
79 | self.style_count = n_styles
80 | for i in range(self.style_count):
81 | style = GradualStyleBlock(512, 512, 16)
82 | self.styles.append(style)
83 |
84 | def forward(self, x):
85 | x = self.conv1(x)
86 | x = self.bn1(x)
87 | x = self.relu(x)
88 | x = self.body(x)
89 | latents = []
90 | for j in range(self.style_count):
91 | latents.append(self.styles[j](x))
92 | out = torch.stack(latents, dim=1)
93 | return out
94 |
--------------------------------------------------------------------------------
/models/mtcnn/__init__.py:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/1jsingh/paint2pix/971d1ea06ef6cbcc555ad09a365bf1621ce13f08/models/mtcnn/__init__.py
--------------------------------------------------------------------------------
/models/mtcnn/mtcnn.py:
--------------------------------------------------------------------------------
1 | import numpy as np
2 | import torch
3 | from PIL import Image
4 | from models.mtcnn.mtcnn_pytorch.src.get_nets import PNet, RNet, ONet
5 | from models.mtcnn.mtcnn_pytorch.src.box_utils import nms, calibrate_box, get_image_boxes, convert_to_square
6 | from models.mtcnn.mtcnn_pytorch.src.first_stage import run_first_stage
7 | from models.mtcnn.mtcnn_pytorch.src.align_trans import get_reference_facial_points, warp_and_crop_face
8 |
9 | device = 'cuda:0'
10 |
11 |
12 | class MTCNN():
13 | def __init__(self):
14 | print(device)
15 | self.pnet = PNet().to(device)
16 | self.rnet = RNet().to(device)
17 | self.onet = ONet().to(device)
18 | self.pnet.eval()
19 | self.rnet.eval()
20 | self.onet.eval()
21 | self.refrence = get_reference_facial_points(default_square=True)
22 |
23 | def align(self, img):
24 | _, landmarks = self.detect_faces(img)
25 | if len(landmarks) == 0:
26 | return None, None
27 | facial5points = [[landmarks[0][j], landmarks[0][j + 5]] for j in range(5)]
28 | warped_face, tfm = warp_and_crop_face(np.array(img), facial5points, self.refrence, crop_size=(112, 112))
29 | return Image.fromarray(warped_face), tfm
30 |
31 | def align_multi(self, img, limit=None, min_face_size=30.0):
32 | boxes, landmarks = self.detect_faces(img, min_face_size)
33 | if limit:
34 | boxes = boxes[:limit]
35 | landmarks = landmarks[:limit]
36 | faces = []
37 | tfms = []
38 | for landmark in landmarks:
39 | facial5points = [[landmark[j], landmark[j + 5]] for j in range(5)]
40 | warped_face, tfm = warp_and_crop_face(np.array(img), facial5points, self.refrence, crop_size=(112, 112))
41 | faces.append(Image.fromarray(warped_face))
42 | tfms.append(tfm)
43 | return boxes, faces, tfms
44 |
45 | def detect_faces(self, image, min_face_size=20.0,
46 | thresholds=[0.15, 0.25, 0.35],
47 | nms_thresholds=[0.7, 0.7, 0.7]):
48 | """
49 | Arguments:
50 | image: an instance of PIL.Image.
51 | min_face_size: a float number.
52 | thresholds: a list of length 3.
53 | nms_thresholds: a list of length 3.
54 |
55 | Returns:
56 | two float numpy arrays of shapes [n_boxes, 4] and [n_boxes, 10],
57 | bounding boxes and facial landmarks.
58 | """
59 |
60 | # BUILD AN IMAGE PYRAMID
61 | width, height = image.size
62 | min_length = min(height, width)
63 |
64 | min_detection_size = 12
65 | factor = 0.707 # sqrt(0.5)
66 |
67 | # scales for scaling the image
68 | scales = []
69 |
70 | # scales the image so that
71 | # minimum size that we can detect equals to
72 | # minimum face size that we want to detect
73 | m = min_detection_size / min_face_size
74 | min_length *= m
75 |
76 | factor_count = 0
77 | while min_length > min_detection_size:
78 | scales.append(m * factor ** factor_count)
79 | min_length *= factor
80 | factor_count += 1
81 |
82 | # STAGE 1
83 |
84 | # it will be returned
85 | bounding_boxes = []
86 |
87 | with torch.no_grad():
88 | # run P-Net on different scales
89 | for s in scales:
90 | boxes = run_first_stage(image, self.pnet, scale=s, threshold=thresholds[0])
91 | bounding_boxes.append(boxes)
92 |
93 | # collect boxes (and offsets, and scores) from different scales
94 | bounding_boxes = [i for i in bounding_boxes if i is not None]
95 | bounding_boxes = np.vstack(bounding_boxes)
96 |
97 | keep = nms(bounding_boxes[:, 0:5], nms_thresholds[0])
98 | bounding_boxes = bounding_boxes[keep]
99 |
100 | # use offsets predicted by pnet to transform bounding boxes
101 | bounding_boxes = calibrate_box(bounding_boxes[:, 0:5], bounding_boxes[:, 5:])
102 | # shape [n_boxes, 5]
103 |
104 | bounding_boxes = convert_to_square(bounding_boxes)
105 | bounding_boxes[:, 0:4] = np.round(bounding_boxes[:, 0:4])
106 |
107 | # STAGE 2
108 |
109 | img_boxes = get_image_boxes(bounding_boxes, image, size=24)
110 | img_boxes = torch.FloatTensor(img_boxes).to(device)
111 |
112 | output = self.rnet(img_boxes)
113 | offsets = output[0].cpu().data.numpy() # shape [n_boxes, 4]
114 | probs = output[1].cpu().data.numpy() # shape [n_boxes, 2]
115 |
116 | keep = np.where(probs[:, 1] > thresholds[1])[0]
117 | bounding_boxes = bounding_boxes[keep]
118 | bounding_boxes[:, 4] = probs[keep, 1].reshape((-1,))
119 | offsets = offsets[keep]
120 |
121 | keep = nms(bounding_boxes, nms_thresholds[1])
122 | bounding_boxes = bounding_boxes[keep]
123 | bounding_boxes = calibrate_box(bounding_boxes, offsets[keep])
124 | bounding_boxes = convert_to_square(bounding_boxes)
125 | bounding_boxes[:, 0:4] = np.round(bounding_boxes[:, 0:4])
126 |
127 | # STAGE 3
128 |
129 | img_boxes = get_image_boxes(bounding_boxes, image, size=48)
130 | if len(img_boxes) == 0:
131 | return [], []
132 | img_boxes = torch.FloatTensor(img_boxes).to(device)
133 | output = self.onet(img_boxes)
134 | landmarks = output[0].cpu().data.numpy() # shape [n_boxes, 10]
135 | offsets = output[1].cpu().data.numpy() # shape [n_boxes, 4]
136 | probs = output[2].cpu().data.numpy() # shape [n_boxes, 2]
137 |
138 | keep = np.where(probs[:, 1] > thresholds[2])[0]
139 | bounding_boxes = bounding_boxes[keep]
140 | bounding_boxes[:, 4] = probs[keep, 1].reshape((-1,))
141 | offsets = offsets[keep]
142 | landmarks = landmarks[keep]
143 |
144 | # compute landmark points
145 | width = bounding_boxes[:, 2] - bounding_boxes[:, 0] + 1.0
146 | height = bounding_boxes[:, 3] - bounding_boxes[:, 1] + 1.0
147 | xmin, ymin = bounding_boxes[:, 0], bounding_boxes[:, 1]
148 | landmarks[:, 0:5] = np.expand_dims(xmin, 1) + np.expand_dims(width, 1) * landmarks[:, 0:5]
149 | landmarks[:, 5:10] = np.expand_dims(ymin, 1) + np.expand_dims(height, 1) * landmarks[:, 5:10]
150 |
151 | bounding_boxes = calibrate_box(bounding_boxes, offsets)
152 | keep = nms(bounding_boxes, nms_thresholds[2], mode='min')
153 | bounding_boxes = bounding_boxes[keep]
154 | landmarks = landmarks[keep]
155 |
156 | return bounding_boxes, landmarks
157 |
--------------------------------------------------------------------------------
/models/mtcnn/mtcnn_pytorch/__init__.py:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/1jsingh/paint2pix/971d1ea06ef6cbcc555ad09a365bf1621ce13f08/models/mtcnn/mtcnn_pytorch/__init__.py
--------------------------------------------------------------------------------
/models/mtcnn/mtcnn_pytorch/src/__init__.py:
--------------------------------------------------------------------------------
1 | from .visualization_utils import show_bboxes
2 | from .detector import detect_faces
3 |
--------------------------------------------------------------------------------
/models/mtcnn/mtcnn_pytorch/src/align_trans.py:
--------------------------------------------------------------------------------
1 | # -*- coding: utf-8 -*-
2 | """
3 | Created on Mon Apr 24 15:43:29 2017
4 | @author: zhaoy
5 | """
6 | import numpy as np
7 | import cv2
8 |
9 | # from scipy.linalg import lstsq
10 | # from scipy.ndimage import geometric_transform # , map_coordinates
11 |
12 | from models.mtcnn.mtcnn_pytorch.src.matlab_cp2tform import get_similarity_transform_for_cv2
13 |
14 | # reference facial points, a list of coordinates (x,y)
15 | REFERENCE_FACIAL_POINTS = [
16 | [30.29459953, 51.69630051],
17 | [65.53179932, 51.50139999],
18 | [48.02519989, 71.73660278],
19 | [33.54930115, 92.3655014],
20 | [62.72990036, 92.20410156]
21 | ]
22 |
23 | DEFAULT_CROP_SIZE = (96, 112)
24 |
25 |
26 | class FaceWarpException(Exception):
27 | def __str__(self):
28 | return 'In File {}:{}'.format(
29 | __file__, super.__str__(self))
30 |
31 |
32 | def get_reference_facial_points(output_size=None,
33 | inner_padding_factor=0.0,
34 | outer_padding=(0, 0),
35 | default_square=False):
36 | """
37 | Function:
38 | ----------
39 | get reference 5 key points according to crop settings:
40 | 0. Set default crop_size:
41 | if default_square:
42 | crop_size = (112, 112)
43 | else:
44 | crop_size = (96, 112)
45 | 1. Pad the crop_size by inner_padding_factor in each side;
46 | 2. Resize crop_size into (output_size - outer_padding*2),
47 | pad into output_size with outer_padding;
48 | 3. Output reference_5point;
49 | Parameters:
50 | ----------
51 | @output_size: (w, h) or None
52 | size of aligned face image
53 | @inner_padding_factor: (w_factor, h_factor)
54 | padding factor for inner (w, h)
55 | @outer_padding: (w_pad, h_pad)
56 | each row is a pair of coordinates (x, y)
57 | @default_square: True or False
58 | if True:
59 | default crop_size = (112, 112)
60 | else:
61 | default crop_size = (96, 112);
62 | !!! make sure, if output_size is not None:
63 | (output_size - outer_padding)
64 | = some_scale * (default crop_size * (1.0 + inner_padding_factor))
65 | Returns:
66 | ----------
67 | @reference_5point: 5x2 np.array
68 | each row is a pair of transformed coordinates (x, y)
69 | """
70 | # print('\n===> get_reference_facial_points():')
71 |
72 | # print('---> Params:')
73 | # print(' output_size: ', output_size)
74 | # print(' inner_padding_factor: ', inner_padding_factor)
75 | # print(' outer_padding:', outer_padding)
76 | # print(' default_square: ', default_square)
77 |
78 | tmp_5pts = np.array(REFERENCE_FACIAL_POINTS)
79 | tmp_crop_size = np.array(DEFAULT_CROP_SIZE)
80 |
81 | # 0) make the inner region a square
82 | if default_square:
83 | size_diff = max(tmp_crop_size) - tmp_crop_size
84 | tmp_5pts += size_diff / 2
85 | tmp_crop_size += size_diff
86 |
87 | # print('---> default:')
88 | # print(' crop_size = ', tmp_crop_size)
89 | # print(' reference_5pts = ', tmp_5pts)
90 |
91 | if (output_size and
92 | output_size[0] == tmp_crop_size[0] and
93 | output_size[1] == tmp_crop_size[1]):
94 | # print('output_size == DEFAULT_CROP_SIZE {}: return default reference points'.format(tmp_crop_size))
95 | return tmp_5pts
96 |
97 | if (inner_padding_factor == 0 and
98 | outer_padding == (0, 0)):
99 | if output_size is None:
100 | # print('No paddings to do: return default reference points')
101 | return tmp_5pts
102 | else:
103 | raise FaceWarpException(
104 | 'No paddings to do, output_size must be None or {}'.format(tmp_crop_size))
105 |
106 | # check output size
107 | if not (0 <= inner_padding_factor <= 1.0):
108 | raise FaceWarpException('Not (0 <= inner_padding_factor <= 1.0)')
109 |
110 | if ((inner_padding_factor > 0 or outer_padding[0] > 0 or outer_padding[1] > 0)
111 | and output_size is None):
112 | output_size = tmp_crop_size * \
113 | (1 + inner_padding_factor * 2).astype(np.int32)
114 | output_size += np.array(outer_padding)
115 | # print(' deduced from paddings, output_size = ', output_size)
116 |
117 | if not (outer_padding[0] < output_size[0]
118 | and outer_padding[1] < output_size[1]):
119 | raise FaceWarpException('Not (outer_padding[0] < output_size[0]'
120 | 'and outer_padding[1] < output_size[1])')
121 |
122 | # 1) pad the inner region according inner_padding_factor
123 | # print('---> STEP1: pad the inner region according inner_padding_factor')
124 | if inner_padding_factor > 0:
125 | size_diff = tmp_crop_size * inner_padding_factor * 2
126 | tmp_5pts += size_diff / 2
127 | tmp_crop_size += np.round(size_diff).astype(np.int32)
128 |
129 | # print(' crop_size = ', tmp_crop_size)
130 | # print(' reference_5pts = ', tmp_5pts)
131 |
132 | # 2) resize the padded inner region
133 | # print('---> STEP2: resize the padded inner region')
134 | size_bf_outer_pad = np.array(output_size) - np.array(outer_padding) * 2
135 | # print(' crop_size = ', tmp_crop_size)
136 | # print(' size_bf_outer_pad = ', size_bf_outer_pad)
137 |
138 | if size_bf_outer_pad[0] * tmp_crop_size[1] != size_bf_outer_pad[1] * tmp_crop_size[0]:
139 | raise FaceWarpException('Must have (output_size - outer_padding)'
140 | '= some_scale * (crop_size * (1.0 + inner_padding_factor)')
141 |
142 | scale_factor = size_bf_outer_pad[0].astype(np.float32) / tmp_crop_size[0]
143 | # print(' resize scale_factor = ', scale_factor)
144 | tmp_5pts = tmp_5pts * scale_factor
145 | # size_diff = tmp_crop_size * (scale_factor - min(scale_factor))
146 | # tmp_5pts = tmp_5pts + size_diff / 2
147 | tmp_crop_size = size_bf_outer_pad
148 | # print(' crop_size = ', tmp_crop_size)
149 | # print(' reference_5pts = ', tmp_5pts)
150 |
151 | # 3) add outer_padding to make output_size
152 | reference_5point = tmp_5pts + np.array(outer_padding)
153 | tmp_crop_size = output_size
154 | # print('---> STEP3: add outer_padding to make output_size')
155 | # print(' crop_size = ', tmp_crop_size)
156 | # print(' reference_5pts = ', tmp_5pts)
157 |
158 | # print('===> end get_reference_facial_points\n')
159 |
160 | return reference_5point
161 |
162 |
163 | def get_affine_transform_matrix(src_pts, dst_pts):
164 | """
165 | Function:
166 | ----------
167 | get affine transform matrix 'tfm' from src_pts to dst_pts
168 | Parameters:
169 | ----------
170 | @src_pts: Kx2 np.array
171 | source points matrix, each row is a pair of coordinates (x, y)
172 | @dst_pts: Kx2 np.array
173 | destination points matrix, each row is a pair of coordinates (x, y)
174 | Returns:
175 | ----------
176 | @tfm: 2x3 np.array
177 | transform matrix from src_pts to dst_pts
178 | """
179 |
180 | tfm = np.float32([[1, 0, 0], [0, 1, 0]])
181 | n_pts = src_pts.shape[0]
182 | ones = np.ones((n_pts, 1), src_pts.dtype)
183 | src_pts_ = np.hstack([src_pts, ones])
184 | dst_pts_ = np.hstack([dst_pts, ones])
185 |
186 | # #print(('src_pts_:\n' + str(src_pts_))
187 | # #print(('dst_pts_:\n' + str(dst_pts_))
188 |
189 | A, res, rank, s = np.linalg.lstsq(src_pts_, dst_pts_)
190 |
191 | # #print(('np.linalg.lstsq return A: \n' + str(A))
192 | # #print(('np.linalg.lstsq return res: \n' + str(res))
193 | # #print(('np.linalg.lstsq return rank: \n' + str(rank))
194 | # #print(('np.linalg.lstsq return s: \n' + str(s))
195 |
196 | if rank == 3:
197 | tfm = np.float32([
198 | [A[0, 0], A[1, 0], A[2, 0]],
199 | [A[0, 1], A[1, 1], A[2, 1]]
200 | ])
201 | elif rank == 2:
202 | tfm = np.float32([
203 | [A[0, 0], A[1, 0], 0],
204 | [A[0, 1], A[1, 1], 0]
205 | ])
206 |
207 | return tfm
208 |
209 |
210 | def warp_and_crop_face(src_img,
211 | facial_pts,
212 | reference_pts=None,
213 | crop_size=(96, 112),
214 | align_type='smilarity'):
215 | """
216 | Function:
217 | ----------
218 | apply affine transform 'trans' to uv
219 | Parameters:
220 | ----------
221 | @src_img: 3x3 np.array
222 | input image
223 | @facial_pts: could be
224 | 1)a list of K coordinates (x,y)
225 | or
226 | 2) Kx2 or 2xK np.array
227 | each row or col is a pair of coordinates (x, y)
228 | @reference_pts: could be
229 | 1) a list of K coordinates (x,y)
230 | or
231 | 2) Kx2 or 2xK np.array
232 | each row or col is a pair of coordinates (x, y)
233 | or
234 | 3) None
235 | if None, use default reference facial points
236 | @crop_size: (w, h)
237 | output face image size
238 | @align_type: transform type, could be one of
239 | 1) 'similarity': use similarity transform
240 | 2) 'cv2_affine': use the first 3 points to do affine transform,
241 | by calling cv2.getAffineTransform()
242 | 3) 'affine': use all points to do affine transform
243 | Returns:
244 | ----------
245 | @face_img: output face image with size (w, h) = @crop_size
246 | """
247 |
248 | if reference_pts is None:
249 | if crop_size[0] == 96 and crop_size[1] == 112:
250 | reference_pts = REFERENCE_FACIAL_POINTS
251 | else:
252 | default_square = False
253 | inner_padding_factor = 0
254 | outer_padding = (0, 0)
255 | output_size = crop_size
256 |
257 | reference_pts = get_reference_facial_points(output_size,
258 | inner_padding_factor,
259 | outer_padding,
260 | default_square)
261 |
262 | ref_pts = np.float32(reference_pts)
263 | ref_pts_shp = ref_pts.shape
264 | if max(ref_pts_shp) < 3 or min(ref_pts_shp) != 2:
265 | raise FaceWarpException(
266 | 'reference_pts.shape must be (K,2) or (2,K) and K>2')
267 |
268 | if ref_pts_shp[0] == 2:
269 | ref_pts = ref_pts.T
270 |
271 | src_pts = np.float32(facial_pts)
272 | src_pts_shp = src_pts.shape
273 | if max(src_pts_shp) < 3 or min(src_pts_shp) != 2:
274 | raise FaceWarpException(
275 | 'facial_pts.shape must be (K,2) or (2,K) and K>2')
276 |
277 | if src_pts_shp[0] == 2:
278 | src_pts = src_pts.T
279 |
280 | # #print('--->src_pts:\n', src_pts
281 | # #print('--->ref_pts\n', ref_pts
282 |
283 | if src_pts.shape != ref_pts.shape:
284 | raise FaceWarpException(
285 | 'facial_pts and reference_pts must have the same shape')
286 |
287 | if align_type is 'cv2_affine':
288 | tfm = cv2.getAffineTransform(src_pts[0:3], ref_pts[0:3])
289 | # #print(('cv2.getAffineTransform() returns tfm=\n' + str(tfm))
290 | elif align_type is 'affine':
291 | tfm = get_affine_transform_matrix(src_pts, ref_pts)
292 | # #print(('get_affine_transform_matrix() returns tfm=\n' + str(tfm))
293 | else:
294 | tfm = get_similarity_transform_for_cv2(src_pts, ref_pts)
295 | # #print(('get_similarity_transform_for_cv2() returns tfm=\n' + str(tfm))
296 |
297 | # #print('--->Transform matrix: '
298 | # #print(('type(tfm):' + str(type(tfm)))
299 | # #print(('tfm.dtype:' + str(tfm.dtype))
300 | # #print( tfm
301 |
302 | face_img = cv2.warpAffine(src_img, tfm, (crop_size[0], crop_size[1]))
303 |
304 | return face_img, tfm
305 |
--------------------------------------------------------------------------------
/models/mtcnn/mtcnn_pytorch/src/box_utils.py:
--------------------------------------------------------------------------------
1 | import numpy as np
2 | from PIL import Image
3 |
4 |
5 | def nms(boxes, overlap_threshold=0.5, mode='union'):
6 | """Non-maximum suppression.
7 |
8 | Arguments:
9 | boxes: a float numpy array of shape [n, 5],
10 | where each row is (xmin, ymin, xmax, ymax, score).
11 | overlap_threshold: a float number.
12 | mode: 'union' or 'min'.
13 |
14 | Returns:
15 | list with indices of the selected boxes
16 | """
17 |
18 | # if there are no boxes, return the empty list
19 | if len(boxes) == 0:
20 | return []
21 |
22 | # list of picked indices
23 | pick = []
24 |
25 | # grab the coordinates of the bounding boxes
26 | x1, y1, x2, y2, score = [boxes[:, i] for i in range(5)]
27 |
28 | area = (x2 - x1 + 1.0) * (y2 - y1 + 1.0)
29 | ids = np.argsort(score) # in increasing order
30 |
31 | while len(ids) > 0:
32 |
33 | # grab index of the largest value
34 | last = len(ids) - 1
35 | i = ids[last]
36 | pick.append(i)
37 |
38 | # compute intersections
39 | # of the box with the largest score
40 | # with the rest of boxes
41 |
42 | # left top corner of intersection boxes
43 | ix1 = np.maximum(x1[i], x1[ids[:last]])
44 | iy1 = np.maximum(y1[i], y1[ids[:last]])
45 |
46 | # right bottom corner of intersection boxes
47 | ix2 = np.minimum(x2[i], x2[ids[:last]])
48 | iy2 = np.minimum(y2[i], y2[ids[:last]])
49 |
50 | # width and height of intersection boxes
51 | w = np.maximum(0.0, ix2 - ix1 + 1.0)
52 | h = np.maximum(0.0, iy2 - iy1 + 1.0)
53 |
54 | # intersections' areas
55 | inter = w * h
56 | if mode == 'min':
57 | overlap = inter / np.minimum(area[i], area[ids[:last]])
58 | elif mode == 'union':
59 | # intersection over union (IoU)
60 | overlap = inter / (area[i] + area[ids[:last]] - inter)
61 |
62 | # delete all boxes where overlap is too big
63 | ids = np.delete(
64 | ids,
65 | np.concatenate([[last], np.where(overlap > overlap_threshold)[0]])
66 | )
67 |
68 | return pick
69 |
70 |
71 | def convert_to_square(bboxes):
72 | """Convert bounding boxes to a square form.
73 |
74 | Arguments:
75 | bboxes: a float numpy array of shape [n, 5].
76 |
77 | Returns:
78 | a float numpy array of shape [n, 5],
79 | squared bounding boxes.
80 | """
81 |
82 | square_bboxes = np.zeros_like(bboxes)
83 | x1, y1, x2, y2 = [bboxes[:, i] for i in range(4)]
84 | h = y2 - y1 + 1.0
85 | w = x2 - x1 + 1.0
86 | max_side = np.maximum(h, w)
87 | square_bboxes[:, 0] = x1 + w * 0.5 - max_side * 0.5
88 | square_bboxes[:, 1] = y1 + h * 0.5 - max_side * 0.5
89 | square_bboxes[:, 2] = square_bboxes[:, 0] + max_side - 1.0
90 | square_bboxes[:, 3] = square_bboxes[:, 1] + max_side - 1.0
91 | return square_bboxes
92 |
93 |
94 | def calibrate_box(bboxes, offsets):
95 | """Transform bounding boxes to be more like true bounding boxes.
96 | 'offsets' is one of the outputs of the nets.
97 |
98 | Arguments:
99 | bboxes: a float numpy array of shape [n, 5].
100 | offsets: a float numpy array of shape [n, 4].
101 |
102 | Returns:
103 | a float numpy array of shape [n, 5].
104 | """
105 | x1, y1, x2, y2 = [bboxes[:, i] for i in range(4)]
106 | w = x2 - x1 + 1.0
107 | h = y2 - y1 + 1.0
108 | w = np.expand_dims(w, 1)
109 | h = np.expand_dims(h, 1)
110 |
111 | # this is what happening here:
112 | # tx1, ty1, tx2, ty2 = [offsets[:, i] for i in range(4)]
113 | # x1_true = x1 + tx1*w
114 | # y1_true = y1 + ty1*h
115 | # x2_true = x2 + tx2*w
116 | # y2_true = y2 + ty2*h
117 | # below is just more compact form of this
118 |
119 | # are offsets always such that
120 | # x1 < x2 and y1 < y2 ?
121 |
122 | translation = np.hstack([w, h, w, h]) * offsets
123 | bboxes[:, 0:4] = bboxes[:, 0:4] + translation
124 | return bboxes
125 |
126 |
127 | def get_image_boxes(bounding_boxes, img, size=24):
128 | """Cut out boxes from the image.
129 |
130 | Arguments:
131 | bounding_boxes: a float numpy array of shape [n, 5].
132 | img: an instance of PIL.Image.
133 | size: an integer, size of cutouts.
134 |
135 | Returns:
136 | a float numpy array of shape [n, 3, size, size].
137 | """
138 |
139 | num_boxes = len(bounding_boxes)
140 | width, height = img.size
141 |
142 | [dy, edy, dx, edx, y, ey, x, ex, w, h] = correct_bboxes(bounding_boxes, width, height)
143 | img_boxes = np.zeros((num_boxes, 3, size, size), 'float32')
144 |
145 | for i in range(num_boxes):
146 | img_box = np.zeros((h[i], w[i], 3), 'uint8')
147 |
148 | img_array = np.asarray(img, 'uint8')
149 | img_box[dy[i]:(edy[i] + 1), dx[i]:(edx[i] + 1), :] = \
150 | img_array[y[i]:(ey[i] + 1), x[i]:(ex[i] + 1), :]
151 |
152 | # resize
153 | img_box = Image.fromarray(img_box)
154 | img_box = img_box.resize((size, size), Image.BILINEAR)
155 | img_box = np.asarray(img_box, 'float32')
156 |
157 | img_boxes[i, :, :, :] = _preprocess(img_box)
158 |
159 | return img_boxes
160 |
161 |
162 | def correct_bboxes(bboxes, width, height):
163 | """Crop boxes that are too big and get coordinates
164 | with respect to cutouts.
165 |
166 | Arguments:
167 | bboxes: a float numpy array of shape [n, 5],
168 | where each row is (xmin, ymin, xmax, ymax, score).
169 | width: a float number.
170 | height: a float number.
171 |
172 | Returns:
173 | dy, dx, edy, edx: a int numpy arrays of shape [n],
174 | coordinates of the boxes with respect to the cutouts.
175 | y, x, ey, ex: a int numpy arrays of shape [n],
176 | corrected ymin, xmin, ymax, xmax.
177 | h, w: a int numpy arrays of shape [n],
178 | just heights and widths of boxes.
179 |
180 | in the following order:
181 | [dy, edy, dx, edx, y, ey, x, ex, w, h].
182 | """
183 |
184 | x1, y1, x2, y2 = [bboxes[:, i] for i in range(4)]
185 | w, h = x2 - x1 + 1.0, y2 - y1 + 1.0
186 | num_boxes = bboxes.shape[0]
187 |
188 | # 'e' stands for end
189 | # (x, y) -> (ex, ey)
190 | x, y, ex, ey = x1, y1, x2, y2
191 |
192 | # we need to cut out a box from the image.
193 | # (x, y, ex, ey) are corrected coordinates of the box
194 | # in the image.
195 | # (dx, dy, edx, edy) are coordinates of the box in the cutout
196 | # from the image.
197 | dx, dy = np.zeros((num_boxes,)), np.zeros((num_boxes,))
198 | edx, edy = w.copy() - 1.0, h.copy() - 1.0
199 |
200 | # if box's bottom right corner is too far right
201 | ind = np.where(ex > width - 1.0)[0]
202 | edx[ind] = w[ind] + width - 2.0 - ex[ind]
203 | ex[ind] = width - 1.0
204 |
205 | # if box's bottom right corner is too low
206 | ind = np.where(ey > height - 1.0)[0]
207 | edy[ind] = h[ind] + height - 2.0 - ey[ind]
208 | ey[ind] = height - 1.0
209 |
210 | # if box's top left corner is too far left
211 | ind = np.where(x < 0.0)[0]
212 | dx[ind] = 0.0 - x[ind]
213 | x[ind] = 0.0
214 |
215 | # if box's top left corner is too high
216 | ind = np.where(y < 0.0)[0]
217 | dy[ind] = 0.0 - y[ind]
218 | y[ind] = 0.0
219 |
220 | return_list = [dy, edy, dx, edx, y, ey, x, ex, w, h]
221 | return_list = [i.astype('int32') for i in return_list]
222 |
223 | return return_list
224 |
225 |
226 | def _preprocess(img):
227 | """Preprocessing step before feeding the network.
228 |
229 | Arguments:
230 | img: a float numpy array of shape [h, w, c].
231 |
232 | Returns:
233 | a float numpy array of shape [1, c, h, w].
234 | """
235 | img = img.transpose((2, 0, 1))
236 | img = np.expand_dims(img, 0)
237 | img = (img - 127.5) * 0.0078125
238 | return img
239 |
--------------------------------------------------------------------------------
/models/mtcnn/mtcnn_pytorch/src/detector.py:
--------------------------------------------------------------------------------
1 | import numpy as np
2 | import torch
3 | from .get_nets import PNet, RNet, ONet
4 | from .box_utils import nms, calibrate_box, get_image_boxes, convert_to_square
5 | from .first_stage import run_first_stage
6 |
7 |
8 | def detect_faces(image, min_face_size=20.0,
9 | thresholds=[0.6, 0.7, 0.8],
10 | nms_thresholds=[0.7, 0.7, 0.7]):
11 | """
12 | Arguments:
13 | image: an instance of PIL.Image.
14 | min_face_size: a float number.
15 | thresholds: a list of length 3.
16 | nms_thresholds: a list of length 3.
17 |
18 | Returns:
19 | two float numpy arrays of shapes [n_boxes, 4] and [n_boxes, 10],
20 | bounding boxes and facial landmarks.
21 | """
22 |
23 | # LOAD MODELS
24 | pnet = PNet()
25 | rnet = RNet()
26 | onet = ONet()
27 | onet.eval()
28 |
29 | # BUILD AN IMAGE PYRAMID
30 | width, height = image.size
31 | min_length = min(height, width)
32 |
33 | min_detection_size = 12
34 | factor = 0.707 # sqrt(0.5)
35 |
36 | # scales for scaling the image
37 | scales = []
38 |
39 | # scales the image so that
40 | # minimum size that we can detect equals to
41 | # minimum face size that we want to detect
42 | m = min_detection_size / min_face_size
43 | min_length *= m
44 |
45 | factor_count = 0
46 | while min_length > min_detection_size:
47 | scales.append(m * factor ** factor_count)
48 | min_length *= factor
49 | factor_count += 1
50 |
51 | # STAGE 1
52 |
53 | # it will be returned
54 | bounding_boxes = []
55 |
56 | with torch.no_grad():
57 | # run P-Net on different scales
58 | for s in scales:
59 | boxes = run_first_stage(image, pnet, scale=s, threshold=thresholds[0])
60 | bounding_boxes.append(boxes)
61 |
62 | # collect boxes (and offsets, and scores) from different scales
63 | bounding_boxes = [i for i in bounding_boxes if i is not None]
64 | bounding_boxes = np.vstack(bounding_boxes)
65 |
66 | keep = nms(bounding_boxes[:, 0:5], nms_thresholds[0])
67 | bounding_boxes = bounding_boxes[keep]
68 |
69 | # use offsets predicted by pnet to transform bounding boxes
70 | bounding_boxes = calibrate_box(bounding_boxes[:, 0:5], bounding_boxes[:, 5:])
71 | # shape [n_boxes, 5]
72 |
73 | bounding_boxes = convert_to_square(bounding_boxes)
74 | bounding_boxes[:, 0:4] = np.round(bounding_boxes[:, 0:4])
75 |
76 | # STAGE 2
77 |
78 | img_boxes = get_image_boxes(bounding_boxes, image, size=24)
79 | img_boxes = torch.FloatTensor(img_boxes)
80 |
81 | output = rnet(img_boxes)
82 | offsets = output[0].data.numpy() # shape [n_boxes, 4]
83 | probs = output[1].data.numpy() # shape [n_boxes, 2]
84 |
85 | keep = np.where(probs[:, 1] > thresholds[1])[0]
86 | bounding_boxes = bounding_boxes[keep]
87 | bounding_boxes[:, 4] = probs[keep, 1].reshape((-1,))
88 | offsets = offsets[keep]
89 |
90 | keep = nms(bounding_boxes, nms_thresholds[1])
91 | bounding_boxes = bounding_boxes[keep]
92 | bounding_boxes = calibrate_box(bounding_boxes, offsets[keep])
93 | bounding_boxes = convert_to_square(bounding_boxes)
94 | bounding_boxes[:, 0:4] = np.round(bounding_boxes[:, 0:4])
95 |
96 | # STAGE 3
97 |
98 | img_boxes = get_image_boxes(bounding_boxes, image, size=48)
99 | if len(img_boxes) == 0:
100 | return [], []
101 | img_boxes = torch.FloatTensor(img_boxes)
102 | output = onet(img_boxes)
103 | landmarks = output[0].data.numpy() # shape [n_boxes, 10]
104 | offsets = output[1].data.numpy() # shape [n_boxes, 4]
105 | probs = output[2].data.numpy() # shape [n_boxes, 2]
106 |
107 | keep = np.where(probs[:, 1] > thresholds[2])[0]
108 | bounding_boxes = bounding_boxes[keep]
109 | bounding_boxes[:, 4] = probs[keep, 1].reshape((-1,))
110 | offsets = offsets[keep]
111 | landmarks = landmarks[keep]
112 |
113 | # compute landmark points
114 | width = bounding_boxes[:, 2] - bounding_boxes[:, 0] + 1.0
115 | height = bounding_boxes[:, 3] - bounding_boxes[:, 1] + 1.0
116 | xmin, ymin = bounding_boxes[:, 0], bounding_boxes[:, 1]
117 | landmarks[:, 0:5] = np.expand_dims(xmin, 1) + np.expand_dims(width, 1) * landmarks[:, 0:5]
118 | landmarks[:, 5:10] = np.expand_dims(ymin, 1) + np.expand_dims(height, 1) * landmarks[:, 5:10]
119 |
120 | bounding_boxes = calibrate_box(bounding_boxes, offsets)
121 | keep = nms(bounding_boxes, nms_thresholds[2], mode='min')
122 | bounding_boxes = bounding_boxes[keep]
123 | landmarks = landmarks[keep]
124 |
125 | return bounding_boxes, landmarks
126 |
--------------------------------------------------------------------------------
/models/mtcnn/mtcnn_pytorch/src/first_stage.py:
--------------------------------------------------------------------------------
1 | import torch
2 | import math
3 | from PIL import Image
4 | import numpy as np
5 | from .box_utils import nms, _preprocess
6 |
7 | # device = torch.device("cuda:0" if torch.cuda.is_available() else "cpu")
8 | device = 'cuda:0'
9 |
10 |
11 | def run_first_stage(image, net, scale, threshold):
12 | """Run P-Net, generate bounding boxes, and do NMS.
13 |
14 | Arguments:
15 | image: an instance of PIL.Image.
16 | net: an instance of pytorch's nn.Module, P-Net.
17 | scale: a float number,
18 | scale width and height of the image by this number.
19 | threshold: a float number,
20 | threshold on the probability of a face when generating
21 | bounding boxes from predictions of the net.
22 |
23 | Returns:
24 | a float numpy array of shape [n_boxes, 9],
25 | bounding boxes with scores and offsets (4 + 1 + 4).
26 | """
27 |
28 | # scale the image and convert it to a float array
29 | width, height = image.size
30 | sw, sh = math.ceil(width * scale), math.ceil(height * scale)
31 | img = image.resize((sw, sh), Image.BILINEAR)
32 | img = np.asarray(img, 'float32')
33 |
34 | img = torch.FloatTensor(_preprocess(img)).to(device)
35 | with torch.no_grad():
36 | output = net(img)
37 | probs = output[1].cpu().data.numpy()[0, 1, :, :]
38 | offsets = output[0].cpu().data.numpy()
39 | # probs: probability of a face at each sliding window
40 | # offsets: transformations to true bounding boxes
41 |
42 | boxes = _generate_bboxes(probs, offsets, scale, threshold)
43 | if len(boxes) == 0:
44 | return None
45 |
46 | keep = nms(boxes[:, 0:5], overlap_threshold=0.5)
47 | return boxes[keep]
48 |
49 |
50 | def _generate_bboxes(probs, offsets, scale, threshold):
51 | """Generate bounding boxes at places
52 | where there is probably a face.
53 |
54 | Arguments:
55 | probs: a float numpy array of shape [n, m].
56 | offsets: a float numpy array of shape [1, 4, n, m].
57 | scale: a float number,
58 | width and height of the image were scaled by this number.
59 | threshold: a float number.
60 |
61 | Returns:
62 | a float numpy array of shape [n_boxes, 9]
63 | """
64 |
65 | # applying P-Net is equivalent, in some sense, to
66 | # moving 12x12 window with stride 2
67 | stride = 2
68 | cell_size = 12
69 |
70 | # indices of boxes where there is probably a face
71 | inds = np.where(probs > threshold)
72 |
73 | if inds[0].size == 0:
74 | return np.array([])
75 |
76 | # transformations of bounding boxes
77 | tx1, ty1, tx2, ty2 = [offsets[0, i, inds[0], inds[1]] for i in range(4)]
78 | # they are defined as:
79 | # w = x2 - x1 + 1
80 | # h = y2 - y1 + 1
81 | # x1_true = x1 + tx1*w
82 | # x2_true = x2 + tx2*w
83 | # y1_true = y1 + ty1*h
84 | # y2_true = y2 + ty2*h
85 |
86 | offsets = np.array([tx1, ty1, tx2, ty2])
87 | score = probs[inds[0], inds[1]]
88 |
89 | # P-Net is applied to scaled images
90 | # so we need to rescale bounding boxes back
91 | bounding_boxes = np.vstack([
92 | np.round((stride * inds[1] + 1.0) / scale),
93 | np.round((stride * inds[0] + 1.0) / scale),
94 | np.round((stride * inds[1] + 1.0 + cell_size) / scale),
95 | np.round((stride * inds[0] + 1.0 + cell_size) / scale),
96 | score, offsets
97 | ])
98 | # why one is added?
99 |
100 | return bounding_boxes.T
101 |
--------------------------------------------------------------------------------
/models/mtcnn/mtcnn_pytorch/src/get_nets.py:
--------------------------------------------------------------------------------
1 | import torch
2 | import torch.nn as nn
3 | import torch.nn.functional as F
4 | from collections import OrderedDict
5 | import numpy as np
6 |
7 | from configs.paths_config import model_paths
8 | PNET_PATH = model_paths["mtcnn_pnet"]
9 | ONET_PATH = model_paths["mtcnn_onet"]
10 | RNET_PATH = model_paths["mtcnn_rnet"]
11 |
12 |
13 | class Flatten(nn.Module):
14 |
15 | def __init__(self):
16 | super(Flatten, self).__init__()
17 |
18 | def forward(self, x):
19 | """
20 | Arguments:
21 | x: a float tensor with shape [batch_size, c, h, w].
22 | Returns:
23 | a float tensor with shape [batch_size, c*h*w].
24 | """
25 |
26 | # without this pretrained model isn't working
27 | x = x.transpose(3, 2).contiguous()
28 |
29 | return x.view(x.size(0), -1)
30 |
31 |
32 | class PNet(nn.Module):
33 |
34 | def __init__(self):
35 | super().__init__()
36 |
37 | # suppose we have input with size HxW, then
38 | # after first layer: H - 2,
39 | # after pool: ceil((H - 2)/2),
40 | # after second conv: ceil((H - 2)/2) - 2,
41 | # after last conv: ceil((H - 2)/2) - 4,
42 | # and the same for W
43 |
44 | self.features = nn.Sequential(OrderedDict([
45 | ('conv1', nn.Conv2d(3, 10, 3, 1)),
46 | ('prelu1', nn.PReLU(10)),
47 | ('pool1', nn.MaxPool2d(2, 2, ceil_mode=True)),
48 |
49 | ('conv2', nn.Conv2d(10, 16, 3, 1)),
50 | ('prelu2', nn.PReLU(16)),
51 |
52 | ('conv3', nn.Conv2d(16, 32, 3, 1)),
53 | ('prelu3', nn.PReLU(32))
54 | ]))
55 |
56 | self.conv4_1 = nn.Conv2d(32, 2, 1, 1)
57 | self.conv4_2 = nn.Conv2d(32, 4, 1, 1)
58 |
59 | weights = np.load(PNET_PATH, allow_pickle=True)[()]
60 | for n, p in self.named_parameters():
61 | p.data = torch.FloatTensor(weights[n])
62 |
63 | def forward(self, x):
64 | """
65 | Arguments:
66 | x: a float tensor with shape [batch_size, 3, h, w].
67 | Returns:
68 | b: a float tensor with shape [batch_size, 4, h', w'].
69 | a: a float tensor with shape [batch_size, 2, h', w'].
70 | """
71 | x = self.features(x)
72 | a = self.conv4_1(x)
73 | b = self.conv4_2(x)
74 | a = F.softmax(a, dim=-1)
75 | return b, a
76 |
77 |
78 | class RNet(nn.Module):
79 |
80 | def __init__(self):
81 | super().__init__()
82 |
83 | self.features = nn.Sequential(OrderedDict([
84 | ('conv1', nn.Conv2d(3, 28, 3, 1)),
85 | ('prelu1', nn.PReLU(28)),
86 | ('pool1', nn.MaxPool2d(3, 2, ceil_mode=True)),
87 |
88 | ('conv2', nn.Conv2d(28, 48, 3, 1)),
89 | ('prelu2', nn.PReLU(48)),
90 | ('pool2', nn.MaxPool2d(3, 2, ceil_mode=True)),
91 |
92 | ('conv3', nn.Conv2d(48, 64, 2, 1)),
93 | ('prelu3', nn.PReLU(64)),
94 |
95 | ('flatten', Flatten()),
96 | ('conv4', nn.Linear(576, 128)),
97 | ('prelu4', nn.PReLU(128))
98 | ]))
99 |
100 | self.conv5_1 = nn.Linear(128, 2)
101 | self.conv5_2 = nn.Linear(128, 4)
102 |
103 | weights = np.load(RNET_PATH, allow_pickle=True)[()]
104 | for n, p in self.named_parameters():
105 | p.data = torch.FloatTensor(weights[n])
106 |
107 | def forward(self, x):
108 | """
109 | Arguments:
110 | x: a float tensor with shape [batch_size, 3, h, w].
111 | Returns:
112 | b: a float tensor with shape [batch_size, 4].
113 | a: a float tensor with shape [batch_size, 2].
114 | """
115 | x = self.features(x)
116 | a = self.conv5_1(x)
117 | b = self.conv5_2(x)
118 | a = F.softmax(a, dim=-1)
119 | return b, a
120 |
121 |
122 | class ONet(nn.Module):
123 |
124 | def __init__(self):
125 | super().__init__()
126 |
127 | self.features = nn.Sequential(OrderedDict([
128 | ('conv1', nn.Conv2d(3, 32, 3, 1)),
129 | ('prelu1', nn.PReLU(32)),
130 | ('pool1', nn.MaxPool2d(3, 2, ceil_mode=True)),
131 |
132 | ('conv2', nn.Conv2d(32, 64, 3, 1)),
133 | ('prelu2', nn.PReLU(64)),
134 | ('pool2', nn.MaxPool2d(3, 2, ceil_mode=True)),
135 |
136 | ('conv3', nn.Conv2d(64, 64, 3, 1)),
137 | ('prelu3', nn.PReLU(64)),
138 | ('pool3', nn.MaxPool2d(2, 2, ceil_mode=True)),
139 |
140 | ('conv4', nn.Conv2d(64, 128, 2, 1)),
141 | ('prelu4', nn.PReLU(128)),
142 |
143 | ('flatten', Flatten()),
144 | ('conv5', nn.Linear(1152, 256)),
145 | ('drop5', nn.Dropout(0.25)),
146 | ('prelu5', nn.PReLU(256)),
147 | ]))
148 |
149 | self.conv6_1 = nn.Linear(256, 2)
150 | self.conv6_2 = nn.Linear(256, 4)
151 | self.conv6_3 = nn.Linear(256, 10)
152 |
153 | weights = np.load(ONET_PATH, allow_pickle=True)[()]
154 | for n, p in self.named_parameters():
155 | p.data = torch.FloatTensor(weights[n])
156 |
157 | def forward(self, x):
158 | """
159 | Arguments:
160 | x: a float tensor with shape [batch_size, 3, h, w].
161 | Returns:
162 | c: a float tensor with shape [batch_size, 10].
163 | b: a float tensor with shape [batch_size, 4].
164 | a: a float tensor with shape [batch_size, 2].
165 | """
166 | x = self.features(x)
167 | a = self.conv6_1(x)
168 | b = self.conv6_2(x)
169 | c = self.conv6_3(x)
170 | a = F.softmax(a, dim=-1)
171 | return c, b, a
172 |
--------------------------------------------------------------------------------
/models/mtcnn/mtcnn_pytorch/src/matlab_cp2tform.py:
--------------------------------------------------------------------------------
1 | # -*- coding: utf-8 -*-
2 | """
3 | Created on Tue Jul 11 06:54:28 2017
4 |
5 | @author: zhaoyafei
6 | """
7 |
8 | import numpy as np
9 | from numpy.linalg import inv, norm, lstsq
10 | from numpy.linalg import matrix_rank as rank
11 |
12 |
13 | class MatlabCp2tormException(Exception):
14 | def __str__(self):
15 | return 'In File {}:{}'.format(
16 | __file__, super.__str__(self))
17 |
18 |
19 | def tformfwd(trans, uv):
20 | """
21 | Function:
22 | ----------
23 | apply affine transform 'trans' to uv
24 |
25 | Parameters:
26 | ----------
27 | @trans: 3x3 np.array
28 | transform matrix
29 | @uv: Kx2 np.array
30 | each row is a pair of coordinates (x, y)
31 |
32 | Returns:
33 | ----------
34 | @xy: Kx2 np.array
35 | each row is a pair of transformed coordinates (x, y)
36 | """
37 | uv = np.hstack((
38 | uv, np.ones((uv.shape[0], 1))
39 | ))
40 | xy = np.dot(uv, trans)
41 | xy = xy[:, 0:-1]
42 | return xy
43 |
44 |
45 | def tforminv(trans, uv):
46 | """
47 | Function:
48 | ----------
49 | apply the inverse of affine transform 'trans' to uv
50 |
51 | Parameters:
52 | ----------
53 | @trans: 3x3 np.array
54 | transform matrix
55 | @uv: Kx2 np.array
56 | each row is a pair of coordinates (x, y)
57 |
58 | Returns:
59 | ----------
60 | @xy: Kx2 np.array
61 | each row is a pair of inverse-transformed coordinates (x, y)
62 | """
63 | Tinv = inv(trans)
64 | xy = tformfwd(Tinv, uv)
65 | return xy
66 |
67 |
68 | def findNonreflectiveSimilarity(uv, xy, options=None):
69 | options = {'K': 2}
70 |
71 | K = options['K']
72 | M = xy.shape[0]
73 | x = xy[:, 0].reshape((-1, 1)) # use reshape to keep a column vector
74 | y = xy[:, 1].reshape((-1, 1)) # use reshape to keep a column vector
75 | # print('--->x, y:\n', x, y
76 |
77 | tmp1 = np.hstack((x, y, np.ones((M, 1)), np.zeros((M, 1))))
78 | tmp2 = np.hstack((y, -x, np.zeros((M, 1)), np.ones((M, 1))))
79 | X = np.vstack((tmp1, tmp2))
80 | # print('--->X.shape: ', X.shape
81 | # print('X:\n', X
82 |
83 | u = uv[:, 0].reshape((-1, 1)) # use reshape to keep a column vector
84 | v = uv[:, 1].reshape((-1, 1)) # use reshape to keep a column vector
85 | U = np.vstack((u, v))
86 | # print('--->U.shape: ', U.shape
87 | # print('U:\n', U
88 |
89 | # We know that X * r = U
90 | if rank(X) >= 2 * K:
91 | r, _, _, _ = lstsq(X, U, rcond=None) # Make sure this is what I want
92 | r = np.squeeze(r)
93 | else:
94 | raise Exception('cp2tform:twoUniquePointsReq')
95 |
96 | # print('--->r:\n', r
97 |
98 | sc = r[0]
99 | ss = r[1]
100 | tx = r[2]
101 | ty = r[3]
102 |
103 | Tinv = np.array([
104 | [sc, -ss, 0],
105 | [ss, sc, 0],
106 | [tx, ty, 1]
107 | ])
108 |
109 | # print('--->Tinv:\n', Tinv
110 |
111 | T = inv(Tinv)
112 | # print('--->T:\n', T
113 |
114 | T[:, 2] = np.array([0, 0, 1])
115 |
116 | return T, Tinv
117 |
118 |
119 | def findSimilarity(uv, xy, options=None):
120 | options = {'K': 2}
121 |
122 | # uv = np.array(uv)
123 | # xy = np.array(xy)
124 |
125 | # Solve for trans1
126 | trans1, trans1_inv = findNonreflectiveSimilarity(uv, xy, options)
127 |
128 | # Solve for trans2
129 |
130 | # manually reflect the xy data across the Y-axis
131 | xyR = xy
132 | xyR[:, 0] = -1 * xyR[:, 0]
133 |
134 | trans2r, trans2r_inv = findNonreflectiveSimilarity(uv, xyR, options)
135 |
136 | # manually reflect the tform to undo the reflection done on xyR
137 | TreflectY = np.array([
138 | [-1, 0, 0],
139 | [0, 1, 0],
140 | [0, 0, 1]
141 | ])
142 |
143 | trans2 = np.dot(trans2r, TreflectY)
144 |
145 | # Figure out if trans1 or trans2 is better
146 | xy1 = tformfwd(trans1, uv)
147 | norm1 = norm(xy1 - xy)
148 |
149 | xy2 = tformfwd(trans2, uv)
150 | norm2 = norm(xy2 - xy)
151 |
152 | if norm1 <= norm2:
153 | return trans1, trans1_inv
154 | else:
155 | trans2_inv = inv(trans2)
156 | return trans2, trans2_inv
157 |
158 |
159 | def get_similarity_transform(src_pts, dst_pts, reflective=True):
160 | """
161 | Function:
162 | ----------
163 | Find Similarity Transform Matrix 'trans':
164 | u = src_pts[:, 0]
165 | v = src_pts[:, 1]
166 | x = dst_pts[:, 0]
167 | y = dst_pts[:, 1]
168 | [x, y, 1] = [u, v, 1] * trans
169 |
170 | Parameters:
171 | ----------
172 | @src_pts: Kx2 np.array
173 | source points, each row is a pair of coordinates (x, y)
174 | @dst_pts: Kx2 np.array
175 | destination points, each row is a pair of transformed
176 | coordinates (x, y)
177 | @reflective: True or False
178 | if True:
179 | use reflective similarity transform
180 | else:
181 | use non-reflective similarity transform
182 |
183 | Returns:
184 | ----------
185 | @trans: 3x3 np.array
186 | transform matrix from uv to xy
187 | trans_inv: 3x3 np.array
188 | inverse of trans, transform matrix from xy to uv
189 | """
190 |
191 | if reflective:
192 | trans, trans_inv = findSimilarity(src_pts, dst_pts)
193 | else:
194 | trans, trans_inv = findNonreflectiveSimilarity(src_pts, dst_pts)
195 |
196 | return trans, trans_inv
197 |
198 |
199 | def cvt_tform_mat_for_cv2(trans):
200 | """
201 | Function:
202 | ----------
203 | Convert Transform Matrix 'trans' into 'cv2_trans' which could be
204 | directly used by cv2.warpAffine():
205 | u = src_pts[:, 0]
206 | v = src_pts[:, 1]
207 | x = dst_pts[:, 0]
208 | y = dst_pts[:, 1]
209 | [x, y].T = cv_trans * [u, v, 1].T
210 |
211 | Parameters:
212 | ----------
213 | @trans: 3x3 np.array
214 | transform matrix from uv to xy
215 |
216 | Returns:
217 | ----------
218 | @cv2_trans: 2x3 np.array
219 | transform matrix from src_pts to dst_pts, could be directly used
220 | for cv2.warpAffine()
221 | """
222 | cv2_trans = trans[:, 0:2].T
223 |
224 | return cv2_trans
225 |
226 |
227 | def get_similarity_transform_for_cv2(src_pts, dst_pts, reflective=True):
228 | """
229 | Function:
230 | ----------
231 | Find Similarity Transform Matrix 'cv2_trans' which could be
232 | directly used by cv2.warpAffine():
233 | u = src_pts[:, 0]
234 | v = src_pts[:, 1]
235 | x = dst_pts[:, 0]
236 | y = dst_pts[:, 1]
237 | [x, y].T = cv_trans * [u, v, 1].T
238 |
239 | Parameters:
240 | ----------
241 | @src_pts: Kx2 np.array
242 | source points, each row is a pair of coordinates (x, y)
243 | @dst_pts: Kx2 np.array
244 | destination points, each row is a pair of transformed
245 | coordinates (x, y)
246 | reflective: True or False
247 | if True:
248 | use reflective similarity transform
249 | else:
250 | use non-reflective similarity transform
251 |
252 | Returns:
253 | ----------
254 | @cv2_trans: 2x3 np.array
255 | transform matrix from src_pts to dst_pts, could be directly used
256 | for cv2.warpAffine()
257 | """
258 | trans, trans_inv = get_similarity_transform(src_pts, dst_pts, reflective)
259 | cv2_trans = cvt_tform_mat_for_cv2(trans)
260 |
261 | return cv2_trans
262 |
263 |
264 | if __name__ == '__main__':
265 | """
266 | u = [0, 6, -2]
267 | v = [0, 3, 5]
268 | x = [-1, 0, 4]
269 | y = [-1, -10, 4]
270 |
271 | # In Matlab, run:
272 | #
273 | # uv = [u'; v'];
274 | # xy = [x'; y'];
275 | # tform_sim=cp2tform(uv,xy,'similarity');
276 | #
277 | # trans = tform_sim.tdata.T
278 | # ans =
279 | # -0.0764 -1.6190 0
280 | # 1.6190 -0.0764 0
281 | # -3.2156 0.0290 1.0000
282 | # trans_inv = tform_sim.tdata.Tinv
283 | # ans =
284 | #
285 | # -0.0291 0.6163 0
286 | # -0.6163 -0.0291 0
287 | # -0.0756 1.9826 1.0000
288 | # xy_m=tformfwd(tform_sim, u,v)
289 | #
290 | # xy_m =
291 | #
292 | # -3.2156 0.0290
293 | # 1.1833 -9.9143
294 | # 5.0323 2.8853
295 | # uv_m=tforminv(tform_sim, x,y)
296 | #
297 | # uv_m =
298 | #
299 | # 0.5698 1.3953
300 | # 6.0872 2.2733
301 | # -2.6570 4.3314
302 | """
303 | u = [0, 6, -2]
304 | v = [0, 3, 5]
305 | x = [-1, 0, 4]
306 | y = [-1, -10, 4]
307 |
308 | uv = np.array((u, v)).T
309 | xy = np.array((x, y)).T
310 |
311 | print('\n--->uv:')
312 | print(uv)
313 | print('\n--->xy:')
314 | print(xy)
315 |
316 | trans, trans_inv = get_similarity_transform(uv, xy)
317 |
318 | print('\n--->trans matrix:')
319 | print(trans)
320 |
321 | print('\n--->trans_inv matrix:')
322 | print(trans_inv)
323 |
324 | print('\n---> apply transform to uv')
325 | print('\nxy_m = uv_augmented * trans')
326 | uv_aug = np.hstack((
327 | uv, np.ones((uv.shape[0], 1))
328 | ))
329 | xy_m = np.dot(uv_aug, trans)
330 | print(xy_m)
331 |
332 | print('\nxy_m = tformfwd(trans, uv)')
333 | xy_m = tformfwd(trans, uv)
334 | print(xy_m)
335 |
336 | print('\n---> apply inverse transform to xy')
337 | print('\nuv_m = xy_augmented * trans_inv')
338 | xy_aug = np.hstack((
339 | xy, np.ones((xy.shape[0], 1))
340 | ))
341 | uv_m = np.dot(xy_aug, trans_inv)
342 | print(uv_m)
343 |
344 | print('\nuv_m = tformfwd(trans_inv, xy)')
345 | uv_m = tformfwd(trans_inv, xy)
346 | print(uv_m)
347 |
348 | uv_m = tforminv(trans, xy)
349 | print('\nuv_m = tforminv(trans, xy)')
350 | print(uv_m)
351 |
--------------------------------------------------------------------------------
/models/mtcnn/mtcnn_pytorch/src/visualization_utils.py:
--------------------------------------------------------------------------------
1 | from PIL import ImageDraw
2 |
3 |
4 | def show_bboxes(img, bounding_boxes, facial_landmarks=[]):
5 | """Draw bounding boxes and facial landmarks.
6 |
7 | Arguments:
8 | img: an instance of PIL.Image.
9 | bounding_boxes: a float numpy array of shape [n, 5].
10 | facial_landmarks: a float numpy array of shape [n, 10].
11 |
12 | Returns:
13 | an instance of PIL.Image.
14 | """
15 |
16 | img_copy = img.copy()
17 | draw = ImageDraw.Draw(img_copy)
18 |
19 | for b in bounding_boxes:
20 | draw.rectangle([
21 | (b[0], b[1]), (b[2], b[3])
22 | ], outline='white')
23 |
24 | for p in facial_landmarks:
25 | for i in range(5):
26 | draw.ellipse([
27 | (p[i] - 1.0, p[i + 5] - 1.0),
28 | (p[i] + 1.0, p[i + 5] + 1.0)
29 | ], outline='blue')
30 |
31 | return img_copy
32 |
--------------------------------------------------------------------------------
/models/mtcnn/mtcnn_pytorch/src/weights/onet.npy:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/1jsingh/paint2pix/971d1ea06ef6cbcc555ad09a365bf1621ce13f08/models/mtcnn/mtcnn_pytorch/src/weights/onet.npy
--------------------------------------------------------------------------------
/models/mtcnn/mtcnn_pytorch/src/weights/pnet.npy:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/1jsingh/paint2pix/971d1ea06ef6cbcc555ad09a365bf1621ce13f08/models/mtcnn/mtcnn_pytorch/src/weights/pnet.npy
--------------------------------------------------------------------------------
/models/mtcnn/mtcnn_pytorch/src/weights/rnet.npy:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/1jsingh/paint2pix/971d1ea06ef6cbcc555ad09a365bf1621ce13f08/models/mtcnn/mtcnn_pytorch/src/weights/rnet.npy
--------------------------------------------------------------------------------
/models/psp.py:
--------------------------------------------------------------------------------
1 | """
2 | This file defines the core research contribution
3 | """
4 | import math
5 | import torch
6 | from torch import nn
7 |
8 | from models.stylegan2.model import Generator
9 | from configs.paths_config import model_paths
10 | from models.encoders import fpn_encoders, restyle_psp_encoders
11 | from utils.model_utils import RESNET_MAPPING
12 |
13 |
14 | class pSp(nn.Module):
15 |
16 | def __init__(self, opts):
17 | super(pSp, self).__init__()
18 | self.set_opts(opts)
19 | self.n_styles = int(math.log(self.opts.output_size, 2)) * 2 - 2
20 | # Define architecture
21 | self.encoder = self.set_encoder()
22 | self.decoder = Generator(self.opts.output_size, 512, 8, channel_multiplier=2)
23 | self.face_pool = torch.nn.AdaptiveAvgPool2d((256, 256))
24 | # Load weights if needed
25 | self.load_weights()
26 |
27 | def set_encoder(self):
28 | if self.opts.encoder_type == 'GradualStyleEncoder':
29 | encoder = fpn_encoders.GradualStyleEncoder(50, 'ir_se', self.n_styles, self.opts)
30 | elif self.opts.encoder_type == 'ResNetGradualStyleEncoder':
31 | encoder = fpn_encoders.ResNetGradualStyleEncoder(self.n_styles, self.opts)
32 | elif self.opts.encoder_type == 'BackboneEncoder':
33 | encoder = restyle_psp_encoders.BackboneEncoder(50, 'ir_se', self.n_styles, self.opts)
34 | elif self.opts.encoder_type == 'ResNetBackboneEncoder':
35 | encoder = restyle_psp_encoders.ResNetBackboneEncoder(self.n_styles, self.opts)
36 | else:
37 | raise Exception(f'{self.opts.encoder_type} is not a valid encoders')
38 | return encoder
39 |
40 | def load_weights(self):
41 | if self.opts.checkpoint_path is not None:
42 | print(f'Loading ReStyle pSp from checkpoint: {self.opts.checkpoint_path}')
43 | ckpt = torch.load(self.opts.checkpoint_path, map_location='cpu')
44 | self.encoder.load_state_dict(self.__get_keys(ckpt, 'encoder'), strict=False)
45 | self.decoder.load_state_dict(self.__get_keys(ckpt, 'decoder'), strict=True)
46 | self.__load_latent_avg(ckpt)
47 | else:
48 | encoder_ckpt = self.__get_encoder_checkpoint()
49 | self.encoder.load_state_dict(encoder_ckpt, strict=False)
50 | print(f'Loading decoder weights from pretrained path: {self.opts.stylegan_weights}')
51 | ckpt = torch.load(self.opts.stylegan_weights)
52 | self.decoder.load_state_dict(ckpt['g_ema'], strict=True)
53 | self.__load_latent_avg(ckpt, repeat=self.n_styles)
54 |
55 | def forward(self, x, latent=None, resize=True, latent_mask=None, input_code=False, randomize_noise=True,
56 | inject_latent=None, return_latents=False, alpha=None, average_code=False, input_is_full=False):
57 | if input_code:
58 | codes = x
59 | else:
60 | codes = self.encoder(x)
61 | # residual step
62 | if x.shape[1] == 6 and latent is not None:
63 | # learn error with respect to previous iteration
64 | codes = codes + latent
65 | else:
66 | # first iteration is with respect to the avg latent code
67 | codes = codes + self.latent_avg.repeat(codes.shape[0], 1, 1)
68 |
69 | if latent_mask is not None:
70 | for i in latent_mask:
71 | if inject_latent is not None:
72 | if alpha is not None:
73 | codes[:, i] = alpha * inject_latent[:, i] + (1 - alpha) * codes[:, i]
74 | else:
75 | codes[:, i] = inject_latent[:, i]
76 | else:
77 | codes[:, i] = 0
78 |
79 | if average_code:
80 | input_is_latent = True
81 | else:
82 | input_is_latent = (not input_code) or (input_is_full)
83 |
84 | images, result_latent = self.decoder([codes],
85 | input_is_latent=input_is_latent,
86 | randomize_noise=randomize_noise,
87 | return_latents=return_latents)
88 |
89 | if resize:
90 | images = self.face_pool(images)
91 |
92 | if return_latents:
93 | return images, result_latent
94 | else:
95 | return images
96 |
97 | def set_opts(self, opts):
98 | self.opts = opts
99 |
100 | def __load_latent_avg(self, ckpt, repeat=None):
101 | if 'latent_avg' in ckpt:
102 | self.latent_avg = ckpt['latent_avg'].to(self.opts.device)
103 | if repeat is not None:
104 | self.latent_avg = self.latent_avg.repeat(repeat, 1)
105 | else:
106 | self.latent_avg = None
107 |
108 | def __get_encoder_checkpoint(self):
109 | if "ffhq" in self.opts.dataset_type:
110 | print('Loading encoders weights from irse50!')
111 | encoder_ckpt = torch.load(model_paths['ir_se50'])
112 | # Transfer the RGB input of the irse50 network to the first 3 input channels of pSp's encoder
113 | if self.opts.input_nc != 3:
114 | shape = encoder_ckpt['input_layer.0.weight'].shape
115 | altered_input_layer = torch.randn(shape[0], self.opts.input_nc, shape[2], shape[3], dtype=torch.float32)
116 | altered_input_layer[:, :3, :, :] = encoder_ckpt['input_layer.0.weight']
117 | encoder_ckpt['input_layer.0.weight'] = altered_input_layer
118 | return encoder_ckpt
119 | else:
120 | print('Loading encoders weights from resnet34!')
121 | encoder_ckpt = torch.load(model_paths['resnet34'])
122 | # Transfer the RGB input of the resnet34 network to the first 3 input channels of pSp's encoder
123 | if self.opts.input_nc != 3:
124 | shape = encoder_ckpt['conv1.weight'].shape
125 | altered_input_layer = torch.randn(shape[0], self.opts.input_nc, shape[2], shape[3], dtype=torch.float32)
126 | altered_input_layer[:, :3, :, :] = encoder_ckpt['conv1.weight']
127 | encoder_ckpt['conv1.weight'] = altered_input_layer
128 | mapped_encoder_ckpt = dict(encoder_ckpt)
129 | for p, v in encoder_ckpt.items():
130 | for original_name, psp_name in RESNET_MAPPING.items():
131 | if original_name in p:
132 | mapped_encoder_ckpt[p.replace(original_name, psp_name)] = v
133 | mapped_encoder_ckpt.pop(p)
134 | return encoder_ckpt
135 |
136 | @staticmethod
137 | def __get_keys(d, name):
138 | if 'state_dict' in d:
139 | d = d['state_dict']
140 | d_filt = {k[len(name) + 1:]: v for k, v in d.items() if k[:len(name)] == name}
141 | return d_filt
142 |
--------------------------------------------------------------------------------
/models/stylegan2/__init__.py:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/1jsingh/paint2pix/971d1ea06ef6cbcc555ad09a365bf1621ce13f08/models/stylegan2/__init__.py
--------------------------------------------------------------------------------
/models/stylegan2/op/__init__.py:
--------------------------------------------------------------------------------
1 | from .fused_act import FusedLeakyReLU, fused_leaky_relu
2 | from .upfirdn2d import upfirdn2d
3 |
--------------------------------------------------------------------------------
/models/stylegan2/op/fused_act.py:
--------------------------------------------------------------------------------
1 | import os
2 |
3 | import torch
4 | from torch import nn
5 | from torch.autograd import Function
6 | from torch.utils.cpp_extension import load
7 |
8 | module_path = os.path.dirname(__file__)
9 | fused = load(
10 | 'fused',
11 | sources=[
12 | os.path.join(module_path, 'fused_bias_act.cpp'),
13 | os.path.join(module_path, 'fused_bias_act_kernel.cu'),
14 | ],
15 | )
16 |
17 |
18 | class FusedLeakyReLUFunctionBackward(Function):
19 | @staticmethod
20 | def forward(ctx, grad_output, out, negative_slope, scale):
21 | ctx.save_for_backward(out)
22 | ctx.negative_slope = negative_slope
23 | ctx.scale = scale
24 |
25 | empty = grad_output.new_empty(0)
26 |
27 | grad_input = fused.fused_bias_act(
28 | grad_output, empty, out, 3, 1, negative_slope, scale
29 | )
30 |
31 | dim = [0]
32 |
33 | if grad_input.ndim > 2:
34 | dim += list(range(2, grad_input.ndim))
35 |
36 | grad_bias = grad_input.sum(dim).detach()
37 |
38 | return grad_input, grad_bias
39 |
40 | @staticmethod
41 | def backward(ctx, gradgrad_input, gradgrad_bias):
42 | out, = ctx.saved_tensors
43 | gradgrad_out = fused.fused_bias_act(
44 | gradgrad_input, gradgrad_bias, out, 3, 1, ctx.negative_slope, ctx.scale
45 | )
46 |
47 | return gradgrad_out, None, None, None
48 |
49 |
50 | class FusedLeakyReLUFunction(Function):
51 | @staticmethod
52 | def forward(ctx, input, bias, negative_slope, scale):
53 | empty = input.new_empty(0)
54 | out = fused.fused_bias_act(input, bias, empty, 3, 0, negative_slope, scale)
55 | ctx.save_for_backward(out)
56 | ctx.negative_slope = negative_slope
57 | ctx.scale = scale
58 |
59 | return out
60 |
61 | @staticmethod
62 | def backward(ctx, grad_output):
63 | out, = ctx.saved_tensors
64 |
65 | grad_input, grad_bias = FusedLeakyReLUFunctionBackward.apply(
66 | grad_output, out, ctx.negative_slope, ctx.scale
67 | )
68 |
69 | return grad_input, grad_bias, None, None
70 |
71 |
72 | class FusedLeakyReLU(nn.Module):
73 | def __init__(self, channel, negative_slope=0.2, scale=2 ** 0.5):
74 | super().__init__()
75 |
76 | self.bias = nn.Parameter(torch.zeros(channel))
77 | self.negative_slope = negative_slope
78 | self.scale = scale
79 |
80 | def forward(self, input):
81 | return fused_leaky_relu(input, self.bias, self.negative_slope, self.scale)
82 |
83 |
84 | def fused_leaky_relu(input, bias, negative_slope=0.2, scale=2 ** 0.5):
85 | return FusedLeakyReLUFunction.apply(input, bias, negative_slope, scale)
86 |
--------------------------------------------------------------------------------
/models/stylegan2/op/fused_bias_act.cpp:
--------------------------------------------------------------------------------
1 | #include
2 |
3 |
4 | torch::Tensor fused_bias_act_op(const torch::Tensor& input, const torch::Tensor& bias, const torch::Tensor& refer,
5 | int act, int grad, float alpha, float scale);
6 |
7 | #define CHECK_CUDA(x) TORCH_CHECK(x.type().is_cuda(), #x " must be a CUDA tensor")
8 | #define CHECK_CONTIGUOUS(x) TORCH_CHECK(x.is_contiguous(), #x " must be contiguous")
9 | #define CHECK_INPUT(x) CHECK_CUDA(x); CHECK_CONTIGUOUS(x)
10 |
11 | torch::Tensor fused_bias_act(const torch::Tensor& input, const torch::Tensor& bias, const torch::Tensor& refer,
12 | int act, int grad, float alpha, float scale) {
13 | CHECK_CUDA(input);
14 | CHECK_CUDA(bias);
15 |
16 | return fused_bias_act_op(input, bias, refer, act, grad, alpha, scale);
17 | }
18 |
19 | PYBIND11_MODULE(TORCH_EXTENSION_NAME, m) {
20 | m.def("fused_bias_act", &fused_bias_act, "fused bias act (CUDA)");
21 | }
--------------------------------------------------------------------------------
/models/stylegan2/op/fused_bias_act_kernel.cu:
--------------------------------------------------------------------------------
1 | // Copyright (c) 2019, NVIDIA Corporation. All rights reserved.
2 | //
3 | // This work is made available under the Nvidia Source Code License-NC.
4 | // To view a copy of this license, visit
5 | // https://nvlabs.github.io/stylegan2/license.html
6 |
7 | #include
8 |
9 | #include
10 | #include
11 | #include
12 | #include
13 |
14 | #include
15 | #include
16 |
17 |
18 | template
19 | static __global__ void fused_bias_act_kernel(scalar_t* out, const scalar_t* p_x, const scalar_t* p_b, const scalar_t* p_ref,
20 | int act, int grad, scalar_t alpha, scalar_t scale, int loop_x, int size_x, int step_b, int size_b, int use_bias, int use_ref) {
21 | int xi = blockIdx.x * loop_x * blockDim.x + threadIdx.x;
22 |
23 | scalar_t zero = 0.0;
24 |
25 | for (int loop_idx = 0; loop_idx < loop_x && xi < size_x; loop_idx++, xi += blockDim.x) {
26 | scalar_t x = p_x[xi];
27 |
28 | if (use_bias) {
29 | x += p_b[(xi / step_b) % size_b];
30 | }
31 |
32 | scalar_t ref = use_ref ? p_ref[xi] : zero;
33 |
34 | scalar_t y;
35 |
36 | switch (act * 10 + grad) {
37 | default:
38 | case 10: y = x; break;
39 | case 11: y = x; break;
40 | case 12: y = 0.0; break;
41 |
42 | case 30: y = (x > 0.0) ? x : x * alpha; break;
43 | case 31: y = (ref > 0.0) ? x : x * alpha; break;
44 | case 32: y = 0.0; break;
45 | }
46 |
47 | out[xi] = y * scale;
48 | }
49 | }
50 |
51 |
52 | torch::Tensor fused_bias_act_op(const torch::Tensor& input, const torch::Tensor& bias, const torch::Tensor& refer,
53 | int act, int grad, float alpha, float scale) {
54 | int curDevice = -1;
55 | cudaGetDevice(&curDevice);
56 | cudaStream_t stream = at::cuda::getCurrentCUDAStream(curDevice);
57 |
58 | auto x = input.contiguous();
59 | auto b = bias.contiguous();
60 | auto ref = refer.contiguous();
61 |
62 | int use_bias = b.numel() ? 1 : 0;
63 | int use_ref = ref.numel() ? 1 : 0;
64 |
65 | int size_x = x.numel();
66 | int size_b = b.numel();
67 | int step_b = 1;
68 |
69 | for (int i = 1 + 1; i < x.dim(); i++) {
70 | step_b *= x.size(i);
71 | }
72 |
73 | int loop_x = 4;
74 | int block_size = 4 * 32;
75 | int grid_size = (size_x - 1) / (loop_x * block_size) + 1;
76 |
77 | auto y = torch::empty_like(x);
78 |
79 | AT_DISPATCH_FLOATING_TYPES_AND_HALF(x.scalar_type(), "fused_bias_act_kernel", [&] {
80 | fused_bias_act_kernel<<>>(
81 | y.data_ptr(),
82 | x.data_ptr(),
83 | b.data_ptr(),
84 | ref.data_ptr(),
85 | act,
86 | grad,
87 | alpha,
88 | scale,
89 | loop_x,
90 | size_x,
91 | step_b,
92 | size_b,
93 | use_bias,
94 | use_ref
95 | );
96 | });
97 |
98 | return y;
99 | }
--------------------------------------------------------------------------------
/models/stylegan2/op/upfirdn2d.cpp:
--------------------------------------------------------------------------------
1 | #include
2 |
3 |
4 | torch::Tensor upfirdn2d_op(const torch::Tensor& input, const torch::Tensor& kernel,
5 | int up_x, int up_y, int down_x, int down_y,
6 | int pad_x0, int pad_x1, int pad_y0, int pad_y1);
7 |
8 | #define CHECK_CUDA(x) TORCH_CHECK(x.type().is_cuda(), #x " must be a CUDA tensor")
9 | #define CHECK_CONTIGUOUS(x) TORCH_CHECK(x.is_contiguous(), #x " must be contiguous")
10 | #define CHECK_INPUT(x) CHECK_CUDA(x); CHECK_CONTIGUOUS(x)
11 |
12 | torch::Tensor upfirdn2d(const torch::Tensor& input, const torch::Tensor& kernel,
13 | int up_x, int up_y, int down_x, int down_y,
14 | int pad_x0, int pad_x1, int pad_y0, int pad_y1) {
15 | CHECK_CUDA(input);
16 | CHECK_CUDA(kernel);
17 |
18 | return upfirdn2d_op(input, kernel, up_x, up_y, down_x, down_y, pad_x0, pad_x1, pad_y0, pad_y1);
19 | }
20 |
21 | PYBIND11_MODULE(TORCH_EXTENSION_NAME, m) {
22 | m.def("upfirdn2d", &upfirdn2d, "upfirdn2d (CUDA)");
23 | }
--------------------------------------------------------------------------------
/models/stylegan2/op/upfirdn2d.py:
--------------------------------------------------------------------------------
1 | import os
2 |
3 | import torch
4 | from torch.autograd import Function
5 | from torch.utils.cpp_extension import load
6 |
7 | module_path = os.path.dirname(__file__)
8 | upfirdn2d_op = load(
9 | 'upfirdn2d',
10 | sources=[
11 | os.path.join(module_path, 'upfirdn2d.cpp'),
12 | os.path.join(module_path, 'upfirdn2d_kernel.cu'),
13 | ],
14 | )
15 |
16 |
17 | class UpFirDn2dBackward(Function):
18 | @staticmethod
19 | def forward(
20 | ctx, grad_output, kernel, grad_kernel, up, down, pad, g_pad, in_size, out_size
21 | ):
22 | up_x, up_y = up
23 | down_x, down_y = down
24 | g_pad_x0, g_pad_x1, g_pad_y0, g_pad_y1 = g_pad
25 |
26 | grad_output = grad_output.reshape(-1, out_size[0], out_size[1], 1)
27 |
28 | grad_input = upfirdn2d_op.upfirdn2d(
29 | grad_output,
30 | grad_kernel,
31 | down_x,
32 | down_y,
33 | up_x,
34 | up_y,
35 | g_pad_x0,
36 | g_pad_x1,
37 | g_pad_y0,
38 | g_pad_y1,
39 | )
40 | grad_input = grad_input.view(in_size[0], in_size[1], in_size[2], in_size[3])
41 |
42 | ctx.save_for_backward(kernel)
43 |
44 | pad_x0, pad_x1, pad_y0, pad_y1 = pad
45 |
46 | ctx.up_x = up_x
47 | ctx.up_y = up_y
48 | ctx.down_x = down_x
49 | ctx.down_y = down_y
50 | ctx.pad_x0 = pad_x0
51 | ctx.pad_x1 = pad_x1
52 | ctx.pad_y0 = pad_y0
53 | ctx.pad_y1 = pad_y1
54 | ctx.in_size = in_size
55 | ctx.out_size = out_size
56 |
57 | return grad_input
58 |
59 | @staticmethod
60 | def backward(ctx, gradgrad_input):
61 | kernel, = ctx.saved_tensors
62 |
63 | gradgrad_input = gradgrad_input.reshape(-1, ctx.in_size[2], ctx.in_size[3], 1)
64 |
65 | gradgrad_out = upfirdn2d_op.upfirdn2d(
66 | gradgrad_input,
67 | kernel,
68 | ctx.up_x,
69 | ctx.up_y,
70 | ctx.down_x,
71 | ctx.down_y,
72 | ctx.pad_x0,
73 | ctx.pad_x1,
74 | ctx.pad_y0,
75 | ctx.pad_y1,
76 | )
77 | # gradgrad_out = gradgrad_out.view(ctx.in_size[0], ctx.out_size[0], ctx.out_size[1], ctx.in_size[3])
78 | gradgrad_out = gradgrad_out.view(
79 | ctx.in_size[0], ctx.in_size[1], ctx.out_size[0], ctx.out_size[1]
80 | )
81 |
82 | return gradgrad_out, None, None, None, None, None, None, None, None
83 |
84 |
85 | class UpFirDn2d(Function):
86 | @staticmethod
87 | def forward(ctx, input, kernel, up, down, pad):
88 | up_x, up_y = up
89 | down_x, down_y = down
90 | pad_x0, pad_x1, pad_y0, pad_y1 = pad
91 |
92 | kernel_h, kernel_w = kernel.shape
93 | batch, channel, in_h, in_w = input.shape
94 | ctx.in_size = input.shape
95 |
96 | input = input.reshape(-1, in_h, in_w, 1)
97 |
98 | ctx.save_for_backward(kernel, torch.flip(kernel, [0, 1]))
99 |
100 | out_h = (in_h * up_y + pad_y0 + pad_y1 - kernel_h) // down_y + 1
101 | out_w = (in_w * up_x + pad_x0 + pad_x1 - kernel_w) // down_x + 1
102 | ctx.out_size = (out_h, out_w)
103 |
104 | ctx.up = (up_x, up_y)
105 | ctx.down = (down_x, down_y)
106 | ctx.pad = (pad_x0, pad_x1, pad_y0, pad_y1)
107 |
108 | g_pad_x0 = kernel_w - pad_x0 - 1
109 | g_pad_y0 = kernel_h - pad_y0 - 1
110 | g_pad_x1 = in_w * up_x - out_w * down_x + pad_x0 - up_x + 1
111 | g_pad_y1 = in_h * up_y - out_h * down_y + pad_y0 - up_y + 1
112 |
113 | ctx.g_pad = (g_pad_x0, g_pad_x1, g_pad_y0, g_pad_y1)
114 |
115 | out = upfirdn2d_op.upfirdn2d(
116 | input, kernel, up_x, up_y, down_x, down_y, pad_x0, pad_x1, pad_y0, pad_y1
117 | )
118 | # out = out.view(major, out_h, out_w, minor)
119 | out = out.view(-1, channel, out_h, out_w)
120 |
121 | return out
122 |
123 | @staticmethod
124 | def backward(ctx, grad_output):
125 | kernel, grad_kernel = ctx.saved_tensors
126 |
127 | grad_input = UpFirDn2dBackward.apply(
128 | grad_output,
129 | kernel,
130 | grad_kernel,
131 | ctx.up,
132 | ctx.down,
133 | ctx.pad,
134 | ctx.g_pad,
135 | ctx.in_size,
136 | ctx.out_size,
137 | )
138 |
139 | return grad_input, None, None, None, None
140 |
141 |
142 | def upfirdn2d(input, kernel, up=1, down=1, pad=(0, 0)):
143 | out = UpFirDn2d.apply(
144 | input, kernel, (up, up), (down, down), (pad[0], pad[1], pad[0], pad[1])
145 | )
146 |
147 | return out
148 |
149 |
150 | def upfirdn2d_native(
151 | input, kernel, up_x, up_y, down_x, down_y, pad_x0, pad_x1, pad_y0, pad_y1
152 | ):
153 | _, in_h, in_w, minor = input.shape
154 | kernel_h, kernel_w = kernel.shape
155 |
156 | out = input.view(-1, in_h, 1, in_w, 1, minor)
157 | out = F.pad(out, [0, 0, 0, up_x - 1, 0, 0, 0, up_y - 1])
158 | out = out.view(-1, in_h * up_y, in_w * up_x, minor)
159 |
160 | out = F.pad(
161 | out, [0, 0, max(pad_x0, 0), max(pad_x1, 0), max(pad_y0, 0), max(pad_y1, 0)]
162 | )
163 | out = out[
164 | :,
165 | max(-pad_y0, 0): out.shape[1] - max(-pad_y1, 0),
166 | max(-pad_x0, 0): out.shape[2] - max(-pad_x1, 0),
167 | :,
168 | ]
169 |
170 | out = out.permute(0, 3, 1, 2)
171 | out = out.reshape(
172 | [-1, 1, in_h * up_y + pad_y0 + pad_y1, in_w * up_x + pad_x0 + pad_x1]
173 | )
174 | w = torch.flip(kernel, [0, 1]).view(1, 1, kernel_h, kernel_w)
175 | out = F.conv2d(out, w)
176 | out = out.reshape(
177 | -1,
178 | minor,
179 | in_h * up_y + pad_y0 + pad_y1 - kernel_h + 1,
180 | in_w * up_x + pad_x0 + pad_x1 - kernel_w + 1,
181 | )
182 | out = out.permute(0, 2, 3, 1)
183 |
184 | return out[:, ::down_y, ::down_x, :]
185 |
--------------------------------------------------------------------------------
/models/stylegan2/op/upfirdn2d_kernel.cu:
--------------------------------------------------------------------------------
1 | // Copyright (c) 2019, NVIDIA Corporation. All rights reserved.
2 | //
3 | // This work is made available under the Nvidia Source Code License-NC.
4 | // To view a copy of this license, visit
5 | // https://nvlabs.github.io/stylegan2/license.html
6 |
7 | #include
8 |
9 | #include
10 | #include
11 | #include
12 | #include
13 |
14 | #include
15 | #include
16 |
17 |
18 | static __host__ __device__ __forceinline__ int floor_div(int a, int b) {
19 | int c = a / b;
20 |
21 | if (c * b > a) {
22 | c--;
23 | }
24 |
25 | return c;
26 | }
27 |
28 |
29 | struct UpFirDn2DKernelParams {
30 | int up_x;
31 | int up_y;
32 | int down_x;
33 | int down_y;
34 | int pad_x0;
35 | int pad_x1;
36 | int pad_y0;
37 | int pad_y1;
38 |
39 | int major_dim;
40 | int in_h;
41 | int in_w;
42 | int minor_dim;
43 | int kernel_h;
44 | int kernel_w;
45 | int out_h;
46 | int out_w;
47 | int loop_major;
48 | int loop_x;
49 | };
50 |
51 |
52 | template
53 | __global__ void upfirdn2d_kernel(scalar_t* out, const scalar_t* input, const scalar_t* kernel, const UpFirDn2DKernelParams p) {
54 | const int tile_in_h = ((tile_out_h - 1) * down_y + kernel_h - 1) / up_y + 1;
55 | const int tile_in_w = ((tile_out_w - 1) * down_x + kernel_w - 1) / up_x + 1;
56 |
57 | __shared__ volatile float sk[kernel_h][kernel_w];
58 | __shared__ volatile float sx[tile_in_h][tile_in_w];
59 |
60 | int minor_idx = blockIdx.x;
61 | int tile_out_y = minor_idx / p.minor_dim;
62 | minor_idx -= tile_out_y * p.minor_dim;
63 | tile_out_y *= tile_out_h;
64 | int tile_out_x_base = blockIdx.y * p.loop_x * tile_out_w;
65 | int major_idx_base = blockIdx.z * p.loop_major;
66 |
67 | if (tile_out_x_base >= p.out_w | tile_out_y >= p.out_h | major_idx_base >= p.major_dim) {
68 | return;
69 | }
70 |
71 | for (int tap_idx = threadIdx.x; tap_idx < kernel_h * kernel_w; tap_idx += blockDim.x) {
72 | int ky = tap_idx / kernel_w;
73 | int kx = tap_idx - ky * kernel_w;
74 | scalar_t v = 0.0;
75 |
76 | if (kx < p.kernel_w & ky < p.kernel_h) {
77 | v = kernel[(p.kernel_h - 1 - ky) * p.kernel_w + (p.kernel_w - 1 - kx)];
78 | }
79 |
80 | sk[ky][kx] = v;
81 | }
82 |
83 | for (int loop_major = 0, major_idx = major_idx_base; loop_major < p.loop_major & major_idx < p.major_dim; loop_major++, major_idx++) {
84 | for (int loop_x = 0, tile_out_x = tile_out_x_base; loop_x < p.loop_x & tile_out_x < p.out_w; loop_x++, tile_out_x += tile_out_w) {
85 | int tile_mid_x = tile_out_x * down_x + up_x - 1 - p.pad_x0;
86 | int tile_mid_y = tile_out_y * down_y + up_y - 1 - p.pad_y0;
87 | int tile_in_x = floor_div(tile_mid_x, up_x);
88 | int tile_in_y = floor_div(tile_mid_y, up_y);
89 |
90 | __syncthreads();
91 |
92 | for (int in_idx = threadIdx.x; in_idx < tile_in_h * tile_in_w; in_idx += blockDim.x) {
93 | int rel_in_y = in_idx / tile_in_w;
94 | int rel_in_x = in_idx - rel_in_y * tile_in_w;
95 | int in_x = rel_in_x + tile_in_x;
96 | int in_y = rel_in_y + tile_in_y;
97 |
98 | scalar_t v = 0.0;
99 |
100 | if (in_x >= 0 & in_y >= 0 & in_x < p.in_w & in_y < p.in_h) {
101 | v = input[((major_idx * p.in_h + in_y) * p.in_w + in_x) * p.minor_dim + minor_idx];
102 | }
103 |
104 | sx[rel_in_y][rel_in_x] = v;
105 | }
106 |
107 | __syncthreads();
108 | for (int out_idx = threadIdx.x; out_idx < tile_out_h * tile_out_w; out_idx += blockDim.x) {
109 | int rel_out_y = out_idx / tile_out_w;
110 | int rel_out_x = out_idx - rel_out_y * tile_out_w;
111 | int out_x = rel_out_x + tile_out_x;
112 | int out_y = rel_out_y + tile_out_y;
113 |
114 | int mid_x = tile_mid_x + rel_out_x * down_x;
115 | int mid_y = tile_mid_y + rel_out_y * down_y;
116 | int in_x = floor_div(mid_x, up_x);
117 | int in_y = floor_div(mid_y, up_y);
118 | int rel_in_x = in_x - tile_in_x;
119 | int rel_in_y = in_y - tile_in_y;
120 | int kernel_x = (in_x + 1) * up_x - mid_x - 1;
121 | int kernel_y = (in_y + 1) * up_y - mid_y - 1;
122 |
123 | scalar_t v = 0.0;
124 |
125 | #pragma unroll
126 | for (int y = 0; y < kernel_h / up_y; y++)
127 | #pragma unroll
128 | for (int x = 0; x < kernel_w / up_x; x++)
129 | v += sx[rel_in_y + y][rel_in_x + x] * sk[kernel_y + y * up_y][kernel_x + x * up_x];
130 |
131 | if (out_x < p.out_w & out_y < p.out_h) {
132 | out[((major_idx * p.out_h + out_y) * p.out_w + out_x) * p.minor_dim + minor_idx] = v;
133 | }
134 | }
135 | }
136 | }
137 | }
138 |
139 |
140 | torch::Tensor upfirdn2d_op(const torch::Tensor& input, const torch::Tensor& kernel,
141 | int up_x, int up_y, int down_x, int down_y,
142 | int pad_x0, int pad_x1, int pad_y0, int pad_y1) {
143 | int curDevice = -1;
144 | cudaGetDevice(&curDevice);
145 | cudaStream_t stream = at::cuda::getCurrentCUDAStream(curDevice);
146 |
147 | UpFirDn2DKernelParams p;
148 |
149 | auto x = input.contiguous();
150 | auto k = kernel.contiguous();
151 |
152 | p.major_dim = x.size(0);
153 | p.in_h = x.size(1);
154 | p.in_w = x.size(2);
155 | p.minor_dim = x.size(3);
156 | p.kernel_h = k.size(0);
157 | p.kernel_w = k.size(1);
158 | p.up_x = up_x;
159 | p.up_y = up_y;
160 | p.down_x = down_x;
161 | p.down_y = down_y;
162 | p.pad_x0 = pad_x0;
163 | p.pad_x1 = pad_x1;
164 | p.pad_y0 = pad_y0;
165 | p.pad_y1 = pad_y1;
166 |
167 | p.out_h = (p.in_h * p.up_y + p.pad_y0 + p.pad_y1 - p.kernel_h + p.down_y) / p.down_y;
168 | p.out_w = (p.in_w * p.up_x + p.pad_x0 + p.pad_x1 - p.kernel_w + p.down_x) / p.down_x;
169 |
170 | auto out = at::empty({p.major_dim, p.out_h, p.out_w, p.minor_dim}, x.options());
171 |
172 | int mode = -1;
173 |
174 | int tile_out_h;
175 | int tile_out_w;
176 |
177 | if (p.up_x == 1 && p.up_y == 1 && p.down_x == 1 && p.down_y == 1 && p.kernel_h <= 4 && p.kernel_w <= 4) {
178 | mode = 1;
179 | tile_out_h = 16;
180 | tile_out_w = 64;
181 | }
182 |
183 | if (p.up_x == 1 && p.up_y == 1 && p.down_x == 1 && p.down_y == 1 && p.kernel_h <= 3 && p.kernel_w <= 3) {
184 | mode = 2;
185 | tile_out_h = 16;
186 | tile_out_w = 64;
187 | }
188 |
189 | if (p.up_x == 2 && p.up_y == 2 && p.down_x == 1 && p.down_y == 1 && p.kernel_h <= 4 && p.kernel_w <= 4) {
190 | mode = 3;
191 | tile_out_h = 16;
192 | tile_out_w = 64;
193 | }
194 |
195 | if (p.up_x == 2 && p.up_y == 2 && p.down_x == 1 && p.down_y == 1 && p.kernel_h <= 2 && p.kernel_w <= 2) {
196 | mode = 4;
197 | tile_out_h = 16;
198 | tile_out_w = 64;
199 | }
200 |
201 | if (p.up_x == 1 && p.up_y == 1 && p.down_x == 2 && p.down_y == 2 && p.kernel_h <= 4 && p.kernel_w <= 4) {
202 | mode = 5;
203 | tile_out_h = 8;
204 | tile_out_w = 32;
205 | }
206 |
207 | if (p.up_x == 1 && p.up_y == 1 && p.down_x == 2 && p.down_y == 2 && p.kernel_h <= 2 && p.kernel_w <= 2) {
208 | mode = 6;
209 | tile_out_h = 8;
210 | tile_out_w = 32;
211 | }
212 |
213 | dim3 block_size;
214 | dim3 grid_size;
215 |
216 | if (tile_out_h > 0 && tile_out_w) {
217 | p.loop_major = (p.major_dim - 1) / 16384 + 1;
218 | p.loop_x = 1;
219 | block_size = dim3(32 * 8, 1, 1);
220 | grid_size = dim3(((p.out_h - 1) / tile_out_h + 1) * p.minor_dim,
221 | (p.out_w - 1) / (p.loop_x * tile_out_w) + 1,
222 | (p.major_dim - 1) / p.loop_major + 1);
223 | }
224 |
225 | AT_DISPATCH_FLOATING_TYPES_AND_HALF(x.scalar_type(), "upfirdn2d_cuda", [&] {
226 | switch (mode) {
227 | case 1:
228 | upfirdn2d_kernel<<>>(
229 | out.data_ptr(), x.data_ptr(), k.data_ptr(), p
230 | );
231 |
232 | break;
233 |
234 | case 2:
235 | upfirdn2d_kernel<<>>(
236 | out.data_ptr(), x.data_ptr(), k.data_ptr(), p
237 | );
238 |
239 | break;
240 |
241 | case 3:
242 | upfirdn2d_kernel<<>>(
243 | out.data_ptr(), x.data_ptr(), k.data_ptr(), p
244 | );
245 |
246 | break;
247 |
248 | case 4:
249 | upfirdn2d_kernel<<>>(
250 | out.data_ptr(), x.data_ptr(), k.data_ptr(), p
251 | );
252 |
253 | break;
254 |
255 | case 5:
256 | upfirdn2d_kernel<<>>(
257 | out.data_ptr(), x.data_ptr(), k.data_ptr(), p
258 | );
259 |
260 | break;
261 |
262 | case 6:
263 | upfirdn2d_kernel<<>>(
264 | out.data_ptr(), x.data_ptr(), k.data_ptr(), p
265 | );
266 |
267 | break;
268 | }
269 | });
270 |
271 | return out;
272 | }
--------------------------------------------------------------------------------
/output/result_0.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/1jsingh/paint2pix/971d1ea06ef6cbcc555ad09a365bf1621ce13f08/output/result_0.png
--------------------------------------------------------------------------------
/output/result_mask_0.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/1jsingh/paint2pix/971d1ea06ef6cbcc555ad09a365bf1621ce13f08/output/result_mask_0.png
--------------------------------------------------------------------------------
/utils/.ipynb_checkpoints/id_utils-checkpoint.py:
--------------------------------------------------------------------------------
1 | from utils.common import tensor2im
2 | from PIL import ImageColor
3 | import torch
4 | import cv2
5 |
6 | import numpy as np
7 | from collections import deque
8 | import cv2
9 | import pandas as pd
10 | import os,sys
11 | import glob
12 |
13 | import random
14 | import torch
15 | import torch.nn as nn
16 | import torch.nn.functional as F
17 | import torch.optim as optim
18 | from torchvision import transforms, utils
19 | from PIL import Image
20 |
21 | from utils.common import tensor2im
22 | from models.psp import pSp
23 | from models.e4e import e4e
24 | # from utils.inference_utils import run_on_batch
25 |
26 | from criteria import id_loss, moco_loss
27 |
28 | # from utils.common import tensor2im
29 | # from options.train_options import TrainOptions
30 | # from models.psp import pSp
31 |
32 | import streamlit as st
33 |
34 |
35 | from argparse import Namespace
36 |
37 | import torch
38 | import clip
39 | from PIL import Image
40 |
41 | device = torch.device("cuda:0" if torch.cuda.is_available() else "cpu")
42 |
43 | def load_model(experiment_type='ffhq',use_baseline=False,id_constrain=False):
44 | with torch.no_grad():
45 | if experiment_type == 'ffhq':
46 | if use_baseline:
47 | model_path = 'pretrained_models/restyle_e4e_ffhq_encode.pt'
48 | else:
49 | #model_path = 'experiment_paint_v2/checkpoints/best_model.pt'
50 | #model_path = 'experiment_paint_v4/checkpoints/best_model.pt'
51 | #model_path = 'experiment_1024_v4/checkpoints/best_model.pt'
52 | if id_constrain:
53 | model_path = 'experiments/celeba/intelli-paint/paint_1024_id-constrain_v2/checkpoints/best_model.pt'
54 | else:
55 | model_path = 'experiments/celeba/intelli-paint/paint_1024_v1/checkpoints/best_model.pt'
56 |
57 | resize_dims = (256,256)
58 |
59 | elif experiment_type == 'cars_encode':
60 | model_path = 'pretrained_models/restyle_e4e_cars_encode.pt'
61 | model_path = 'experiments/cars196/intelli-paint/paint_512_v1/checkpoints/best_model.pt'
62 | resize_dims = (192,256)
63 |
64 | ckpt = torch.load(model_path, map_location='cpu')
65 | opts = ckpt['opts']
66 | # pprint.pprint(opts) # Display full options used
67 | # update the training options
68 | opts['checkpoint_path'] = model_path
69 | opts['device'] = device
70 |
71 | opts = Namespace(**opts)
72 | net = e4e(opts)
73 | # if experiment_type == 'horse_encode' or experiment_type == 'ffhq_encode':
74 | # net = e4e(opts)
75 | # else:
76 | # net = pSp(opts)
77 |
78 | net.eval()
79 | net = net.to(device)
80 | print('Model successfully loaded!')
81 |
82 | transform = transforms.Compose([
83 | transforms.Resize(resize_dims),
84 | transforms.ToTensor(),
85 | transforms.Normalize([0.5, 0.5, 0.5], [0.5, 0.5, 0.5])])
86 |
87 | return net, transform, opts
88 |
89 |
90 | def get_avg_image(net, experiment_type='ffhq'):
91 | avg_image = net(net.latent_avg.unsqueeze(0),
92 | input_code=True,
93 | randomize_noise=False,
94 | return_latents=False,
95 | average_code=True)[0]
96 | avg_image = avg_image.to('cuda').float().detach()
97 | if experiment_type == "cars_encode":
98 | avg_image = avg_image[:, 32:224, :]
99 | return avg_image
100 |
101 | def run_on_batch(inputs, net, opts, avg_image, target_id_feat=None):
102 | y_hat, latent = None, None
103 | #results_batch = {idx: [] for idx in range(inputs.shape[0])}
104 | #results_latent = {idx: [] for idx in range(inputs.shape[0])}
105 | for iter in range(opts.n_iters_per_batch):
106 | if iter == 0:
107 | avg_image_for_batch = avg_image.unsqueeze(0).repeat(inputs.shape[0], 1, 1, 1)
108 | x_input = torch.cat([inputs, avg_image_for_batch], dim=1)
109 | else:
110 | x_input = torch.cat([inputs, y_hat], dim=1)
111 |
112 | y_hat, latent = net.forward(x_input,
113 | target_id_feat=target_id_feat,
114 | latent=latent,
115 | randomize_noise=False,
116 | return_latents=True,
117 | resize=opts.resize_outputs)
118 |
119 | if opts.dataset_type == "cars_encode":
120 | if opts.resize_outputs:
121 | y_hat = y_hat[:, :, 32:224, :]
122 | else:
123 | y_hat = y_hat[:, :, 64:448, :]
124 |
125 | # # store intermediate outputs
126 | # for idx in range(inputs.shape[0]):
127 | # results_batch[idx].append(y_hat[idx])
128 | # results_latent[idx].append(latent[idx].cpu().numpy())
129 |
130 | # resize input to 256 before feeding into next iteration
131 | if opts.dataset_type == "cars_encode":
132 | y_hat = torch.nn.AdaptiveAvgPool2d((192, 256))(y_hat)
133 | else:
134 | y_hat = net.face_pool(y_hat)
135 |
136 | return y_hat, latent #results_batch, results_latent
137 |
138 | def predict_image_completion(image, net, transform, opts, preprocess=False, experiment_type='ffhq', resize_dims=(256,256), multi_modal=False, num_multi_output=5, n_iters=5, latent_mask=None ,mix_alpha=None, id_constrain=False, target_id_feat=None):
139 | opts.n_iters_per_batch = n_iters
140 | opts.resize_outputs = False # generate outputs at full resolution
141 |
142 | if preprocess:
143 | image = transform(image).to(device).unsqueeze(0)
144 |
145 | with torch.no_grad():
146 | avg_image = get_avg_image(net,experiment_type)
147 | images, latents = run_on_batch(image, net, opts, avg_image)
148 | #run_on_batch(transformed_image.unsqueeze(0), net, experiment_type=experiment_type)
149 | #result_images, latent = images[0], latents[0]
150 |
151 | if preprocess:
152 | result_image = tensor2im(result_images[-1]).resize(resize_dims[::-1])
153 | return images, latents
--------------------------------------------------------------------------------
/utils/.ipynb_checkpoints/inference_utils-checkpoint.py:
--------------------------------------------------------------------------------
1 | import torch
2 |
3 |
4 | def get_average_image(net, opts):
5 | avg_image = net(net.latent_avg.unsqueeze(0),
6 | input_code=True,
7 | randomize_noise=False,
8 | return_latents=False,
9 | average_code=True)[0]
10 | avg_image = avg_image.to('cuda').float().detach()
11 | if opts.dataset_type == "cars_encode":
12 | avg_image = avg_image[:, 32:224, :]
13 | return avg_image
14 |
15 |
16 | def run_on_batch(inputs, net, opts, avg_image, target_id_feat=None):
17 | y_hat, latent = None, None
18 | results_batch = {idx: [] for idx in range(inputs.shape[0])}
19 | results_latent = {idx: [] for idx in range(inputs.shape[0])}
20 | for iter in range(opts.n_iters_per_batch):
21 | if iter == 0:
22 | avg_image_for_batch = avg_image.unsqueeze(0).repeat(inputs.shape[0], 1, 1, 1)
23 | x_input = torch.cat([inputs, avg_image_for_batch], dim=1)
24 | else:
25 | x_input = torch.cat([inputs, y_hat], dim=1)
26 |
27 | y_hat, latent = net.forward(x_input,
28 | target_id_feat=target_id_feat,
29 | latent=latent,
30 | randomize_noise=False,
31 | return_latents=True,
32 | resize=opts.resize_outputs)
33 |
34 | if opts.dataset_type == "cars_encode":
35 | if opts.resize_outputs:
36 | y_hat = y_hat[:, :, 32:224, :]
37 | else:
38 | y_hat = y_hat[:, :, 64:448, :]
39 |
40 | # store intermediate outputs
41 | for idx in range(inputs.shape[0]):
42 | results_batch[idx].append(y_hat[idx])
43 | results_latent[idx].append(latent[idx].cpu().numpy())
44 |
45 | # resize input to 256 before feeding into next iteration
46 | if opts.dataset_type == "cars_encode":
47 | y_hat = torch.nn.AdaptiveAvgPool2d((192, 256))(y_hat)
48 | else:
49 | y_hat = net.face_pool(y_hat)
50 |
51 | return results_batch, results_latent
52 |
--------------------------------------------------------------------------------
/utils/__init__.py:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/1jsingh/paint2pix/971d1ea06ef6cbcc555ad09a365bf1621ce13f08/utils/__init__.py
--------------------------------------------------------------------------------
/utils/common.py:
--------------------------------------------------------------------------------
1 | from PIL import Image
2 | import matplotlib.pyplot as plt
3 |
4 |
5 | def tensor2im(var):
6 | var = var.cpu().detach().transpose(0, 2).transpose(0, 1).numpy()
7 | var = ((var + 1) / 2)
8 | var[var < 0] = 0
9 | var[var > 1] = 1
10 | var = var * 255
11 | return Image.fromarray(var.astype('uint8'))
12 |
13 |
14 | def vis_faces(log_hooks):
15 | display_count = len(log_hooks)
16 | n_outputs = len(log_hooks[0]['output_face']) if type(log_hooks[0]['output_face']) == list else 1
17 | fig = plt.figure(figsize=(6 + (n_outputs * 2), 4 * display_count))
18 | gs = fig.add_gridspec(display_count, (2 + n_outputs))
19 | for i in range(display_count):
20 | hooks_dict = log_hooks[i]
21 | fig.add_subplot(gs[i, 0])
22 | vis_faces_iterative(hooks_dict, fig, gs, i)
23 | plt.tight_layout()
24 | return fig
25 |
26 |
27 | def vis_faces_iterative(hooks_dict, fig, gs, i):
28 | plt.imshow(hooks_dict['input_face'])
29 | plt.title('Input\nOut Sim={:.2f}'.format(float(hooks_dict['diff_input'])))
30 | fig.add_subplot(gs[i, 1])
31 | plt.imshow(hooks_dict['target_face'])
32 | plt.title('Target\nIn={:.2f}, Out={:.2f}'.format(float(hooks_dict['diff_views']), float(hooks_dict['diff_target'])))
33 | for idx, output_idx in enumerate(range(len(hooks_dict['output_face']) - 1, -1, -1)):
34 | output_image, similarity = hooks_dict['output_face'][output_idx]
35 | fig.add_subplot(gs[i, 2 + idx])
36 | plt.imshow(output_image)
37 | plt.title('Output {}\n Target Sim={:.2f}'.format(output_idx, float(similarity)))
38 |
--------------------------------------------------------------------------------
/utils/data_utils.py:
--------------------------------------------------------------------------------
1 | """
2 | Code adopted from pix2pixHD:
3 | https://github.com/NVIDIA/pix2pixHD/blob/master/data/image_folder.py
4 | """
5 | import os
6 |
7 | IMG_EXTENSIONS = [
8 | '.jpg', '.JPG', '.jpeg', '.JPEG',
9 | '.png', '.PNG', '.ppm', '.PPM', '.bmp', '.BMP', '.tiff'
10 | ]
11 |
12 |
13 | def is_image_file(filename):
14 | return any(filename.endswith(extension) for extension in IMG_EXTENSIONS)
15 |
16 |
17 | def make_dataset(dir):
18 | images = []
19 | assert os.path.isdir(dir), '%s is not a valid directory' % dir
20 | for root, _, fnames in sorted(os.walk(dir)):
21 | for fname in fnames:
22 | if is_image_file(fname):
23 | path = os.path.join(root, fname)
24 | images.append(path)
25 | return images
26 |
--------------------------------------------------------------------------------
/utils/id_utils.py:
--------------------------------------------------------------------------------
1 | from utils.common import tensor2im
2 | from PIL import ImageColor
3 | import torch
4 | import cv2
5 |
6 | import numpy as np
7 | from collections import deque
8 | import cv2
9 | import pandas as pd
10 | import os,sys
11 | import glob
12 |
13 | import random
14 | import torch
15 | import torch.nn as nn
16 | import torch.nn.functional as F
17 | import torch.optim as optim
18 | from torchvision import transforms, utils
19 | from PIL import Image
20 |
21 | from utils.common import tensor2im
22 | from models.psp import pSp
23 | from models.e4e import e4e
24 | # from utils.inference_utils import run_on_batch
25 |
26 | from criteria import id_loss, moco_loss
27 |
28 | # from utils.common import tensor2im
29 | # from options.train_options import TrainOptions
30 | # from models.psp import pSp
31 |
32 | import streamlit as st
33 |
34 |
35 | from argparse import Namespace
36 |
37 | import torch
38 | import clip
39 | from PIL import Image
40 |
41 | device = torch.device("cuda:0" if torch.cuda.is_available() else "cpu")
42 |
43 | def load_model(experiment_type='ffhq',use_baseline=False,id_constrain=False):
44 | with torch.no_grad():
45 | if experiment_type == 'ffhq':
46 | if use_baseline:
47 | model_path = 'pretrained_models/restyle_e4e_ffhq_encode.pt'
48 | else:
49 | #model_path = 'experiment_paint_v2/checkpoints/best_model.pt'
50 | #model_path = 'experiment_paint_v4/checkpoints/best_model.pt'
51 | #model_path = 'experiment_1024_v4/checkpoints/best_model.pt'
52 | if id_constrain:
53 | model_path = 'experiments/celeba/intelli-paint/paint_1024_id-constrain_v2/checkpoints/best_model.pt'
54 | else:
55 | model_path = 'experiments/celeba/intelli-paint/paint_1024_v1/checkpoints/best_model.pt'
56 |
57 | resize_dims = (256,256)
58 |
59 | elif experiment_type == 'cars_encode':
60 | model_path = 'pretrained_models/restyle_e4e_cars_encode.pt'
61 | model_path = 'experiments/cars196/intelli-paint/paint_512_v1/checkpoints/best_model.pt'
62 | resize_dims = (192,256)
63 |
64 | ckpt = torch.load(model_path, map_location='cpu')
65 | opts = ckpt['opts']
66 | # pprint.pprint(opts) # Display full options used
67 | # update the training options
68 | opts['checkpoint_path'] = model_path
69 | opts['device'] = device
70 |
71 | opts = Namespace(**opts)
72 | net = e4e(opts)
73 | # if experiment_type == 'horse_encode' or experiment_type == 'ffhq_encode':
74 | # net = e4e(opts)
75 | # else:
76 | # net = pSp(opts)
77 |
78 | net.eval()
79 | net = net.to(device)
80 | print('Model successfully loaded!')
81 |
82 | transform = transforms.Compose([
83 | transforms.Resize(resize_dims),
84 | transforms.ToTensor(),
85 | transforms.Normalize([0.5, 0.5, 0.5], [0.5, 0.5, 0.5])])
86 |
87 | return net, transform, opts
88 |
89 |
90 | def get_avg_image(net, experiment_type='ffhq'):
91 | avg_image = net(net.latent_avg.unsqueeze(0),
92 | input_code=True,
93 | randomize_noise=False,
94 | return_latents=False,
95 | average_code=True)[0]
96 | avg_image = avg_image.to('cuda').float().detach()
97 | if experiment_type == "cars_encode":
98 | avg_image = avg_image[:, 32:224, :]
99 | return avg_image
100 |
101 | def run_on_batch(inputs, net, opts, avg_image, target_id_feat=None):
102 | y_hat, latent = None, None
103 | #results_batch = {idx: [] for idx in range(inputs.shape[0])}
104 | #results_latent = {idx: [] for idx in range(inputs.shape[0])}
105 | for iter in range(opts.n_iters_per_batch):
106 | if iter == 0:
107 | avg_image_for_batch = avg_image.unsqueeze(0).repeat(inputs.shape[0], 1, 1, 1)
108 | x_input = torch.cat([inputs, avg_image_for_batch], dim=1)
109 | else:
110 | x_input = torch.cat([inputs, y_hat], dim=1)
111 |
112 | y_hat, latent = net.forward(x_input,
113 | target_id_feat=target_id_feat,
114 | latent=latent,
115 | randomize_noise=False,
116 | return_latents=True,
117 | resize=opts.resize_outputs)
118 |
119 | if opts.dataset_type == "cars_encode":
120 | if opts.resize_outputs:
121 | y_hat = y_hat[:, :, 32:224, :]
122 | else:
123 | y_hat = y_hat[:, :, 64:448, :]
124 |
125 | # # store intermediate outputs
126 | # for idx in range(inputs.shape[0]):
127 | # results_batch[idx].append(y_hat[idx])
128 | # results_latent[idx].append(latent[idx].cpu().numpy())
129 |
130 | # resize input to 256 before feeding into next iteration
131 | if opts.dataset_type == "cars_encode":
132 | y_hat = torch.nn.AdaptiveAvgPool2d((192, 256))(y_hat)
133 | else:
134 | y_hat = net.face_pool(y_hat)
135 |
136 | return y_hat, latent #results_batch, results_latent
137 |
138 | def predict_image_completion(image, net, transform, opts, preprocess=False, experiment_type='ffhq', resize_dims=(256,256), multi_modal=False, num_multi_output=5, n_iters=5, latent_mask=None ,mix_alpha=None, id_constrain=False, target_id_feat=None):
139 | opts.n_iters_per_batch = n_iters
140 | opts.resize_outputs = False # generate outputs at full resolution
141 |
142 | if preprocess:
143 | image = transform(image).to(device).unsqueeze(0)
144 |
145 | with torch.no_grad():
146 | avg_image = get_avg_image(net,experiment_type)
147 | images, latents = run_on_batch(image, net, opts, avg_image)
148 | #run_on_batch(transformed_image.unsqueeze(0), net, experiment_type=experiment_type)
149 | #result_images, latent = images[0], latents[0]
150 |
151 | if preprocess:
152 | result_image = tensor2im(result_images[-1]).resize(resize_dims[::-1])
153 | return images, latents
--------------------------------------------------------------------------------
/utils/inference_utils.py:
--------------------------------------------------------------------------------
1 | import torch
2 |
3 |
4 | def get_average_image(net, opts):
5 | avg_image = net(net.latent_avg.unsqueeze(0),
6 | input_code=True,
7 | randomize_noise=False,
8 | return_latents=False,
9 | average_code=True)[0]
10 | avg_image = avg_image.to('cuda').float().detach()
11 | if opts.dataset_type == "cars_encode":
12 | avg_image = avg_image[:, 32:224, :]
13 | return avg_image
14 |
15 |
16 | def run_on_batch(inputs, net, opts, avg_image, target_id_feat=None):
17 | y_hat, latent = None, None
18 | results_batch = {idx: [] for idx in range(inputs.shape[0])}
19 | results_latent = {idx: [] for idx in range(inputs.shape[0])}
20 | for iter in range(opts.n_iters_per_batch):
21 | if iter == 0:
22 | avg_image_for_batch = avg_image.unsqueeze(0).repeat(inputs.shape[0], 1, 1, 1)
23 | x_input = torch.cat([inputs, avg_image_for_batch, inputs, avg_image_for_batch], dim=1)
24 | else:
25 | x_input = torch.cat([inputs, y_hat, inputs, y_hat], dim=1)
26 |
27 | y_hat, latent = net.forward(x_input,
28 | target_id_feat=target_id_feat,
29 | latent=latent,
30 | randomize_noise=False,
31 | return_latents=True,
32 | resize=opts.resize_outputs)
33 |
34 | if opts.dataset_type == "cars_encode":
35 | if opts.resize_outputs:
36 | y_hat = y_hat[:, :, 32:224, :]
37 | else:
38 | y_hat = y_hat[:, :, 64:448, :]
39 |
40 | # store intermediate outputs
41 | for idx in range(inputs.shape[0]):
42 | results_batch[idx].append(y_hat[idx])
43 | results_latent[idx].append(latent[idx].cpu().numpy())
44 |
45 | # resize input to 256 before feeding into next iteration
46 | if opts.dataset_type == "cars_encode":
47 | y_hat = torch.nn.AdaptiveAvgPool2d((192, 256))(y_hat)
48 | else:
49 | y_hat = net.face_pool(y_hat)
50 |
51 | return results_batch, results_latent
52 |
--------------------------------------------------------------------------------
/utils/model_utils.py:
--------------------------------------------------------------------------------
1 | # specify the encoder types for pSp and e4e - this is mainly used for the inference scripts
2 | ENCODER_TYPES = {
3 | 'pSp': ['GradualStyleEncoder', 'ResNetGradualStyleEncoder', 'BackboneEncoder', 'ResNetBackboneEncoder'],
4 | 'e4e': ['ProgressiveBackboneEncoder', 'ResNetProgressiveBackboneEncoder']
5 | }
6 |
7 | RESNET_MAPPING = {
8 | 'layer1.0': 'body.0',
9 | 'layer1.1': 'body.1',
10 | 'layer1.2': 'body.2',
11 | 'layer2.0': 'body.3',
12 | 'layer2.1': 'body.4',
13 | 'layer2.2': 'body.5',
14 | 'layer2.3': 'body.6',
15 | 'layer3.0': 'body.7',
16 | 'layer3.1': 'body.8',
17 | 'layer3.2': 'body.9',
18 | 'layer3.3': 'body.10',
19 | 'layer3.4': 'body.11',
20 | 'layer3.5': 'body.12',
21 | 'layer4.0': 'body.13',
22 | 'layer4.1': 'body.14',
23 | 'layer4.2': 'body.15',
24 | }
25 |
--------------------------------------------------------------------------------
/utils/train_utils.py:
--------------------------------------------------------------------------------
1 |
2 | def aggregate_loss_dict(agg_loss_dict):
3 | mean_vals = {}
4 | for output in agg_loss_dict:
5 | for key in output:
6 | mean_vals[key] = mean_vals.setdefault(key, []) + [output[key]]
7 | for key in mean_vals:
8 | if len(mean_vals[key]) > 0:
9 | mean_vals[key] = sum(mean_vals[key]) / len(mean_vals[key])
10 | else:
11 | print('{} has no value'.format(key))
12 | mean_vals[key] = 0
13 | return mean_vals
14 |
--------------------------------------------------------------------------------