-
Notifications
You must be signed in to change notification settings - Fork 7
/
Copy pathtiler.py
428 lines (369 loc) · 11.8 KB
/
tiler.py
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
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
import collections
import math
import random
import numpy as np
from PIL import Image
from drawing import cairo_context
from helpers import array_slices_2d, color, range2d, closest
def rotations(cls, num_rots=4):
return map(cls, range(num_rots))
def collect(tile_list, repeat=1, rotations=None, flip=None):
def _dec(cls):
rots = rotations
if rots is None:
rots = cls.rotations
will_flip = flip
if will_flip is None:
will_flip = cls.flip
flips = [False, True] if will_flip else [False]
for _ in range(repeat):
for rot in range(rots):
for flipped in flips:
tile_list.append(cls(rot=rot, flipped=flipped))
return cls
return _dec
def stroke(method):
method.is_stroke = True
return method
class TileBase:
class G:
def __init__(self, wh, bgfg=None):
self.wh = wh
self.bgfg = bgfg
if self.bgfg is None:
self.bgfg = [color(1), color(0)]
rotations = 4
flip = False
def __init__(self, rot=0, flipped=False):
self.rot = rot
self.flipped = flipped
def init_tile(self, ctx, g, base_color=None):
...
def draw_tile(self, ctx, wh, bgfg=None, base_color=None, meth_name="draw"):
g = self.G(wh, bgfg)
self.init_tile(ctx, g, base_color=base_color)
getattr(self, meth_name)(ctx, g)
def tile_value(tile):
"""The gray value of a tile from 0 (black) to 1 (white)."""
pic = multiscale_truchet(tiles=[tile], width=10, height=10, tilew=10, nlayers=1, format="png")
a = np.array(Image.open(pic.pngio).convert("L"))
value = np.sum(a) / a.size / 255
return value
def tile_value4(tile):
"""The four-quadrant gray values (0->1) of a tile."""
pw = 10
pw2 = pw // 2
pic = multiscale_truchet(tiles=[tile], width=pw, height=pw, tilew=pw, nlayers=1, format="png")
a = np.array(Image.open(pic.pngio).convert("L"))
values = []
for a4 in array_slices_2d(a, 0, 0, nx=2, dx=pw2):
values.append(np.sum(a4) / a4.size / 255)
return np.array(values)
def value_chart(tiles, inverted=False):
marg = 50
width = 800
mid = 30
def tick(x, h):
v = (width - 2 * marg) * x + marg
ctx.move_to(v, mid - h / 2)
ctx.line_to(v, mid + h / 2)
ctx.stroke()
with cairo_context(width, mid * 2) as ctx:
ctx.set_line_width(0.5)
ctx.move_to(marg, mid)
ctx.line_to(width - marg, mid)
ctx.stroke()
tick(0, 20)
tick(1, 20)
for t in tiles:
value = tile_value(t)
tick(value, 20)
if inverted:
tick(1 - value, 20)
ctx.set_source_rgb(1, 0, 0)
ctx.set_line_width(2)
for i in range(11):
tick(i / 10, 10)
return ctx
def show_tiles(
tiles,
size=100,
frac=.6,
width=950,
with_value=False,
with_name=False,
only_one=False,
sort=True,
):
if only_one:
# Keep only one of each class
classes = {tile.__class__ for tile in tiles}
tiles = [cls() for cls in classes]
if with_value:
values = {t: f"{tile_value(t):.3f}" for t in tiles}
if sort:
tiles = sorted(tiles, key=lambda t: t.__class__.__name__)
if with_value:
tiles = sorted(tiles, key=values.get)
wh = size * frac
gap = size / 10
per_row = (width + gap) // (size + gap)
nrows = len(tiles) // per_row + (1 if len(tiles) % per_row else 0)
ncols = per_row if nrows > 1 else len(tiles)
totalW = (size + gap) * ncols - gap
totalH = (size + gap) * nrows - gap
with cairo_context(totalW, totalH) as ctx:
ctx.select_font_face("Sans")
ctx.set_font_size(10)
for i, tile in enumerate(tiles):
r, c = divmod(i, per_row)
ctx.save()
ctx.translate((size + gap) * c, (size + gap) * r)
ctx.rectangle(0, 0, size, size)
ctx.set_source_rgb(0.85, 0.85, 0.85)
ctx.fill()
ctx.save()
ctx.translate((size - wh) / 2, (size - wh) / 2)
tile.draw_tile(ctx, wh)
ctx.rectangle(0, 0, wh, wh)
ctx.set_source_rgba(0.5, 0.5, 0.5, 0.75)
ctx.set_line_width(1)
ctx.set_dash([5, 5], 7.5)
ctx.stroke()
ctx.restore()
if with_value:
ctx.move_to(2, 10)
ctx.set_source_rgba(0, 0, 0, 1)
ctx.show_text(values[tile])
if with_name:
ctx.move_to(2, size - 2)
ctx.set_source_rgba(0, 0, 0, 1)
ctx.show_text(tile.__class__.__name__)
ctx.restore()
return ctx
def show_overlap(tile):
W = 200
bgfg = [color(1), color(0)]
with cairo_context(W, W) as ctx:
ctx.rectangle(0, 0, W, W)
ctx.set_source_rgb(.75, .75, .75)
ctx.fill()
ctx.save()
ctx.translate(W/4, W/4)
tile.draw(ctx, W/2, bgfg)
ctx.restore()
offset = 0
bgfg = [color((0, 0, .7)), color((1, .5, .5))]
for x, y in range2d(2, 2):
ctx.save()
ctx.translate(W/4 + x * W/4 + offset, W/4 + y * W/4 + offset)
tile.draw(ctx, W/4, bgfg)
ctx.restore()
return ctx
def multiscale_truchet(
tiles=None,
tile_chooser=None,
width=400,
height=200,
tilew=40,
nlayers=2,
chance=0.5,
should_split=None,
bg=1,
fg=0,
seed=None,
format="svg",
output=None,
grid=False,
):
all_boxes = []
rand = random.Random(seed)
if isinstance(tiles, (list, tuple)):
assert tile_chooser is None
tile_chooser = lambda ux, uy, uw, ilevel: rand.choice(tiles)
if isinstance(chance, float):
_chance = chance
chance = lambda *a, **k: _chance
if should_split is None:
should_split = lambda x, y, size, ilayer: rand.random() <= chance(x, y, size, ilayer)
def one_tile(x, y, size, ilayer):
tile = tile_chooser(x / width, y / width, size / width, ilayer)
with ctx.save_restore():
ctx.translate(x, y)
tile.draw_tile(ctx, size, bgfg)
boxes.append((x, y, size))
if grid:
all_boxes.append((x, y, size))
with cairo_context(width, height, format=format, output=output) as ctx:
boxes = []
bgfg = [color(bg), color(fg)]
wextra = 1 if (width % tilew) else 0
hextra = 1 if (height % tilew) else 0
for ox, oy in range2d(int(width / tilew) + wextra, int(height / tilew) + hextra):
one_tile(ox * tilew, oy * tilew, tilew, 0)
for ilayer in range(nlayers - 1):
last_boxes = boxes
bgfg = bgfg[::-1]
boxes = []
for bx, by, bsize in last_boxes:
if should_split((bx + bsize/2)/ width, (by + bsize/2) / height, bsize / width, ilayer):
nbsize = bsize / 2
for dx, dy in range2d(2, 2):
nbx, nby = bx + dx * nbsize, by + dy * nbsize
one_tile(nbx, nby, nbsize, ilayer+1)
if grid:
ctx.set_line_width(.5)
ctx.set_source_rgb(1, 0, 0)
for x, y, size in all_boxes:
ctx.rectangle(x, y, size, size)
ctx.stroke()
return ctx
def nearest(levels, data):
"""Find the values in a closest to the values in b"""
data_shape = data.shape
linear = data.reshape((math.prod(data_shape),))
adjusted = levels[np.argmin(np.abs(levels[:, np.newaxis] - linear[np.newaxis, :]), axis=0)]
return adjusted.reshape(data_shape)
def image_truchet(
tiles,
image,
width=400,
height=400,
tilew=40,
nlayers=1,
format="svg",
output=None,
grid=False,
seed=None,
scale=0,
jitter=0,
split_thresh=50,
split_test=2,
):
rand = random.Random(seed)
if isinstance(image, str):
image = np.array(Image.open(image).convert("L"))
tile_valuess = []
levelss = []
all_levels = []
for half in [0, 1]:
tile_values = collections.defaultdict(list)
for tile in tiles:
value = int(tile_value(tile) * 255)
if half == 1:
value = 256 - value
tile_values[value].append(tile)
levels = np.array(sorted(tile_values.keys()))
tile_valuess.append(tile_values)
levelss.append(levels)
all_levels.extend(levels)
lmin, lmax = min(all_levels), max(all_levels)
imin, imax = np.min(image), np.max(image)
scale = float(scale)
lmin *= scale
lmax = 1 - scale * (1 - lmax)
imin *= scale
imax = 1 - scale * (1 - imax)
image = image - imin # make a copy of the image
image /= (imax - imin)
image *= (lmax - lmin)
image += lmin
def tile_chooser(ux, uy, us, ilayer):
ix = int(ux * image.shape[0])
iy = int(uy * image.shape[1])
isize = int(us * image.shape[0])
color = np.mean(image[iy:iy+isize, ix:ix+isize])
if jitter:
color += rand.random() * jitter * 2 - jitter
close_color = closest(color, levelss[ilayer % 2])
tiles = tile_valuess[ilayer % 2][close_color]
return rand.choice(tiles)
def should_split(ux, uy, us, _):
nsplit = 2 ** split_test
ix = int(ux * image.shape[0])
iy = int(uy * image.shape[1])
isize = int(us * image.shape[0] / nsplit)
colors = []
for aslice in array_slices_2d(image, ix, iy, nx=nsplit, dx=isize):
colors.append(np.mean(aslice))
lo = min(colors)
hi = max(colors)
return (hi - lo) > split_thresh
return multiscale_truchet(
tile_chooser=tile_chooser,
should_split=should_split,
width=width,
height=height,
tilew=tilew,
nlayers=nlayers,
bg=1,
fg=0,
format=format,
output=output,
grid=grid,
)
def image_truchet4(
tiles,
image,
width=400,
height=400,
tilew=40,
nlayers=1,
format="svg",
output=None,
grid=False,
split_thresh=50,
split_test=2,
):
if isinstance(image, str):
image = np.array(Image.open(image).convert("L"))
tile_valuess = []
for half in [0, 1]:
tile_values = []
for tile in tiles:
value4 = tile_value4(tile)
if half == 1:
value4 = 1 - value4
tile_values.append((value4, tile))
tile_valuess.append(tile_values)
def tile_chooser(ux, uy, us, ilayer):
ix = int(ux * image.shape[0])
iy = int(uy * image.shape[1])
isize = int(us * image.shape[0])
color4 = []
is2 = isize // 2
for aslice in array_slices_2d(image, ix, iy, nx=2, dx=is2):
color4.append(np.mean(aslice))
color4 = np.array(color4) / 255
min_close = 999999999
best_tile = None
for value4, tile in tile_valuess[ilayer % 2]:
close = np.sum(np.absolute(color4 - value4))
if close < min_close:
min_close = close
best_tile = tile
return best_tile
def should_split(ux, uy, us, _):
nsplit = 2 ** split_test
ix = int(ux * image.shape[0])
iy = int(uy * image.shape[1])
isize = int(us * image.shape[0] / nsplit)
colors = []
for aslice in array_slices_2d(image, ix, iy, nx=nsplit, dx=isize):
colors.append(np.mean(aslice))
lo = min(colors)
hi = max(colors)
return (hi - lo) > split_thresh
return multiscale_truchet(
tile_chooser=tile_chooser,
should_split=should_split,
width=width,
height=height,
tilew=tilew,
nlayers=nlayers,
bg=1,
fg=0,
format=format,
output=output,
grid=grid,
)