File size: 5,983 Bytes
35536db
 
 
 
 
 
 
 
 
 
 
 
 
 
d9778ff
35536db
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
d9778ff
fb910bc
35536db
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
d9778ff
35536db
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
import os
from argparse import Namespace
import numpy as np
import torch

from models.StyleGANControler import StyleGANControler


class Model:
    def __init__(
        self, checkpoint_path, truncation=0.5, use_average_code_as_input=False
    ):
        self.truncation = truncation
        self.use_average_code_as_input = use_average_code_as_input
        ckpt = torch.load(checkpoint_path, map_location="cpu")
        opts = ckpt["opts"]
        opts["checkpoint_path"] = checkpoint_path
        self.opts = Namespace(**ckpt["opts"])
        self.net = StyleGANControler(self.opts)
        self.net.eval()
        self.net.cuda()
        self.target_layers = [0, 1, 2, 3, 4, 5]

    def random_sample(self):
        z1 = torch.randn(1, 512).to("cuda")
        x1, w1, f1 = self.net.decoder(
            [z1],
            input_is_latent=False,
            randomize_noise=False,
            return_feature_map=True,
            return_latents=True,
            truncation=self.truncation,
            truncation_latent=self.net.latent_avg[0],
        )
        w1_initial = w1.clone()
        x1 = self.net.face_pool(x1)
        image = (
            ((x1.detach()[0].permute(1, 2, 0) + 1.0) * 127.5).cpu().numpy()[:, :, ::-1]
        )
        return (
            image,
            {
                "w1": w1.cpu().detach().numpy(),
                "w1_initial": w1_initial.cpu().detach().numpy(),
            },
        )  # return latent vector along with the image

    def latents_to_tensor(self, latents):
        w1 = latents["w1"]
        w1_initial = latents["w1_initial"]

        w1 = torch.tensor(w1).to("cuda")
        w1_initial = torch.tensor(w1_initial).to("cuda")

        x1, w1, f1 = self.net.decoder(
            [w1],
            input_is_latent=True,
            randomize_noise=False,
            return_feature_map=True,
            return_latents=True,
        )
        x1, w1_initial, f1 = self.net.decoder(
            [w1_initial],
            input_is_latent=True,
            randomize_noise=False,
            return_feature_map=True,
            return_latents=True,
        )

        return (w1, w1_initial, f1)

    def transform(
        self,
        latents,
        dz,
        dxy,
        sxsy=[0, 0],
        stop_points=[],
        zoom_in=False,
        zoom_out=False,
    ):
        w1, w1_initial, f1 = self.latents_to_tensor(latents)
        w1 = w1_initial.clone()

        dxyz = np.array([dxy[0], dxy[1], dz], dtype=np.float32)
        dxy_norm = np.linalg.norm(dxyz[:2], ord=2)
        epsilon = 1e-8
        dxy_norm = dxy_norm + epsilon
        dxyz[:2] = dxyz[:2] / dxy_norm
        vec_num = dxy_norm / 10

        x = torch.from_numpy(np.array([[dxyz]], dtype=np.float32)).cuda()
        f1 = torch.nn.functional.interpolate(f1, (256, 256))
        y = f1[:, :, sxsy[1], sxsy[0]].unsqueeze(0)

        if len(stop_points) > 0:
            x = torch.cat(
                [x, torch.zeros(x.shape[0], len(stop_points), x.shape[2]).cuda()], dim=1
            )
            tmp = []
            for sp in stop_points:
                tmp.append(f1[:, :, sp[1], sp[0]].unsqueeze(1))
            y = torch.cat([y, torch.cat(tmp, dim=1)], dim=1)

        if not self.use_average_code_as_input:
            w_hat = self.net.encoder(
                w1[:, self.target_layers].detach(),
                x.detach(),
                y.detach(),
                alpha=vec_num,
            )
            w1 = w1.clone()
            w1[:, self.target_layers] = w_hat
        else:
            w_hat = self.net.encoder(
                self.net.latent_avg.unsqueeze(0)[:, self.target_layers].detach(),
                x.detach(),
                y.detach(),
                alpha=vec_num,
            )
            w1 = w1.clone()
            w1[:, self.target_layers] = (
                w1.clone()[:, self.target_layers]
                + w_hat
                - self.net.latent_avg.unsqueeze(0)[:, self.target_layers]
            )

        x1, _ = self.net.decoder([w1], input_is_latent=True, randomize_noise=False)

        x1 = self.net.face_pool(x1)
        result = (
            ((x1.detach()[0].permute(1, 2, 0) + 1.0) * 127.5).cpu().numpy()[:, :, ::-1]
        )
        return (
            result,
            {
                "w1": w1.cpu().detach().numpy(),
                "w1_initial": w1_initial.cpu().detach().numpy(),
            },
        )

    def change_style(self, latents):
        w1, w1_initial, f1 = self.latents_to_tensor(latents)
        w1 = w1_initial.clone()

        z1 = torch.randn(1, 512).to("cuda")
        x1, w2 = self.net.decoder(
            [z1],
            input_is_latent=False,
            randomize_noise=False,
            return_latents=True,
            truncation=self.truncation,
            truncation_latent=self.net.latent_avg[0],
        )
        w1[:, 6:] = w2.detach()[:, 0]
        x1, w1_new = self.net.decoder(
            [w1],
            input_is_latent=True,
            randomize_noise=False,
            return_latents=True,
        )
        result = (
            ((x1.detach()[0].permute(1, 2, 0) + 1.0) * 127.5).cpu().numpy()[:, :, ::-1]
        )
        return (
            result,
            {
                "w1": w1_new.cpu().detach().numpy(),
                "w1_initial": w1_initial.cpu().detach().numpy(),
            },
        )

    def reset(self, latents):
        w1, w1_initial, f1 = self.latents_to_tensor(latents)
        x1, w1_new, f1 = self.net.decoder(
            [w1_initial],
            input_is_latent=True,
            randomize_noise=False,
            return_feature_map=True,
            return_latents=True,
        )
        result = (
            ((x1.detach()[0].permute(1, 2, 0) + 1.0) * 127.5).cpu().numpy()[:, :, ::-1]
        )
        return (
            result,
            {
                "w1": w1_new.cpu().detach().numpy(),
                "w1_initial": w1_new.cpu().detach().numpy(),
            },
        )