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
|
"""gen_imgmap.py
Usage: gen_imgmap.py [-hi] image_file csv_file out_file
Options:
-i, --integer-colors Interpret color values as integers (hex is default).
-h, --help Show this information.
Arguments:
image_file – png with one color per clickable area. The areas do not
have to be contiguous, and may have holes.
csv_file – csv mapping colors to tag attributes. The first row must be
labels. The first column must be either a hexadecimal color, or
an integer color (specify -i for integer colors). The remaining
columns will be attached to the area tags as attribute values
(theattribute key will be the column label).
out_file – file name to which the generated image map will be written.
Requirements:
ImageMagick ≥ 6.3.0
Python ≥ 2.4
numpy ≥ 1.0
PIL ≥ 1.1.6\
"""
import sys
import time
import os
import getopt
import csv
import Image
from numpy import *
pil_version = Image.VERSION.split('.')
pil_version =[int(e) for e in pil_version]
if not (len(pil_version) == 3 and pil_version[0] >= 1 and pil_version[1] >= 1 and pil_version[2] >= 6):
sys.stderr.write("your PIL version is too old %s minimum 1.1.6. needed\n" % Image.VERSION)
sys.exit(1)
sys.stdout = sys.stderr
def save(a, name):
Image.fromarray(bit2rgb(a)).save(name)
def bit2rgb(b):
""" Convert a bitmap to an RGB img. """
b = b[:,:,newaxis]*255
return concatenate((b, b, b), 2)
def pixels_of(img):
for y, x in combinations_of(range(img.shape[0]), range(img.shape[1])):
yield y,x
def combinations_of(A,B):
for a in A:
for b in B:
yield a,b
def dist(yx1, yx2):
""" Euclidean distance from `yx1` to `yx2`."""
y1, x1 = yx1
y2, x2 = yx2
return sqrt(float((x2-x1)**2 + (y2-y1)**2))
def fill(img, yx, val):
""" Fill `img` from `yx` with `val`. """
img = img.copy()
edge = [yx]
while edge:
newedge = []
for (y,x) in edge:
for (s, t) in ((y, x+1), (y, x-1), (y+1, x), (y-1, x)):
try:
p = img[s, t]
except IndexError:
pass
else:
if p != val:
img[s, t] = val
newedge.append((s, t))
edge = newedge
return img
def count_neighbors(yx, val, img):
""" Return the number of pixels adjacent to (Y,X) with value `val`. """
c = 0
for t,s in neighbors_of(yx, corners=False):
if (t < 0 or t >= img.shape[0]) or (s < 0 or s >= img.shape[1]):
c+=1
continue
if img[t,s] == val:
c+=1
return c
def neighbors_of(yx, corners=True):
""" Yield the coordinates of pixels that are adjacent yx.
If `corners` is False, don't yield the pixels that are adjacent
to the corners of `yx`.
"""
y,x = yx
if corners:
pixels = [(y-1, x-1), (y-1, x), (y-1, x+1),
( y, x-1), ( y, x+1),
(y+1, x-1), (y+1, x), (y+1, x+1)]
else:
pixels = [(y-1, x), ( y, x+1), (y+1, x), ( y, x-1),]
for yx in pixels:
yield yx
def shapes_from(a):
""" Yield the separate contiguous shapes of a. """
a = a.copy()
while True:
Y, X = a.nonzero()
YX = zip(Y,X)
y,x = min(YX)
b = fill(a, (y,x), 0)
s = logical_xor(b, a)
yield s
a = logical_xor(s,a)
if not a.any():
break
def poly_from(shp):
""" Return the bounding polygon of a contiguous, solid shp.
`shp` should be a binary numpy array. All parts of the shape should be
connected to all other parts of the shape (contiguous). There should not
be a hole in any part of the shape (solid).
"""
if not shp.any():
return []
Y, X = shp.nonzero()
YX = zip(Y,X)
y,x = min(YX)
wfirst = (y, x)
bfirst = (y-1, x)
hist = [(wfirst, bfirst)]
wcurs, bcurs = wfirst, bfirst
while True:
wn = [yx for yx in list(neighbors_of(wcurs))+[wcurs] if yx in YX]
bn = [yx for yx in list(neighbors_of(bcurs)) + [bcurs] if not yx in YX]
distances = [dist(w, b) for w, b in combinations_of(wn, bn)]
temp = sorted(zip(distances, list(combinations_of(wn, bn))))
next_curs = [wb for d, wb in temp if d < 2.0 and wb not in hist]
if all([w in [wh for wh, bh in hist if dist(b, bh) < 2] for w,b in next_curs]) or not next_curs:
break
for wb in next_curs:
wcurs, bcurs = wb
hist.append(wb)
break
poly = [w for w,b in hist]
return poly
def area_of(yx_1, yx_2, yx_3):
""" Euclidean area of the triangle `yx_1`, `yx_2`, `yx_3`. """
y1, x1 = yx_1
y2, x2 = yx_2
y3, x3 = yx_3
return 1/2. * abs(-x2*y1 + x3*y1 + x1*y2 - x3*y2 - x1*y3 + x2*y3)
def simplified(poly, min_area = 0.25):
""" Return a simplified version of `poly` (`poly` is a list or array of points.).
Uses a “triangle-based” simplification algorithm. For consecutive
points along the edge of `poly`"""
i = 0
while True:
if i+2 >= len(poly):
break
j,k,m = i, i+1, i+2
if area_of(poly[j], poly[k], poly[m]) < min_area:
del poly[k]
i = 0
continue
else:
i+=1
return poly
def flip_lonely_pixels(box, min_neighbors=2):
""" Fill in any lonely pixels (a pixel is lonely
if it has less than 2 identical neighbors).
"""
print " Flipping lonely pixels…"
box = box.copy()
while True:
boxl = box.copy()
for Y, X in pixels_of(box):
if count_neighbors((Y,X), box[Y,X], box) < min_neighbors:
box[Y,X] = not box[Y,X]
if (boxl == box).all():
break
return box
def fill_holes(shp):
""" Return `shp` with all of its holes filled in."""
e = shp.copy()
for yx in [(0,0), (-1,0), (0,-1), (-1,-1)]:
d = fill(shp, yx, True)
e = logical_or(e, d)
if logical_not(e).any():
z_order = -1
else:
z_order = 1
filled = logical_or(shp, logical_not(e))
save(filled, 'filled.png')
return filled, z_order
def areatags_from(mask_path=None, kwds={}):
""" Return a list of html area tags for the mask at `mask_path`.
Any kwds is a dictionary of attributes which are added to
ALL of the returned tags. I.e. if you pass {href="http://google.com"},
all of the area tag will have “href="http://google.com"”.
"""
img = asarray(Image.open(mask_path))
img = img[:,:,0].astype(bool |