Debian Codegraph @

experimental/dist_field/genfield.py

raw symbols SCIP
1 #!/usr/bin/python
2 # $Id:$
3
4 import ctypes
5 import math
6 import optparse
7 import pyglet
8
9 root2 = math.sqrt(2)
10
11 def gen_dist_field(img, width, height, spread, bidirectional=True):
12 sample_width = img.width // width
13 sample_height = img.height // height
14 max_dist = spread * root2
15 dist_scale = 127. / max_dist
16
17 # Grab image data as list of int.
18 data = img.get_data('L', img.width)
19 if isinstance(data, str):
20 data = map(ord, data)
21
22 # Pad input image by `spread` on each side to avoid having to check bounds
23 # Add left and right sides
24 data_tmp = []
25 padx = [0] * spread
26 pitch = img.width
27 in_i = 0
28 for row_i in range(img.height):
29 data_tmp.extend(padx)
30 data_tmp.extend(data[in_i:in_i + pitch])
31 data_tmp.extend(padx)
32 in_i += pitch
33 pitch += spread * 2
34 # Add top and bottom
35 pady = [0] * (pitch * spread)
36 data = pady + data_tmp + pady
37
38 field = []
39 for y in range(height):
40 in_i = (spread + int((y + 0.5) * sample_height)) * pitch + \
41 spread + sample_width // 2
42 for x in range(width):
43 colour = data[in_i]
44 dist1_sq = dist2_sq = dist_sq = (max_dist + 1) ** 2
45 for sy in range(-spread, spread + 1):
46 row_i = in_i + sy * pitch
47 for sx in range(-spread, spread + 1):
48 if data[row_i + sx] != colour:
49 dist_sq = min(dist_sq, sy * sy + sx * sx)
50 if sx * sy > 0:
51 dist1_sq = min(dist1_sq, sy * sy + sx * sx)
52 else:
53 dist2_sq = min(dist2_sq, sy * sy + sx * sx)
54 dist = math.sqrt(dist_sq)
55 dist1 = math.sqrt(dist1_sq)
56 dist2 = math.sqrt(dist2_sq)
57
58 if not colour:
59 dist = -dist
60 dist1 = -dist1
61 dist2 = -dist2
62 dist = int(dist * dist_scale) + 128
63 dist1 = int(dist1 * dist_scale) + 128
64 dist2 = int(dist2 * dist_scale) + 128
65 if bidirectional:
66 field.append(dist1)
67 field.append(dist2)
68 field.append(dist)
69 else:
70 field.append(255)
71 field.append(dist)
72 in_i += sample_width
73
74 field = (ctypes.c_byte * len(field))(*field)
75
76 out_img = pyglet.image.create(width, height)
77 if bidirectional:
78 out_img.set_data('RGBA', width * 4, field)
79 else:
80 out_img.set_data('LA', width * 2, field)
81 return out_img
82
83 if __name__ == '__main__':
84 import os
85
86 parser = optparse.OptionParser()
87 parser.add_option('-s', '--size', type=int, default=32)
88 parser.add_option('-p', '--spread', type=int, default=128)
89 parser.add_option('-o', '--output', default=None)
90 parser.add_option('-b', '--bidirectional', action='store_true',
91 default=False)
92 (options, args) = parser.parse_args()
93
94 filename = args[0]
95 img = pyglet.image.load(filename)
96 img2 = gen_dist_field(img, options.size, options.size,
97 options.spread, options.bidirectional)
98 if not options.output:
99 base, _ = os.path.splitext(filename)
100 options.output = f'{base}.df.png'
101 img2.save(options.output)
102