-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathapp.py
616 lines (526 loc) · 20.2 KB
/
app.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
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
import os
import sys
import glob
import json
import time
from PyQt5.QtGui import *
from PyQt5.QtCore import *
from PyQt5.QtWidgets import *
from typing import List
from canvas import Canvas
from label_list import LabelListWidget
from file_list import FileListWidget
from tool_bar import ToolBar
import utils
import action
# IMAGE_EXTENTIONS = [
# "{}".format(fmt.data().decode("ascii").lower())
# for fmt in QImageReader.supportedImageFormats()
# ]
IMAGE_EXTENTIONS = ["jpg", "png"]
class MainWindow(QMainWindow):
def __init__(self):
super(QWidget, self).__init__()
self.setWindowTitle("My Label Tool")
self.canvas = Canvas(self)
self.dirty = False # set True indicates there exists unsaved changes
self.label_list = LabelListWidget()
self.shape_dock = QDockWidget(self.tr(u"Grasp list"), self)
self.shape_dock.setObjectName(u"Grasp list")
self.shape_dock.setWidget(self.label_list)
# connection
self.canvas.shapesAdded.connect(self.label_list.addShapes)
self.canvas.shapesRemoved.connect(self.label_list.removeShapes)
self.canvas.shapesSelectionChanged.connect(self.label_list.changeShapesSelection)
self.canvas.shapesAreaChanged.connect(self.label_list.updateShapesArea)
# self.label_list.shapesAdded.connect(self.canvas.addShapes)
self.label_list.shapesRemoved.connect(self.canvas.removeShapes)
self.label_list.shapesSelectionChanged.connect(self.canvas.changeShapesSelection)
self.label_list.shapeVisibleChanged.connect(self.canvas.changeShapesVisible)
self.label_list.shapesOrderChanged.connect(self.canvas.changeShapesOrder)
self.label_list.reconnectCanvasDataRequest.connect(self._reconnectCanvasAndLabel)
self.file_list = FileListWidget()
self.file_list.filesSelectionChanged.connect(
self._changeFilesSelection
)
self.file_list.fileLabeledChanged.connect(
self._changeFileLabeled
) # 是否完成标注
self.file_dock = QDockWidget(self.tr(u"File list"), self)
self.file_dock.setObjectName(u"File list")
self.file_dock.setWidget(self.file_list)
# set dirty
self.canvas.shapesAdded.connect(self.setDirty)
self.canvas.shapesRemoved.connect(self.setDirty)
self.canvas.shapesAreaChanged.connect(self.setDirty)
self.label_list.shapesRemoved.connect(self.setDirty)
self.label_list.shapesOrderChanged.connect(self.setDirty)
self.file_list.fileLabeledChanged.connect(self.setDirty)
# setup ui
features = QDockWidget.DockWidgetFeatures()
self.shape_dock.setFeatures(features | QDockWidget.DockWidgetFloatable | QDockWidget.DockWidgetMovable)
self.shape_dock.setVisible(True)
self.file_dock.setFeatures(features | QDockWidget.DockWidgetFloatable | QDockWidget.DockWidgetMovable)
self.file_dock.setVisible(True)
self.setCentralWidget(self.canvas)
self.addDockWidget(Qt.RightDockWidgetArea, self.file_dock)
self.addDockWidget(Qt.RightDockWidgetArea, self.shape_dock)
# project result
self.image_folder = None
self.image_files = None
self.output_folder = None
self.output_name = None
# image_file_name = os.path.join(image_folder, image_files[working_idx])
self.results = {
"image_folder": "unknown",
"image_files": {}
}
# results:
# image_folder: xxx
# image_files:
# "00001.jpg":
# "labeled": True
# "shapes":
# [
# {"id": xxx, "points": xxx},
# {"id": xxx, "points": xxx},
# ...
# ],
# "00002.jpg":
# ...
openProject = action.new_action(
self,
self.tr("Open Project"),
lambda: self.importProject(self.openProjectDialog()),
None,
"open-project.png"
)
saveProject = action.new_action(
self,
self.tr("Save Project"),
self.saveProject,
"Ctrl+S",
"save.png"
)
openImages = action.new_action(
self,
self.tr("Open Images"),
lambda: self.importImages(self.openImagesDialog()),
# lambda: self.openImagesDialog(),
None,
"open-images.png"
)
openDir = action.new_action(
self,
self.tr("Open Dir"),
lambda: self.importDirImages(self.openDirDialog()),
None,
"open-dir.png"
)
openPrevImg = action.new_action(
self,
self.tr("Prev Image"),
self.openPrevImg,
"A",
"prev.png"
)
openNextImg = action.new_action(
self,
self.tr("Next Image"),
self.openNextImg,
"D",
"next.png"
)
createMode = action.new_action(
self,
self.tr("Create Mode"),
lambda: self.canvas.setMode(self.canvas.CREATE),
"Ctrl+N",
"create.png"
)
editMode = action.new_action(
self,
self.tr("Edit Mode"),
lambda: self.canvas.setMode(self.canvas.EDIT),
"Ctrl+E",
"edit.png"
)
fitWindow = action.new_action(
self,
self.tr("Fit Window"),
lambda: self.canvas.adjustPainter("fit_window"),
None,
"fit-window.png"
)
# fitWidth = action.new_action(
# self,
# self.tr("Fit Width"),
# lambda: self.canvas.adjustPainter("fit_width"),
# None,
# "fit-width.png"
# )
#
# fitHeight = action.new_action(
# self,
# self.tr("Fit Height"),
# lambda: self.canvas.adjustPainter("fit_height"),
# None,
# "fit-height.png"
# )
fitOrigin = action.new_action(
self,
self.tr("Origin Size"),
lambda: self.canvas.adjustPainter("origin_size"),
None,
"origin-size.png"
)
changeOutputDir = action.new_action(
self,
self.tr("Change Output Dir"),
self.changeOutputDir,
None,
"open-dir.png"
)
self.actions = utils.Struct(
openPrevImg=openPrevImg,
openNextImg=openNextImg
)
self.tool_bar = self.addToolBar_(
"Tools",
[
openProject,
# openImages,
openDir,
openPrevImg,
openNextImg,
saveProject,
createMode,
editMode,
fitWindow,
# fitHeight,
# fitWidth,
fitOrigin
]
)
self.menus = utils.Struct(
file=self.addMenu(self.tr("File")),
edit=self.addMenu(self.tr("Edit")),
view=self.addMenu(self.tr("View"))
)
action.add_actions(
self.menus.file,
[
openProject,
openImages,
openDir,
None,
saveProject,
changeOutputDir
]
)
action.add_actions(
self.menus.edit,
[
createMode,
editMode
]
)
action.add_actions(
self.menus.view,
[
fitWindow,
# fitHeight,
# fitWidth,
fitOrigin
]
)
def _reconnectCanvasAndLabel(self):
self.label_list.reconnectCanvasData(self.canvas.shapes)
def _changeFilesSelection(self, selected, deselected):
assert len(selected) <= 1, "Single selection mode"
assert len(deselected) <= 1, "Single selection mode"
if len(deselected):
# save current work
print("[INFO] [from_app] Saving current work...")
current_file = self.image_files[deselected[0]]
self.results["image_files"][current_file]["shapes"] = self.canvas.exportShapes()
if len(selected):
# load new file
current_file = self.image_files[selected[0]]
print("[INFO] [from_app] Loading data for image {}...".format(current_file))
if current_file not in self.results["image_files"]:
self.canvas.clear()
else:
self.canvas.loadShapes(self.results["image_files"][current_file]["shapes"])
if self.image_folder is not None: # relative path
self.canvas.loadImage(os.path.join(self.image_folder, current_file))
else: # absolute path
self.canvas.loadImage(current_file)
self.setClean()
def _changeFileLabeled(self, index: int, labeled: bool):
file = self.image_files[index]
self.results["image_files"][file]["labeled"] = labeled
def setDirty(self):
self.dirty = True
def setClean(self):
self.dirty = False
def isDirty(self):
return self.dirty
def addMenu(self, title, actions=None):
menu = self.menuBar().addMenu(title)
if actions:
action.add_actions(menu, actions)
return menu
def addToolBar_(self, title, actions=None):
tool_bar = ToolBar(title)
tool_bar.setObjectName("{}ToolBar".format(title))
tool_bar.setOrientation(Qt.Vertical)
tool_bar.setToolButtonStyle(Qt.ToolButtonTextUnderIcon)
if actions:
action.add_actions(tool_bar, actions)
self.addToolBar(Qt.LeftToolBarArea, tool_bar)
return tool_bar
def openProjectDialog(self):
path = QFileDialog.getOpenFileName(
self,
self.tr("Open Project"),
"./",
self.tr("Project File (*.json)")
)[0]
return path
def openImagesDialog(self):
paths = QFileDialog.getOpenFileNames(
self,
self.tr("Open Images"),
"./",
self.tr("Image Files ({})"
.format(" ".join(["*." + ext for ext in IMAGE_EXTENTIONS])))
)[0]
return paths
def openDirDialog(self):
path = QFileDialog.getExistingDirectory(
self,
self.tr("Open Directory"),
"./",
# QFileDialog.ShowDirsOnly | QFileDialog.DontResolveSymlinks
# QFileDialog.DontUseNativeDialog | QFileDialog.DontResolveSymlinks
# QFileDialog.DontResolveSymlinks
QFileDialog.ShowDirsOnly
)
if len(path) == 0:
path = None
print("[INFO] [from app] Choose dir = {}".format(path))
return path
def importProject(self, path: str):
if not path:
return
# clean the current content
self.file_list.clear()
self.canvas.clear()
with open(path, "r", encoding="utf-8") as j:
self.results = json.load(j)
self.image_folder = self.results["image_folder"].lower() \
if self.results["image_folder"].lower() != "absolute_path" \
else None
self.image_files = list(self.results["image_files"].keys())
self.image_files.sort()
# check if file exists
if self.image_folder is None: # absolute path
found, not_found = [], []
for file in self.image_files:
if os.path.exists(file):
found.append(file)
else:
not_found.append(file)
self.image_files = found
if len(not_found):
box = QMessageBox(self)
box.setIcon(QMessageBox.Warning)
box.setText("{} file(s) cannot be found.".format(len(not_found)))
box.setInformativeText("Do you want the project to keep them?")
box.setStandardButtons(QMessageBox.Yes | QMessageBox.No)
box.setDefaultButton(QMessageBox.No)
box.setDetailedText(
"The following file(s) cannot be found:\n\n" +
"\n".join([" - " + f for f in not_found])
)
ret = box.exec()
if ret == QMessageBox.No:
for f in not_found:
self.results["image_files"].pop(f)
else: # relative path
if not os.path.exists(self.image_folder):
box = QMessageBox(self)
box.setIcon(QMessageBox.Critical)
box.setText("Directory not found. Import project failed.")
box.setInformativeText("Select directory: {}".format(self.image_folder))
box.setStandardButtons(QMessageBox.Ok)
box.setDefaultButton(QMessageBox.Ok)
box.exec()
return
else:
found, not_found = [], []
for file in self.image_files:
if os.path.exists(os.path.join(self.image_folder, file)):
found.append(file)
else:
not_found.append(file)
self.image_files = found
if len(not_found):
box = QMessageBox(self)
box.setIcon(QMessageBox.Warning)
box.setText("{} file(s) in directory \"{}\" cannot be found."
.format(len(not_found), self.image_folder))
box.setInformativeText("Do you want the project to keep them?")
box.setStandardButtons(QMessageBox.Yes | QMessageBox.No)
box.setDefaultButton(QMessageBox.No)
box.setDetailedText(
"The following file(s) cannot be found:\n\n" +
"\n".join([" - " + f for f in not_found])
)
ret = box.exec()
if ret == QMessageBox.No:
for f in not_found:
self.results["image_files"].pop(f)
self.file_list.addFiles(self.image_files)
for i, file in enumerate(self.image_files):
self.file_list[i].setCheckState(Qt.Checked if self.results["image_files"][file]["labeled"]
else Qt.Unchecked)
self.file_list.selectNext()
box = QMessageBox(self)
box.setIcon(QMessageBox.Question)
box.setText("Continue working on this opened project?")
box.setInformativeText("If not, you may have to choose another output path"
" when you save the project.")
box.setStandardButtons(QMessageBox.Yes | QMessageBox.No)
box.setDefaultButton(QMessageBox.Yes)
ret = box.exec()
if ret == QMessageBox.Yes:
self.output_folder, self.output_name = os.path.split(path)
if self.output_folder == "":
self.output_folder = "."
self.setClean()
else:
self.setDirty()
def importImages(self, paths: List[str]):
if len(paths) == 0:
return
# clean the current content
self.file_list.clear()
self.canvas.clear()
self.image_folder = None
self.image_files = paths
self.image_files.sort()
self.file_list.addFiles(self.image_files)
self.results = {
"image_folder": "absolute_path",
"image_files": {
f: {
"labeled": False,
"shapes": []
} for f in self.image_files
}
}
self.file_list.selectNext()
self.setDirty()
def importDirImages(self, path: str):
if not path:
return
# clean the current content
self.file_list.clear()
self.canvas.clear()
# self.label_list.clear()
# label_list will automatically clear since its .removeShapes()
# has been connected to canvas' .removeShapes()
# load new files
self.image_folder = path
self.image_files = []
for ext in IMAGE_EXTENTIONS: # ["jpg", "png"]
self.image_files.extend(glob.glob(os.path.join(
self.image_folder,
"*.{}".format(ext)
)))
self.image_files = [os.path.split(f)[-1] for f in self.image_files] # remove dir
self.image_files.sort()
self.file_list.addFiles(self.image_files)
self.results = {
"image_folder": path,
"image_files": {
f: {
"labeled": False,
"shapes": []
} for f in self.image_files
}
}
self.file_list.selectNext()
self.setDirty()
def openNextImg(self):
print("[INFO] Open next image triggered.")
current_select, next_select = self.file_list.selectNext()
# self.changeFilesSelection() will be triggered to process canvas.
if current_select is not None:
self.file_list[current_select].setCheckState(Qt.Checked)
# may trigger setDirty() if check state changes
def openPrevImg(self):
print("[INFO] Open previous image triggered.")
current_select, prev_select = self.file_list.selectPrev()
# self._changeFilesSelection() will be triggered to process canvas.
if current_select is not None:
self.file_list[current_select].setCheckState(Qt.Checked)
def saveProject(self):
print("[INFO] [from app] Saving current work...")
selected = [i.row() for i in self.file_list.selectedIndexes()]
assert len(selected) <= 1, "Single selection mode."
if len(selected):
current_file = self.image_files[selected[0]]
self.results["image_files"][current_file]["shapes"] = self.canvas.exportShapes()
self.file_list[selected[0]].setCheckState(Qt.Checked)
if self.output_folder is None:
self.output_folder = self.openDirDialog()
if self.output_folder is None:
return None # cancel saving if None selected
time_stamp = time.strftime("%m%d%H%M%S", time.localtime())
self.output_name = "proj_" + time_stamp + ".json"
path = os.path.join(self.output_folder, self.output_name)
print("[INFO] [from app] Saving project to {}...".format(path))
with open(path, "w", encoding="utf-8") as j:
json.dump(self.results, j, ensure_ascii=False, indent=4)
self.setClean() # set clean, no unsaved changes
return path
def changeOutputDir(self):
self.output_folder = self.openDirDialog()
return self.output_folder
def resizeEvent(self, e: QResizeEvent):
super(MainWindow, self).resizeEvent(e)
self.canvas.adjustPainter("fit_window")
def closeEvent(self, e: QCloseEvent):
if not self.dirty: # no unsaved changes
e.accept()
else:
box = QMessageBox(self)
box.setIcon(QMessageBox.Question)
box.setText("Save before closing? Or press cancel to back to canvas.")
box.setStandardButtons(QMessageBox.Yes | QMessageBox.No | QMessageBox.Cancel)
box.setDefaultButton(QMessageBox.Yes)
ret = box.exec()
if ret == QMessageBox.Yes:
out_path = self.saveProject()
if out_path is None:
box = QMessageBox(self)
box.setIcon(QMessageBox.Information)
box.setText("Saving project canceled. Will go back to canvas.")
box.setStandardButtons(QMessageBox.Ok)
box.setDefaultButton(QMessageBox.Ok)
box.exec()
e.ignore()
else:
e.accept()
elif ret == QMessageBox.No:
e.accept()
else:
e.ignore()
if __name__ == '__main__':
app = QApplication(sys.argv)
window = MainWindow()
window.show()
app.exec()