-
Notifications
You must be signed in to change notification settings - Fork 0
/
main.py
469 lines (420 loc) · 14.2 KB
/
main.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
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
from math import atan2, degrees, pi
from matplotlib import pyplot as plt
from matplotlib.patches import Rectangle, ConnectionPatch, Polygon
from collections import namedtuple
import sys
import os
import copy
import webbrowser
import numpy as np
import json
import glob
import skimage.io as io
from skimage import color
from skimage import exposure
import colorsys
try:
from skimage.filter import roberts, sobel, scharr, prewitt
except:
pass
SETTINGS_FILE="settings.json"
IMAGE_PATH="image_path"
Line = namedtuple("Line","sx sy ex ey width color")
Rect = namedtuple("Rect","bottomx bottomy topx topy hierarchy")
fig = None
patch = None
orientation = None
click_handlers = True
filename = None
ax = None
# global object
G = {}
G["needle"] = {}
G["px"] = None
G["py"] = None
patches = []
def p(pt, delta=1):
return [pt[0]+delta, pt[1]+delta]
def get_angle(pt1, pt2):
x1 = pt1[0]; x2 = pt2[0]
y1 = pt1[1]; y2 = pt2[1]
dx = x2 - x1
dy = y2 - y1
rads = atan2(-dy,dx)
rads %= 2*pi
return degrees(rads)
def load_settings():
return dict(json.load(open(SETTINGS_FILE,'r')))
def open_color_ref(color_hex):
webbrowser.open("http://www.color-hex.com/color/"+color_hex)
def to_rgb3a(im):
# we can use the same array 3 times
return np.dstack([im] * 3)
def rgb_to_hex(pt):
return '%02x%02x%02x' % (pt[0], pt[1], pt[2])
def do_brighten(pic):
return exposure.adjust_gamma(pic,0.7)
def do_darken(pic):
return exposure.adjust_gamma(pic,1.3)
def edge_detect(pic):
edges = scharr(color.rgb2grey(pic))
#return edges
return to_rgb3a(edges)
def draw_line_on_picture(pic, line):
c2 = line.color
if line.sx == line.ex:
for j in range(line.sy, line.ey):
for i in range(line.sx, line.sx+line.width+1):
c1 = pic[j][i]
if len(c1) == 3:
pic[j][i] = [0.5*(c1[0]+c2[0]),0.5*(c1[1]+c2[1]),0.5*(c1[2]+c2[2])]
else:
pic[j][i] = [0.5*(c1[0]+c2[0]),0.5*(c1[1]+c2[1]),0.5*(c1[2]+c2[2]),1]
elif line.sy == line.ey:
for j in range(line.sy, line.sy+line.width+1):
for i in range(line.sx, line.ex):
c1 = pic[j][i]
c1 = pic[j][i]
if len(c1) == 3:
pic[j][i] = [0.5*(c1[0]+c2[0]),0.5*(c1[1]+c2[1]),0.5*(c1[2]+c2[2])]
else:
pic[j][i] = [0.5*(c1[0]+c2[0]),0.5*(c1[1]+c2[1]),0.5*(c1[2]+c2[2]),1]
else:
raise Exception("Non straight lines not supported")
return pic
parts = []
main_pic = None
original_pic = None
bg_pic = None
history = []
command = None
command_meta = None
colors=[[255,0,0],[0,255,0],[0,255,255]]
magenta = [255,0,255]
lines = []
lws = [3,2,1]
def get_color(idx):
return colors[idx % len(colors)]
def get_line_width(idx):
if idx<len(lws):
return lws[idx]
else:
return lws[-1]
def divide(x,y):
global parts
global main_pic
global lines
if not parts:
parts =[Rect(0,0,main_pic.shape[1], main_pic.shape[0],0)]
#import ipdb; idb.set_trace()
# find relevant part and split it in four
for i,rect in enumerate(parts):
if x>= rect.bottomx and x<rect.topx and y>=rect.bottomy and y<rect.topy:
#import ipdb; ipdb.set_trace()
mx = rect.bottomx + (rect.topx - rect.bottomx)/2
my = rect.bottomy + (rect.topy - rect.bottomy)/2
new_hierarchy = rect.hierarchy + 1
color = get_color(new_hierarchy-1)
lw = get_line_width(new_hierarchy-1)
line1 = Line(mx,rect.bottomy,mx,rect.topy, lw,color)
line2 = Line(rect.bottomx,my,rect.topx,my, lw,color)
print line1, line2
lines.append(line1)
lines.append(line2)
main_pic = draw_line_on_picture(main_pic, line1)
main_pic = draw_line_on_picture(main_pic, line2)
parts.remove(rect)
parts.append(Rect(rect.bottomx, rect.bottomy, mx,my,new_hierarchy))
parts.append(Rect(mx,my,rect.topx, rect.topy,new_hierarchy))
parts.append(Rect(rect.bottomx,my,mx, rect.topy, new_hierarchy))
parts.append(Rect(mx,rect.bottomy,rect.topx, my, new_hierarchy))
return
def onclick(event):
global G
print G["needle"]
if "active" in G["needle"] and "pt1" in G["needle"]:
G["needle"]["pt2"] = (event.xdata, event.ydata)
return
elif "active" in G["needle"]:
G["needle"]["pt1"] = (event.xdata, event.ydata)
return
G["plot_geometry"] = plt.get_current_fig_manager().window.geometry()
print event
print 'button=%d, x=%d, y=%d, xdata=%f, ydata=%f'%(
event.button, event.x, event.y, event.xdata, event.ydata)
global command
global command_meta
command="divide"
command_meta = event
plt.close('all')
#divide(event.xdata, event.ydata)
#plot()
def fileparts(fn):
path = os.path.dirname(fn)
basename = os.path.basename(fn)
name,ext = os.path.splitext(basename)
return (path,name,ext)
def save():
folder,name,ext = fileparts(filename)
i=1
while True:
newfn = os.path.join(folder,"{}_gridded{}{}".format(name,i,ext))
if not os.path.exists(newfn):
#plt.savefig(newfn, bbox_inches='tight', pad_inches=0.0)
io.imsave(newfn, main_pic)
print newfn
return
i+=1
def export_set_up():
folder,name,ext = fileparts(filename)
# 1. output the gridded file
out_folder = "{}_export".format(name)
if not os.path.exists(out_folder):
os.mkdir(out_folder)
newfn = os.path.join(out_folder,"{}_gridded{}".format(name,ext))
io.imsave(newfn, main_pic)
# 2. output the original file
io.imsave(os.path.join(out_folder,"{}{}".format(name,ext)), original_pic)
# 3. output just the grid on white
global lines
global bg_pic
for line in lines:
bg_pic = draw_line_on_picture(bg_pic, line)
io.imsave(os.path.join(out_folder,"{}_template{}".format(name,ext)), bg_pic)
def press(event):
global command
global command_meta
if event.key=="o": # o for out
# seems s is already a shortcut for matplotlib
save()
if event.key=="b":
command="brighten"
if event.key=="n":
command="needle"
if event.key=="a":
command="angle_needle"
if event.key=="p":
command="pick"
if event.key=="q":
export_set_up()
if event.key=="v":
command="vertical_line"
if event.key=="h":
command="horizontal_line"
if event.key=="d":
command="darken"
if event.key=="e":
command="edge"
if event.key=="u":
command="undo"
if event.key=="z":
command="zoom"
if event.key=="c":
command="crop"
if event.key=="r":
command="resize_patch"
if event.key=="m":
command="mirror"
if event.key in "a b d e u z c v h n r m".split(" "):
global G
# save state of plot
G["plot_geometry"] = plt.get_current_fig_manager().window.geometry()
plt.close("all")
def handle_event():
global command
global command_meta
global main_pic
global history
global patch
global patches
global click_handlers
global G
if command=="horizontal_line" or command=="vertical_line":
h,w = main_pic.shape[:2]
if patch is not None:
w1,h1 = patch.get_xy()
if command=="horizontal_line":
line = Line(0,int(h1),w,int(h1), int(patch.get_height()), magenta)
else:
line = Line(int(w1),0,int(w1),h, int(patch.get_width()), magenta)
main_pic = draw_line_on_picture(main_pic, line)
patch=None
else:
if command=="horizontal_line":
patch = Rectangle((0,0), w, 1, edgecolor='magenta', alpha=1)
else:
patch = Rectangle((0,0), 1, h, edgecolor='magenta', alpha=1)
if command=="needle" or command=="angle_needle":
G["needle"]["active"] = True
just_added_patch = False
if "pt1" in G["needle"] and "pt2" in G["needle"]:
if patch is None:
print "Drawing needle patch"
pt1 = G["needle"]["pt1"]
pt2 = G["needle"]["pt2"]
if command=="needle":
patch = Rectangle((pt1[0], pt1[1]), abs(pt2[0]-pt1[0]), abs(pt2[1]-pt1[1]), edgecolor='magenta', alpha=1, facecolor='magenta')
else:
patch = Polygon(np.array([pt1, pt2, p(pt1), p(pt2)]), closed=False,
edgecolor='magenta', alpha=1, facecolor='magenta')
angle = get_angle(pt1, pt2)
print ("Angle :{}".format(angle))
# how to add text?
just_added_patch = True
if patch is not None and not just_added_patch:
if isinstance(patch, Polygon):
patches.append(patch)
patch=None
else:
print "finalize"
w1,h1 = patch.get_xy()
w = patch.get_width()
h = patch.get_height()
if w>h:
print("horizontal patch")
line = Line(int(w1),int(h1),int(w1+w),int(h1), 3, magenta)
else:
line = Line(int(w1),int(h1),int(w1),int(h1+h), 3, magenta)
main_pic = draw_line_on_picture(main_pic, line)
G["needle"] = {}
if command == "divide":
divide(command_meta.xdata, command_meta.ydata)
if command == "brighten":
main_pic = do_brighten(main_pic)
if command == "mirror":
main_pic = np.fliplr(main_pic)
if command == "zoom":
click_handlers = not click_handlers
if command == "darken":
main_pic = do_darken(main_pic)
if command == "edge":
main_pic = edge_detect(main_pic)
if command == "resize_patch":
if patch is not None:
h = patch.get_height()
w = patch.get_width()
patch.set_width(int(w * 0.9))
patch.set_height(int(h * 0.9))
if command == "crop":
if patch is not None:
# apply patch
# crop main_pic
h = patch.get_height()
w = patch.get_width()
w1,h1 = patch.get_xy()
main_pic = main_pic[slice(h1,h1+h),slice(w1,w1+w),slice(None)]
patch=None
else:
# create patch
# TODO: can read this from settings :))
portrait_ratio = 14.8/20.8
if orientation=="portrait":
w_to_h = portrait_ratio
else:
w_to_h = 1.0/portrait_ratio
shape = main_pic.shape
border = 15
hp = shape[0] - border
wp = shape[1] - border
if w_to_h * hp >wp:
tw = wp
th = wp / w_to_h
else:
th = hp
tw = w_to_h * hp
print th,tw
patch = Rectangle((0,0), tw, th, edgecolor='magenta', alpha=1, facecolor='none')
if command == "undo":
print "Undoing"
print len(history)
if len(history)>=2:
main_pic,cmd = history[-2]
print cmd
history = history[:-1]
if command!="undo":
history.append((np.copy(main_pic),command))
if command not in ["crop","horizontal_line","vertical_line","needle","angle_needle","resize_patch"]:
patch = None
command = None
command_meta = None
plot(patch=patch, click_handlers=click_handlers)
if command is not None:
handle_event()
def drag(event):
if event.xdata is None or event.ydata is None:
return
if patch and isinstance(patch, Rectangle):
patch.set_xy((event.xdata,event.ydata))
fig.canvas.draw()
def plot(patch=None,click_handlers=True):
global fig
global ax
global G
fig = plt.figure()
ax = fig.add_subplot(111)
if click_handlers:
cid = fig.canvas.mpl_connect('button_press_event', onclick)
cid2 = fig.canvas.mpl_connect('key_press_event', press)
plt.imshow(main_pic)
if patch:
ax.add_patch(patch)
cid3 = fig.canvas.mpl_connect('motion_notify_event', drag)
for p in patches:
ax.add_patch(p)
if "plot_geometry" in G:
try:
#print("plot geom {}".format(G["plot_geometry"]))
#plt.get_current_fig_manager().window.setGeometry(G["plot_geometry"])
plt.get_current_fig_manager().window.wm_geometry(G["plot_geometry"])
except:
pass
plt.show()
def main(specified_filename, specified_orientation):
global parts
global main_pic
global bg_pic
global original_pic
global orientation
global filename
filename = specified_filename
orientation = specified_orientation
main_pic = io.imread(filename)
original_pic = io.imread(filename)
bg_pic = io.imread(filename)
bg_pic.fill(255)
print("Size {}".format(main_pic.shape))
h = main_pic.shape[0]
w = main_pic.shape[1]
if h>w:
print("Width to Height 1 to {}".format(h*1.0/w))
else:
print("Height to Width 1 to {}".format(w*1.0/h))
parts = []
handle_event()
def determine_filename(fn):
if os.path.exists(fn):
return fn
image_dir = settings[IMAGE_PATH]
path_to_try = os.path.join(image_dir, fn)
if os.path.exists(path_to_try):
return path_to_try
pretty_file_list = os.linesep.join(os.listdir(image_dir))
fn_glob ="*"+fn+"*"
matching_files = glob.glob(os.path.join(image_dir, fn_glob))
if not matching_files:
raise Exception("Could not find file in {} that matches pattern {}. Available files {} {}".format(
image_dir, fn_glob, os.linesep, pretty_file_list))
matching_files = sorted(matching_files, key=lambda x: "gridded" not in x)
return matching_files[-1]
settings = load_settings()
if __name__ == '__main__':
if len(sys.argv)<2:
print("Usage: python main.py image.png [portrait or landscape]")
sys.exit(1)
if len(sys.argv)>1:
orientation = sys.argv[1]
else:
orientation = "portrait"
fn = determine_filename(sys.argv[1])
print fn
main(fn, orientation)