-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathmain.py
More file actions
370 lines (320 loc) · 10.1 KB
/
main.py
File metadata and controls
370 lines (320 loc) · 10.1 KB
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
from tkinter import *
from tkinter import filedialog, messagebox
from PIL import ImageTk, Image
import glob
import pickle
import os
def main():
global label_dir
global image_dir
global browse_btn
global load_images_btn
global canvas
global next_btn
global back_btn
global del_btn
global save_btn
global exit_btn
root.title("Image Annotation Tool")
root.geometry("800x550")
# much buttons, such wow
label_dir.config(text="Choose a directory:", width=20, anchor='w')
image_dir.config(width=40)
browse_btn.config(text="Browse", padx=10, command=browse)
load_images_btn.config(text="Load images", padx=10, state=DISABLED)
canvas.config(width=600, height=400)
next_btn.config(text=">", width=20, state=DISABLED)
back_btn.config(text="<", width=20, state=DISABLED)
del_btn.config(text="Delete last annotation (D)", width=20, state=DISABLED)
save_btn.config(
text="Save current data (S)", width=20, state=DISABLED, command=save
)
exit_btn.config(
text="Save all and exit (Q)", width=20, state=DISABLED, command=save_and_exit
)
# display them nicely
label_dir.grid(row=0, column=0)
image_dir.grid(row=1, column=0, columnspan=2)
browse_btn.grid(row=1, column=2, sticky='w')
load_images_btn.grid(row=2, column=0, padx=(0, 48))
canvas.grid(row=3, column=0, columnspan=3, rowspan=5)
del_btn.grid(row=3, column=3)
save_btn.grid(row=4, column=3)
exit_btn.grid(row=5, column=3)
next_btn.grid(row=8, column=2)
back_btn.grid(row=8, column=0)
# mouse & keys commands
canvas.bind("<Button-1>", click)
canvas.bind("<B1-Motion>", drag)
next_btn.bind_all("<Right>", lambda event: next_btn.invoke())
back_btn.bind_all("<Left>", lambda event: back_btn.invoke())
canvas.bind_all("<s>", save)
save_btn.bind_all("<s>", lambda event: save_btn.invoke())
del_btn.bind_all("<d>", lambda event: del_btn.invoke())
exit_btn.bind_all("<q>", lambda event: exit_btn.invoke())
# create infinite loop
root.mainloop()
# browse directories
def browse():
"""
Browse folders and choose one to start annotate.
"""
image_dir.delete(0, END)
directory = filedialog.askdirectory(title="Select A Folder")
if not os.listdir(directory):
messagebox.showwarning(message="Folder is empty")
image_dir.insert(0, directory)
load_images_btn.config(command=lambda: load_images(image_dir.get()), state=NORMAL)
# load images from file to a list
def load_images(directory):
"""
Load images from folder, and display first image.
Args:
directory (string) -- directory of the folder
"""
global results
global image_list
# reset variable each time we load new images
image_list = []
images = (
glob.glob(directory + f"/*.jpg")
+ glob.glob(directory + f"/*.jfif")
+ glob.glob(directory + f"/*.png")
)
# iterate over the images, open them and create results dict
for idx, filename in enumerate(images):
image = Image.open(filename)
results[f"image{idx}"] = []
image.thumbnail((500, 500), Image.ANTIALIAS)
image = ImageTk.PhotoImage(image)
image_list.append(image)
# check for existing annotations
if os.path.exists("results.pickle"):
lines = [
"Our special state-of-the-art mega-super-scanner",
"has found existing annotations.",
"Do you want to load them?",
]
response = messagebox.askyesno("Text", "\n".join(lines))
if response == 1:
results = load_annotations()
del_btn.config(state=NORMAL)
save_btn.config(state=NORMAL)
exit_btn.config(state=NORMAL)
# check index of the last annotated image
idx = last_annotated_image()
# display images
forward(idx)
def click(event):
"""
Draw rectangle when click on the image
Args:
event -- Button-1 (left mouse button)
"""
# the last rectangle becomes blue
if len(rectangles) > 0:
canvas.itemconfig(rectangles[-1], outline="blue")
# define starting point
bounds = canvas.bbox(image_canvas)
if event.x < bounds[0]:
event.x = bounds[0]
elif event.x > bounds[2]:
event.x = bounds[2]
else:
coords["x2"] = event.x
if event.y < bounds[1]:
event.y = bounds[1]
elif event.y > bounds[3]:
event.y = bounds[3]
else:
coords["y2"] = event.y
coords["x1"] = event.x
coords["y1"] = event.y
rectangle = canvas.create_rectangle(
coords["x1"],
coords["y1"],
coords["x1"],
coords["y1"],
outline="red",
tags="rectangles",
)
# create a rectangle on this point and store it
rectangles.append(rectangle)
def drag(event):
"""
Continue drawing the rectangle when dragging the mouse on image
Args:
event -- B1-Motion
"""
# update the coordinates as the mouse moves
# restrict cursor to image area
bounds = canvas.bbox(image_canvas)
if event.x < bounds[0]:
event.x = bounds[0]
elif event.x > bounds[2]:
event.x = bounds[2]
else:
coords["x2"] = event.x
if event.y < bounds[1]:
event.y = bounds[1]
elif event.y > bounds[3]:
event.y = bounds[3]
else:
coords["y2"] = event.y
# change the coordinates of the rectangle while drawing it
canvas.coords(
rectangles[-1], coords["x1"], coords["y1"], coords["x2"], coords["y2"]
)
def release(event, idx):
"""
Finish rectangle when releasing button-1
Args:
event -- release-Button-1 (left mouse button released)
idx (int) -- index of the image for saving data
"""
# update the coordinates of the final rectangle
# restrict cursor to image area
bounds = canvas.bbox(image_canvas)
if event.x < bounds[0]:
event.x = bounds[0]
elif event.x > bounds[2]:
event.x = bounds[2]
else:
coords["x2"] = event.x
if event.y < bounds[1]:
event.y = bounds[1]
elif event.y > bounds[3]:
event.y = bounds[3]
else:
coords["y2"] = event.y
# change the coordinates of the rectangle to the final ones
canvas.coords(
rectangles[-1], coords["x1"], coords["y1"], coords["x2"], coords["y2"]
)
w = abs(coords["x2"] - coords["x1"])
h = abs(coords["y2"] - coords["y1"])
# adding current rectangle to results
results[f"image{idx}"].append([coords["x1"], coords["y1"], w, h])
def delete_last_rectangle(idx):
"""
Delete last rectangle from image
Args:
idx (int) -- image index
"""
canvas.delete(rectangles[-1])
del rectangles[-1]
del results[f"image{idx}"][-1]
def save():
"""
Save current data.
"""
with open("results.pickle", "wb") as handle:
pickle.dump(results, handle, protocol=pickle.HIGHEST_PROTOCOL)
messagebox.showinfo(message="Annotations have been saved successfully!")
def save_and_exit():
"""
Save current data and exit program.
"""
save()
messagebox.showinfo(message="Goodbye")
root.quit()
print("It works!")
def clear_canvas():
"""
Clear annotations from new image.
"""
canvas.itemconfig("rectangles", state="hidden")
def load_annotations():
"""
Load previous annotations
"""
with open("results.pickle", "rb") as handle:
prv_annotations = pickle.load(handle)
return prv_annotations
def draw_previous_annotations(idx):
"""
Draw previous annotations on current image.
Args:
idx (int) -- index of the current image
"""
annotations = results[f"image{idx}"]
for annotation in annotations:
x1 = annotation[0]
y1 = annotation[1]
x2 = annotation[0] + annotation[2]
y2 = annotation[1] + annotation[3]
canvas.create_rectangle(x1, y1, x2, y2, outline="blue", tags="rectangles")
def last_annotated_image():
"""
Check which image annotated last.
Return:
idx (int) -- index of the last annotated image.
"""
idx = 0
for i, value in reversed(list(enumerate(results.values()))):
if len(value) != 0:
idx = i
break
return idx
def forward(idx):
"""
Display the next image
Args:
idx (int) -- index of the next image
"""
canvas.itemconfig(image_canvas, image=image_list[idx])
# clear previous image's annotations
clear_canvas()
# load previous annotations if exist
draw_previous_annotations(idx)
if idx == len(image_list) - 1:
next_btn.config(state=DISABLED)
else:
next_btn.config(state=NORMAL, command=lambda: forward(idx + 1))
if idx == 0:
back_btn.config(state=DISABLED)
else:
back_btn.config(command=lambda: back(idx - 1), state=NORMAL)
del_btn.config(command=lambda: delete_last_rectangle(idx))
canvas.bind("<ButtonRelease-1>", lambda event, arg=idx: release(event, arg))
def back(idx):
"""
Display the previous image
Args:
idx (int) -- index of the previous image
"""
canvas.itemconfig(image_canvas, image=image_list[idx])
# clear previous image's annotations
clear_canvas()
# load previous annotations if exist
draw_previous_annotations(idx)
if idx == 0:
back_btn.config(state=DISABLED)
else:
back_btn.config(command=lambda: back(idx - 1))
next_btn.config(command=lambda: forward(idx + 1), state=NORMAL)
del_btn.config(command=lambda: delete_last_rectangle(idx))
canvas.bind("<ButtonRelease-1>", lambda event, arg=idx: release(event, arg))
# initialize root widget
root = Tk()
# much buttons, such wow
label_dir = Label(root)
image_dir = Entry(root)
browse_btn = Button(root)
load_images_btn = Button(root)
canvas = Canvas(root)
image_canvas = canvas.create_image(300, 200)
next_btn = Button(root)
back_btn = Button(root)
del_btn = Button(root)
save_btn = Button(root)
exit_btn = Button(root)
image_list = []
# top left point, and bottom right point of the current rectangle
coords = {"x1": 0, "y1": 0, "x2": 0, "y2": 0}
# list of the rectangles in each image
rectangles = []
# dictionary with all the data
results = {}
if __name__ == "__main__":
main()