akhaliq3 commited on
Commit
1a2ae11
1 Parent(s): ee8f6ac

inference update

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