Ahsen Khaliq commited on
Commit
f93590d
1 Parent(s): 035e10c

Create app.py

Browse files
Files changed (1) hide show
  1. app.py +524 -0
app.py ADDED
@@ -0,0 +1,524 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import torch
2
+ import torch.nn.functional as F
3
+ import numpy as np
4
+ from PIL import Image
5
+ import os
6
+ current = os.getcwd()
7
+ print(current)
8
+ full = current + "/inference"
9
+ print(full)
10
+ os.chdir(full)
11
+ print(os.getcwd())
12
+ import network
13
+ import morphology
14
+ import math
15
+ import gradio as gr
16
+ from torchvision import transforms
17
+ import torchtext
18
+
19
+
20
+
21
+ idx = 0
22
+
23
+ torchtext.utils.download_from_url("https://drive.google.com/uc?id=1NDD54BLligyr8tzo8QGI5eihZisXK1nq", root=".")
24
+
25
+
26
+ def save_img(img, output_path):
27
+ result = Image.fromarray((img.data.cpu().numpy().transpose((1, 2, 0)) * 255).astype(np.uint8))
28
+ result.save(output_path)
29
+
30
+
31
+ def param2stroke(param, H, W, meta_brushes):
32
+ """
33
+ Input a set of stroke parameters and output its corresponding foregrounds and alpha maps.
34
+ Args:
35
+ param: a tensor with shape n_strokes x n_param_per_stroke. Here, param_per_stroke is 8:
36
+ x_center, y_center, width, height, theta, R, G, and B.
37
+ H: output height.
38
+ W: output width.
39
+ meta_brushes: a tensor with shape 2 x 3 x meta_brush_height x meta_brush_width.
40
+ The first slice on the batch dimension denotes vertical brush and the second one denotes horizontal brush.
41
+
42
+ Returns:
43
+ foregrounds: a tensor with shape n_strokes x 3 x H x W, containing color information.
44
+ alphas: a tensor with shape n_strokes x 3 x H x W,
45
+ containing binary information of whether a pixel is belonging to the stroke (alpha mat), for painting process.
46
+ """
47
+ # Firstly, resize the meta brushes to the required shape,
48
+ # in order to decrease GPU memory especially when the required shape is small.
49
+ meta_brushes_resize = F.interpolate(meta_brushes, (H, W))
50
+ b = param.shape[0]
51
+ # Extract shape parameters and color parameters.
52
+ param_list = torch.split(param, 1, dim=1)
53
+ x0, y0, w, h, theta = [item.squeeze(-1) for item in param_list[:5]]
54
+ R, G, B = param_list[5:]
55
+ # Pre-compute sin theta and cos theta
56
+ sin_theta = torch.sin(torch.acos(torch.tensor(-1., device=param.device)) * theta)
57
+ cos_theta = torch.cos(torch.acos(torch.tensor(-1., device=param.device)) * theta)
58
+ # index means each stroke should use which meta stroke? Vertical meta stroke or horizontal meta stroke.
59
+ # When h > w, vertical stroke should be used. When h <= w, horizontal stroke should be used.
60
+ index = torch.full((b,), -1, device=param.device, dtype=torch.long)
61
+ index[h > w] = 0
62
+ index[h <= w] = 1
63
+ brush = meta_brushes_resize[index.long()]
64
+
65
+ # Calculate warp matrix according to the rules defined by pytorch, in order for warping.
66
+ warp_00 = cos_theta / w
67
+ warp_01 = sin_theta * H / (W * w)
68
+ warp_02 = (1 - 2 * x0) * cos_theta / w + (1 - 2 * y0) * sin_theta * H / (W * w)
69
+ warp_10 = -sin_theta * W / (H * h)
70
+ warp_11 = cos_theta / h
71
+ warp_12 = (1 - 2 * y0) * cos_theta / h - (1 - 2 * x0) * sin_theta * W / (H * h)
72
+ warp_0 = torch.stack([warp_00, warp_01, warp_02], dim=1)
73
+ warp_1 = torch.stack([warp_10, warp_11, warp_12], dim=1)
74
+ warp = torch.stack([warp_0, warp_1], dim=1)
75
+ # Conduct warping.
76
+ grid = F.affine_grid(warp, [b, 3, H, W], align_corners=False)
77
+ brush = F.grid_sample(brush, grid, align_corners=False)
78
+ # alphas is the binary information suggesting whether a pixel is belonging to the stroke.
79
+ alphas = (brush > 0).float()
80
+ brush = brush.repeat(1, 3, 1, 1)
81
+ alphas = alphas.repeat(1, 3, 1, 1)
82
+ # Give color to foreground strokes.
83
+ color_map = torch.cat([R, G, B], dim=1)
84
+ color_map = color_map.unsqueeze(-1).unsqueeze(-1).repeat(1, 1, H, W)
85
+ foreground = brush * color_map
86
+ # Dilation and erosion are used for foregrounds and alphas respectively to prevent artifacts on stroke borders.
87
+ foreground = morphology.dilation(foreground)
88
+ alphas = morphology.erosion(alphas)
89
+ return foreground, alphas
90
+
91
+
92
+ def param2img_serial(
93
+ param, decision, meta_brushes, cur_canvas, frame_dir, has_border=False, original_h=None, original_w=None):
94
+ """
95
+ Input stroke parameters and decisions for each patch, meta brushes, current canvas, frame directory,
96
+ and whether there is a border (if intermediate painting results are required).
97
+ Output the painting results of adding the corresponding strokes on the current canvas.
98
+ Args:
99
+ param: a tensor with shape batch size x patch along height dimension x patch along width dimension
100
+ x n_stroke_per_patch x n_param_per_stroke
101
+ decision: a 01 tensor with shape batch size x patch along height dimension x patch along width dimension
102
+ x n_stroke_per_patch
103
+ meta_brushes: a tensor with shape 2 x 3 x meta_brush_height x meta_brush_width.
104
+ The first slice on the batch dimension denotes vertical brush and the second one denotes horizontal brush.
105
+ cur_canvas: a tensor with shape batch size x 3 x H x W,
106
+ where H and W denote height and width of padded results of original images.
107
+ frame_dir: directory to save intermediate painting results. None means intermediate results are not required.
108
+ has_border: on the last painting layer, in order to make sure that the painting results do not miss
109
+ any important detail, we choose to paint again on this layer but shift patch_size // 2 pixels when
110
+ cutting patches. In this case, if intermediate results are required, we need to cut the shifted length
111
+ on the border before saving, or there would be a black border.
112
+ original_h: to indicate the original height for cropping when saving intermediate results.
113
+ original_w: to indicate the original width for cropping when saving intermediate results.
114
+
115
+ Returns:
116
+ cur_canvas: a tensor with shape batch size x 3 x H x W, denoting painting results.
117
+ """
118
+ # param: b, h, w, stroke_per_patch, param_per_stroke
119
+ # decision: b, h, w, stroke_per_patch
120
+ b, h, w, s, p = param.shape
121
+ H, W = cur_canvas.shape[-2:]
122
+ is_odd_y = h % 2 == 1
123
+ is_odd_x = w % 2 == 1
124
+ patch_size_y = 2 * H // h
125
+ patch_size_x = 2 * W // w
126
+ even_idx_y = torch.arange(0, h, 2, device=cur_canvas.device)
127
+ even_idx_x = torch.arange(0, w, 2, device=cur_canvas.device)
128
+ odd_idx_y = torch.arange(1, h, 2, device=cur_canvas.device)
129
+ odd_idx_x = torch.arange(1, w, 2, device=cur_canvas.device)
130
+ even_y_even_x_coord_y, even_y_even_x_coord_x = torch.meshgrid([even_idx_y, even_idx_x])
131
+ odd_y_odd_x_coord_y, odd_y_odd_x_coord_x = torch.meshgrid([odd_idx_y, odd_idx_x])
132
+ even_y_odd_x_coord_y, even_y_odd_x_coord_x = torch.meshgrid([even_idx_y, odd_idx_x])
133
+ odd_y_even_x_coord_y, odd_y_even_x_coord_x = torch.meshgrid([odd_idx_y, even_idx_x])
134
+ cur_canvas = F.pad(cur_canvas, [patch_size_x // 4, patch_size_x // 4,
135
+ patch_size_y // 4, patch_size_y // 4, 0, 0, 0, 0])
136
+
137
+ def partial_render(this_canvas, patch_coord_y, patch_coord_x, stroke_id):
138
+ canvas_patch = F.unfold(this_canvas, (patch_size_y, patch_size_x),
139
+ stride=(patch_size_y // 2, patch_size_x // 2))
140
+ # canvas_patch: b, 3 * py * px, h * w
141
+ canvas_patch = canvas_patch.view(b, 3, patch_size_y, patch_size_x, h, w).contiguous()
142
+ canvas_patch = canvas_patch.permute(0, 4, 5, 1, 2, 3).contiguous()
143
+ # canvas_patch: b, h, w, 3, py, px
144
+ selected_canvas_patch = canvas_patch[:, patch_coord_y, patch_coord_x, :, :, :]
145
+ selected_h, selected_w = selected_canvas_patch.shape[1:3]
146
+ selected_param = param[:, patch_coord_y, patch_coord_x, stroke_id, :].view(-1, p).contiguous()
147
+ selected_decision = decision[:, patch_coord_y, patch_coord_x, stroke_id].view(-1).contiguous()
148
+ selected_foregrounds = torch.zeros(selected_param.shape[0], 3, patch_size_y, patch_size_x,
149
+ device=this_canvas.device)
150
+ selected_alphas = torch.zeros(selected_param.shape[0], 3, patch_size_y, patch_size_x, device=this_canvas.device)
151
+ if selected_param[selected_decision, :].shape[0] > 0:
152
+ selected_foregrounds[selected_decision, :, :, :], selected_alphas[selected_decision, :, :, :] = \
153
+ param2stroke(selected_param[selected_decision, :], patch_size_y, patch_size_x, meta_brushes)
154
+ selected_foregrounds = selected_foregrounds.view(
155
+ b, selected_h, selected_w, 3, patch_size_y, patch_size_x).contiguous()
156
+ selected_alphas = selected_alphas.view(b, selected_h, selected_w, 3, patch_size_y, patch_size_x).contiguous()
157
+ selected_decision = selected_decision.view(b, selected_h, selected_w, 1, 1, 1).contiguous()
158
+ selected_canvas_patch = selected_foregrounds * selected_alphas * selected_decision + selected_canvas_patch * (
159
+ 1 - selected_alphas * selected_decision)
160
+ this_canvas = selected_canvas_patch.permute(0, 3, 1, 4, 2, 5).contiguous()
161
+ # this_canvas: b, 3, selected_h, py, selected_w, px
162
+ this_canvas = this_canvas.view(b, 3, selected_h * patch_size_y, selected_w * patch_size_x).contiguous()
163
+ # this_canvas: b, 3, selected_h * py, selected_w * px
164
+ return this_canvas
165
+
166
+ global idx
167
+ if has_border:
168
+ factor = 2
169
+ else:
170
+ factor = 4
171
+ if even_idx_y.shape[0] > 0 and even_idx_x.shape[0] > 0:
172
+ for i in range(s):
173
+ canvas = partial_render(cur_canvas, even_y_even_x_coord_y, even_y_even_x_coord_x, i)
174
+ if not is_odd_y:
175
+ canvas = torch.cat([canvas, cur_canvas[:, :, -patch_size_y // 2:, :canvas.shape[3]]], dim=2)
176
+ if not is_odd_x:
177
+ canvas = torch.cat([canvas, cur_canvas[:, :, :canvas.shape[2], -patch_size_x // 2:]], dim=3)
178
+ cur_canvas = canvas
179
+ idx += 1
180
+ if frame_dir is not None:
181
+ frame = crop(cur_canvas[:, :, patch_size_y // factor:-patch_size_y // factor,
182
+ patch_size_x // factor:-patch_size_x // factor], original_h, original_w)
183
+ save_img(frame[0], os.path.join(frame_dir, '%03d.jpg' % idx))
184
+
185
+ if odd_idx_y.shape[0] > 0 and odd_idx_x.shape[0] > 0:
186
+ for i in range(s):
187
+ canvas = partial_render(cur_canvas, odd_y_odd_x_coord_y, odd_y_odd_x_coord_x, i)
188
+ canvas = torch.cat([cur_canvas[:, :, :patch_size_y // 2, -canvas.shape[3]:], canvas], dim=2)
189
+ canvas = torch.cat([cur_canvas[:, :, -canvas.shape[2]:, :patch_size_x // 2], canvas], dim=3)
190
+ if is_odd_y:
191
+ canvas = torch.cat([canvas, cur_canvas[:, :, -patch_size_y // 2:, :canvas.shape[3]]], dim=2)
192
+ if is_odd_x:
193
+ canvas = torch.cat([canvas, cur_canvas[:, :, :canvas.shape[2], -patch_size_x // 2:]], dim=3)
194
+ cur_canvas = canvas
195
+ idx += 1
196
+ if frame_dir is not None:
197
+ frame = crop(cur_canvas[:, :, patch_size_y // factor:-patch_size_y // factor,
198
+ patch_size_x // factor:-patch_size_x // factor], original_h, original_w)
199
+ save_img(frame[0], os.path.join(frame_dir, '%03d.jpg' % idx))
200
+
201
+ if odd_idx_y.shape[0] > 0 and even_idx_x.shape[0] > 0:
202
+ for i in range(s):
203
+ canvas = partial_render(cur_canvas, odd_y_even_x_coord_y, odd_y_even_x_coord_x, i)
204
+ canvas = torch.cat([cur_canvas[:, :, :patch_size_y // 2, :canvas.shape[3]], canvas], dim=2)
205
+ if is_odd_y:
206
+ canvas = torch.cat([canvas, cur_canvas[:, :, -patch_size_y // 2:, :canvas.shape[3]]], dim=2)
207
+ if not is_odd_x:
208
+ canvas = torch.cat([canvas, cur_canvas[:, :, :canvas.shape[2], -patch_size_x // 2:]], dim=3)
209
+ cur_canvas = canvas
210
+ idx += 1
211
+ if frame_dir is not None:
212
+ frame = crop(cur_canvas[:, :, patch_size_y // factor:-patch_size_y // factor,
213
+ patch_size_x // factor:-patch_size_x // factor], original_h, original_w)
214
+ save_img(frame[0], os.path.join(frame_dir, '%03d.jpg' % idx))
215
+
216
+ if even_idx_y.shape[0] > 0 and odd_idx_x.shape[0] > 0:
217
+ for i in range(s):
218
+ canvas = partial_render(cur_canvas, even_y_odd_x_coord_y, even_y_odd_x_coord_x, i)
219
+ canvas = torch.cat([cur_canvas[:, :, :canvas.shape[2], :patch_size_x // 2], canvas], dim=3)
220
+ if not is_odd_y:
221
+ canvas = torch.cat([canvas, cur_canvas[:, :, -patch_size_y // 2:, -canvas.shape[3]:]], dim=2)
222
+ if is_odd_x:
223
+ canvas = torch.cat([canvas, cur_canvas[:, :, :canvas.shape[2], -patch_size_x // 2:]], dim=3)
224
+ cur_canvas = canvas
225
+ idx += 1
226
+ if frame_dir is not None:
227
+ frame = crop(cur_canvas[:, :, patch_size_y // factor:-patch_size_y // factor,
228
+ patch_size_x // factor:-patch_size_x // factor], original_h, original_w)
229
+ save_img(frame[0], os.path.join(frame_dir, '%03d.jpg' % idx))
230
+
231
+ cur_canvas = cur_canvas[:, :, patch_size_y // 4:-patch_size_y // 4, patch_size_x // 4:-patch_size_x // 4]
232
+
233
+ return cur_canvas
234
+
235
+
236
+ def param2img_parallel(param, decision, meta_brushes, cur_canvas):
237
+ """
238
+ Input stroke parameters and decisions for each patch, meta brushes, current canvas, frame directory,
239
+ and whether there is a border (if intermediate painting results are required).
240
+ Output the painting results of adding the corresponding strokes on the current canvas.
241
+ Args:
242
+ param: a tensor with shape batch size x patch along height dimension x patch along width dimension
243
+ x n_stroke_per_patch x n_param_per_stroke
244
+ decision: a 01 tensor with shape batch size x patch along height dimension x patch along width dimension
245
+ x n_stroke_per_patch
246
+ meta_brushes: a tensor with shape 2 x 3 x meta_brush_height x meta_brush_width.
247
+ The first slice on the batch dimension denotes vertical brush and the second one denotes horizontal brush.
248
+ cur_canvas: a tensor with shape batch size x 3 x H x W,
249
+ where H and W denote height and width of padded results of original images.
250
+
251
+ Returns:
252
+ cur_canvas: a tensor with shape batch size x 3 x H x W, denoting painting results.
253
+ """
254
+ # param: b, h, w, stroke_per_patch, param_per_stroke
255
+ # decision: b, h, w, stroke_per_patch
256
+ b, h, w, s, p = param.shape
257
+ param = param.view(-1, 8).contiguous()
258
+ decision = decision.view(-1).contiguous().bool()
259
+ H, W = cur_canvas.shape[-2:]
260
+ is_odd_y = h % 2 == 1
261
+ is_odd_x = w % 2 == 1
262
+ patch_size_y = 2 * H // h
263
+ patch_size_x = 2 * W // w
264
+ even_idx_y = torch.arange(0, h, 2, device=cur_canvas.device)
265
+ even_idx_x = torch.arange(0, w, 2, device=cur_canvas.device)
266
+ odd_idx_y = torch.arange(1, h, 2, device=cur_canvas.device)
267
+ odd_idx_x = torch.arange(1, w, 2, device=cur_canvas.device)
268
+ even_y_even_x_coord_y, even_y_even_x_coord_x = torch.meshgrid([even_idx_y, even_idx_x])
269
+ odd_y_odd_x_coord_y, odd_y_odd_x_coord_x = torch.meshgrid([odd_idx_y, odd_idx_x])
270
+ even_y_odd_x_coord_y, even_y_odd_x_coord_x = torch.meshgrid([even_idx_y, odd_idx_x])
271
+ odd_y_even_x_coord_y, odd_y_even_x_coord_x = torch.meshgrid([odd_idx_y, even_idx_x])
272
+ cur_canvas = F.pad(cur_canvas, [patch_size_x // 4, patch_size_x // 4,
273
+ patch_size_y // 4, patch_size_y // 4, 0, 0, 0, 0])
274
+ foregrounds = torch.zeros(param.shape[0], 3, patch_size_y, patch_size_x, device=cur_canvas.device)
275
+ alphas = torch.zeros(param.shape[0], 3, patch_size_y, patch_size_x, device=cur_canvas.device)
276
+ valid_foregrounds, valid_alphas = param2stroke(param[decision, :], patch_size_y, patch_size_x, meta_brushes)
277
+ foregrounds[decision, :, :, :] = valid_foregrounds
278
+ alphas[decision, :, :, :] = valid_alphas
279
+ # foreground, alpha: b * h * w * stroke_per_patch, 3, patch_size_y, patch_size_x
280
+ foregrounds = foregrounds.view(-1, h, w, s, 3, patch_size_y, patch_size_x).contiguous()
281
+ alphas = alphas.view(-1, h, w, s, 3, patch_size_y, patch_size_x).contiguous()
282
+ # foreground, alpha: b, h, w, stroke_per_patch, 3, render_size_y, render_size_x
283
+ decision = decision.view(-1, h, w, s, 1, 1, 1).contiguous()
284
+
285
+ # decision: b, h, w, stroke_per_patch, 1, 1, 1
286
+
287
+ def partial_render(this_canvas, patch_coord_y, patch_coord_x):
288
+
289
+ canvas_patch = F.unfold(this_canvas, (patch_size_y, patch_size_x),
290
+ stride=(patch_size_y // 2, patch_size_x // 2))
291
+ # canvas_patch: b, 3 * py * px, h * w
292
+ canvas_patch = canvas_patch.view(b, 3, patch_size_y, patch_size_x, h, w).contiguous()
293
+ canvas_patch = canvas_patch.permute(0, 4, 5, 1, 2, 3).contiguous()
294
+ # canvas_patch: b, h, w, 3, py, px
295
+ selected_canvas_patch = canvas_patch[:, patch_coord_y, patch_coord_x, :, :, :]
296
+ selected_foregrounds = foregrounds[:, patch_coord_y, patch_coord_x, :, :, :, :]
297
+ selected_alphas = alphas[:, patch_coord_y, patch_coord_x, :, :, :, :]
298
+ selected_decisions = decision[:, patch_coord_y, patch_coord_x, :, :, :, :]
299
+ for i in range(s):
300
+ cur_foreground = selected_foregrounds[:, :, :, i, :, :, :]
301
+ cur_alpha = selected_alphas[:, :, :, i, :, :, :]
302
+ cur_decision = selected_decisions[:, :, :, i, :, :, :]
303
+ selected_canvas_patch = cur_foreground * cur_alpha * cur_decision + selected_canvas_patch * (
304
+ 1 - cur_alpha * cur_decision)
305
+ this_canvas = selected_canvas_patch.permute(0, 3, 1, 4, 2, 5).contiguous()
306
+ # this_canvas: b, 3, h_half, py, w_half, px
307
+ h_half = this_canvas.shape[2]
308
+ w_half = this_canvas.shape[4]
309
+ this_canvas = this_canvas.view(b, 3, h_half * patch_size_y, w_half * patch_size_x).contiguous()
310
+ # this_canvas: b, 3, h_half * py, w_half * px
311
+ return this_canvas
312
+
313
+ if even_idx_y.shape[0] > 0 and even_idx_x.shape[0] > 0:
314
+ canvas = partial_render(cur_canvas, even_y_even_x_coord_y, even_y_even_x_coord_x)
315
+ if not is_odd_y:
316
+ canvas = torch.cat([canvas, cur_canvas[:, :, -patch_size_y // 2:, :canvas.shape[3]]], dim=2)
317
+ if not is_odd_x:
318
+ canvas = torch.cat([canvas, cur_canvas[:, :, :canvas.shape[2], -patch_size_x // 2:]], dim=3)
319
+ cur_canvas = canvas
320
+
321
+ if odd_idx_y.shape[0] > 0 and odd_idx_x.shape[0] > 0:
322
+ canvas = partial_render(cur_canvas, odd_y_odd_x_coord_y, odd_y_odd_x_coord_x)
323
+ canvas = torch.cat([cur_canvas[:, :, :patch_size_y // 2, -canvas.shape[3]:], canvas], dim=2)
324
+ canvas = torch.cat([cur_canvas[:, :, -canvas.shape[2]:, :patch_size_x // 2], canvas], dim=3)
325
+ if is_odd_y:
326
+ canvas = torch.cat([canvas, cur_canvas[:, :, -patch_size_y // 2:, :canvas.shape[3]]], dim=2)
327
+ if is_odd_x:
328
+ canvas = torch.cat([canvas, cur_canvas[:, :, :canvas.shape[2], -patch_size_x // 2:]], dim=3)
329
+ cur_canvas = canvas
330
+
331
+ if odd_idx_y.shape[0] > 0 and even_idx_x.shape[0] > 0:
332
+ canvas = partial_render(cur_canvas, odd_y_even_x_coord_y, odd_y_even_x_coord_x)
333
+ canvas = torch.cat([cur_canvas[:, :, :patch_size_y // 2, :canvas.shape[3]], canvas], dim=2)
334
+ if is_odd_y:
335
+ canvas = torch.cat([canvas, cur_canvas[:, :, -patch_size_y // 2:, :canvas.shape[3]]], dim=2)
336
+ if not is_odd_x:
337
+ canvas = torch.cat([canvas, cur_canvas[:, :, :canvas.shape[2], -patch_size_x // 2:]], dim=3)
338
+ cur_canvas = canvas
339
+
340
+ if even_idx_y.shape[0] > 0 and odd_idx_x.shape[0] > 0:
341
+ canvas = partial_render(cur_canvas, even_y_odd_x_coord_y, even_y_odd_x_coord_x)
342
+ canvas = torch.cat([cur_canvas[:, :, :canvas.shape[2], :patch_size_x // 2], canvas], dim=3)
343
+ if not is_odd_y:
344
+ canvas = torch.cat([canvas, cur_canvas[:, :, -patch_size_y // 2:, -canvas.shape[3]:]], dim=2)
345
+ if is_odd_x:
346
+ canvas = torch.cat([canvas, cur_canvas[:, :, :canvas.shape[2], -patch_size_x // 2:]], dim=3)
347
+ cur_canvas = canvas
348
+
349
+ cur_canvas = cur_canvas[:, :, patch_size_y // 4:-patch_size_y // 4, patch_size_x // 4:-patch_size_x // 4]
350
+
351
+ return cur_canvas
352
+
353
+
354
+ def read_img(img_path, img_type='RGB', h=None, w=None):
355
+ img = Image.open(img_path).convert(img_type)
356
+ if h is not None and w is not None:
357
+ img = img.resize((w, h), resample=Image.NEAREST)
358
+ img = np.array(img)
359
+ if img.ndim == 2:
360
+ img = np.expand_dims(img, axis=-1)
361
+ img = img.transpose((2, 0, 1))
362
+ img = torch.from_numpy(img).unsqueeze(0).float() / 255.
363
+ return img
364
+
365
+
366
+ def pad(img, H, W):
367
+ b, c, h, w = img.shape
368
+ pad_h = (H - h) // 2
369
+ pad_w = (W - w) // 2
370
+ remainder_h = (H - h) % 2
371
+ remainder_w = (W - w) % 2
372
+ img = torch.cat([torch.zeros((b, c, pad_h, w), device=img.device), img,
373
+ torch.zeros((b, c, pad_h + remainder_h, w), device=img.device)], dim=-2)
374
+ img = torch.cat([torch.zeros((b, c, H, pad_w), device=img.device), img,
375
+ torch.zeros((b, c, H, pad_w + remainder_w), device=img.device)], dim=-1)
376
+ return img
377
+
378
+
379
+ def crop(img, h, w):
380
+ H, W = img.shape[-2:]
381
+ pad_h = (H - h) // 2
382
+ pad_w = (W - w) // 2
383
+ remainder_h = (H - h) % 2
384
+ remainder_w = (W - w) % 2
385
+ img = img[:, :, pad_h:H - pad_h - remainder_h, pad_w:W - pad_w - remainder_w]
386
+ return img
387
+
388
+
389
+ def main(input_path, model_path, output_dir, need_animation=False, resize_h=None, resize_w=None, serial=False):
390
+ # if not os.path.exists(output_dir):
391
+ # os.mkdir(output_dir)
392
+ input_name = os.path.basename(input_path)
393
+ # output_path = os.path.join(output_dir, input_name)
394
+ frame_dir = None
395
+ if need_animation:
396
+ if not serial:
397
+ print('It must be under serial mode if animation results are required, so serial flag is set to True!')
398
+ serial = True
399
+ frame_dir = os.path.join(output_dir, input_name[:input_name.find('.')])
400
+ if not os.path.exists(frame_dir):
401
+ os.mkdir(frame_dir)
402
+ patch_size = 32
403
+ stroke_num = 8
404
+ device = torch.device("cuda" if torch.cuda.is_available() else "cpu")
405
+ net_g = network.Painter(5, stroke_num, 256, 8, 3, 3).to(device)
406
+ net_g.load_state_dict(torch.load(model_path))
407
+ net_g.eval()
408
+ for param in net_g.parameters():
409
+ param.requires_grad = False
410
+
411
+ brush_large_vertical = read_img('brush/brush_large_vertical.png', 'L').to(device)
412
+ brush_large_horizontal = read_img('brush/brush_large_horizontal.png', 'L').to(device)
413
+ meta_brushes = torch.cat(
414
+ [brush_large_vertical, brush_large_horizontal], dim=0)
415
+
416
+ with torch.no_grad():
417
+ original_img = read_img(input_path, 'RGB', resize_h, resize_w).to(device)
418
+ original_h, original_w = original_img.shape[-2:]
419
+ K = max(math.ceil(math.log2(max(original_h, original_w) / patch_size)), 0)
420
+ original_img_pad_size = patch_size * (2 ** K)
421
+ original_img_pad = pad(original_img, original_img_pad_size, original_img_pad_size)
422
+ final_result = torch.zeros_like(original_img_pad).to(device)
423
+ for layer in range(0, K + 1):
424
+ layer_size = patch_size * (2 ** layer)
425
+ img = F.interpolate(original_img_pad, (layer_size, layer_size))
426
+ result = F.interpolate(final_result, (patch_size * (2 ** layer), patch_size * (2 ** layer)))
427
+ img_patch = F.unfold(img, (patch_size, patch_size), stride=(patch_size, patch_size))
428
+ result_patch = F.unfold(result, (patch_size, patch_size),
429
+ stride=(patch_size, patch_size))
430
+ # There are patch_num * patch_num patches in total
431
+ patch_num = (layer_size - patch_size) // patch_size + 1
432
+
433
+ # img_patch, result_patch: b, 3 * output_size * output_size, h * w
434
+ img_patch = img_patch.permute(0, 2, 1).contiguous().view(-1, 3, patch_size, patch_size).contiguous()
435
+ result_patch = result_patch.permute(0, 2, 1).contiguous().view(
436
+ -1, 3, patch_size, patch_size).contiguous()
437
+ shape_param, stroke_decision = net_g(img_patch, result_patch)
438
+ stroke_decision = network.SignWithSigmoidGrad.apply(stroke_decision)
439
+
440
+ grid = shape_param[:, :, :2].view(img_patch.shape[0] * stroke_num, 1, 1, 2).contiguous()
441
+ img_temp = img_patch.unsqueeze(1).contiguous().repeat(1, stroke_num, 1, 1, 1).view(
442
+ img_patch.shape[0] * stroke_num, 3, patch_size, patch_size).contiguous()
443
+ color = F.grid_sample(img_temp, 2 * grid - 1, align_corners=False).view(
444
+ img_patch.shape[0], stroke_num, 3).contiguous()
445
+ stroke_param = torch.cat([shape_param, color], dim=-1)
446
+ # stroke_param: b * h * w, stroke_per_patch, param_per_stroke
447
+ # stroke_decision: b * h * w, stroke_per_patch, 1
448
+ param = stroke_param.view(1, patch_num, patch_num, stroke_num, 8).contiguous()
449
+ decision = stroke_decision.view(1, patch_num, patch_num, stroke_num).contiguous().bool()
450
+ # param: b, h, w, stroke_per_patch, 8
451
+ # decision: b, h, w, stroke_per_patch
452
+ param[..., :2] = param[..., :2] / 2 + 0.25
453
+ param[..., 2:4] = param[..., 2:4] / 2
454
+ if serial:
455
+ final_result = param2img_serial(param, decision, meta_brushes, final_result,
456
+ frame_dir, False, original_h, original_w)
457
+ else:
458
+ final_result = param2img_parallel(param, decision, meta_brushes, final_result)
459
+
460
+ border_size = original_img_pad_size // (2 * patch_num)
461
+ img = F.interpolate(original_img_pad, (patch_size * (2 ** layer), patch_size * (2 ** layer)))
462
+ result = F.interpolate(final_result, (patch_size * (2 ** layer), patch_size * (2 ** layer)))
463
+ img = F.pad(img, [patch_size // 2, patch_size // 2, patch_size // 2, patch_size // 2,
464
+ 0, 0, 0, 0])
465
+ result = F.pad(result, [patch_size // 2, patch_size // 2, patch_size // 2, patch_size // 2,
466
+ 0, 0, 0, 0])
467
+ img_patch = F.unfold(img, (patch_size, patch_size), stride=(patch_size, patch_size))
468
+ result_patch = F.unfold(result, (patch_size, patch_size), stride=(patch_size, patch_size))
469
+ final_result = F.pad(final_result, [border_size, border_size, border_size, border_size, 0, 0, 0, 0])
470
+ h = (img.shape[2] - patch_size) // patch_size + 1
471
+ w = (img.shape[3] - patch_size) // patch_size + 1
472
+ # img_patch, result_patch: b, 3 * output_size * output_size, h * w
473
+ img_patch = img_patch.permute(0, 2, 1).contiguous().view(-1, 3, patch_size, patch_size).contiguous()
474
+ result_patch = result_patch.permute(0, 2, 1).contiguous().view(-1, 3, patch_size, patch_size).contiguous()
475
+ shape_param, stroke_decision = net_g(img_patch, result_patch)
476
+
477
+ grid = shape_param[:, :, :2].view(img_patch.shape[0] * stroke_num, 1, 1, 2).contiguous()
478
+ img_temp = img_patch.unsqueeze(1).contiguous().repeat(1, stroke_num, 1, 1, 1).view(
479
+ img_patch.shape[0] * stroke_num, 3, patch_size, patch_size).contiguous()
480
+ color = F.grid_sample(img_temp, 2 * grid - 1, align_corners=False).view(
481
+ img_patch.shape[0], stroke_num, 3).contiguous()
482
+ stroke_param = torch.cat([shape_param, color], dim=-1)
483
+ # stroke_param: b * h * w, stroke_per_patch, param_per_stroke
484
+ # stroke_decision: b * h * w, stroke_per_patch, 1
485
+ param = stroke_param.view(1, h, w, stroke_num, 8).contiguous()
486
+ decision = stroke_decision.view(1, h, w, stroke_num).contiguous().bool()
487
+ # param: b, h, w, stroke_per_patch, 8
488
+ # decision: b, h, w, stroke_per_patch
489
+ param[..., :2] = param[..., :2] / 2 + 0.25
490
+ param[..., 2:4] = param[..., 2:4] / 2
491
+ if serial:
492
+ final_result = param2img_serial(param, decision, meta_brushes, final_result,
493
+ frame_dir, True, original_h, original_w)
494
+ else:
495
+ final_result = param2img_parallel(param, decision, meta_brushes, final_result)
496
+ final_result = final_result[:, :, border_size:-border_size, border_size:-border_size]
497
+
498
+ final_result = crop(final_result, original_h, original_w)
499
+ # save_img(final_result[0], output_path)
500
+ tensor_to_pil = transforms.ToPILImage()(final_result[0].squeeze_(0))
501
+ return tensor_to_pil
502
+
503
+
504
+ def gradio_inference(image):
505
+ return main(input_path=image.name,
506
+ model_path='model.pth',
507
+ output_dir='output/',
508
+ need_animation=False, # whether need intermediate results for animation.
509
+ resize_h=512, # resize original input to this size. None means do not resize.
510
+ resize_w=512, # resize original input to this size. None means do not resize.
511
+ serial=False) # if need animation, serial must be True.
512
+
513
+ title = "Anime2Sketch"
514
+ description = "demo for Anime2Sketch. To use it, simply upload your image, or click one of the examples to load them. Read more at the links below."
515
+ article = "<p style='text-align: center'><a href='https://arxiv.org/abs/2104.05703'>Adversarial Open Domain Adaption for Sketch-to-Photo Synthesis</a> | <a href='https://github.com/Mukosame/Anime2Sketch'>Github Repo</a></p>"
516
+
517
+ gr.Interface(
518
+ gradio_inference,
519
+ [gr.inputs.Image(type="file", label="Input")],
520
+ gr.outputs.Image(type="pil", label="Output"),
521
+ title=title,
522
+ description=description,
523
+ article=article
524
+ ).launch(debug=True)