forked from Baidu-AIP/Easyyibiao
-
Notifications
You must be signed in to change notification settings - Fork 0
/
app.py
2052 lines (1841 loc) · 71 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
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
# -*- coding: utf-8 -*-
import functools
import math
import os
import os.path as osp
import re
import webbrowser
import imgviz
from qtpy import QtCore
from qtpy.QtCore import Qt
from qtpy import QtGui
from qtpy import QtWidgets
from conf import __appname__
from conf import PY2
from conf import QT5
import utils
from config import get_config
from label_file import LabelFile
from label_file import LabelFileError
from logger import logger
from shape import Shape
from widgets import BrightnessContrastDialog
from widgets import Canvas
from widgets import LabelDialog
from widgets import LabelListWidget
from widgets import LabelListWidgetItem
from widgets import ToolBar
from widgets import UniqueLabelQListWidget
from widgets import ZoomWidget
# from subWin.login.login_action import LoginWindow
# from subWin.show_dataset_list.show_dataset_list_action import SelectDataset
# from subWin.database.operation import SqLite
from export.export.export_widget_action import ExportWindow
# FIXME
# - [medium] Set max zoom value to something big enough for FitWidth/Window
# TODO(unknown):
# - [high] Add polygon movement with arrow keys
# - [high] Deselect shape when clicking and already selected(?)
# - [low,maybe] Preview images on file dialogs.
# - Zoom is too "steppy".
LABEL_COLORMAP = imgviz.label_colormap(value=200)
class MainWindow(QtWidgets.QMainWindow):
FIT_WINDOW, FIT_WIDTH, MANUAL_ZOOM = 0, 1, 2
def __init__(
self,
config=None,
filename=None,
output=None,
output_file=None,
output_dir=None,
):
if output is not None:
logger.warning(
"argument output is deprecated, use output_file instead"
)
if output_file is None:
output_file = output
# see labelme/config/default_config.yaml for valid configuration
if config is None:
config = get_config()
self._config = config
# set default shape colors
Shape.line_color = QtGui.QColor(*self._config["shape"]["line_color"])
Shape.fill_color = QtGui.QColor(*self._config["shape"]["fill_color"])
Shape.select_line_color = QtGui.QColor(
*self._config["shape"]["select_line_color"]
)
Shape.select_fill_color = QtGui.QColor(
*self._config["shape"]["select_fill_color"]
)
Shape.vertex_fill_color = QtGui.QColor(
*self._config["shape"]["vertex_fill_color"]
)
Shape.hvertex_fill_color = QtGui.QColor(
*self._config["shape"]["hvertex_fill_color"]
)
super(MainWindow, self).__init__()
self.setWindowTitle(__appname__)
# Whether we need to save or not.
self.dirty = False
self._noSelectionSlot = False
# Main widgets and related state.
self.labelDialog = LabelDialog(
parent=self,
labels=self._config["labels"],
sort_labels=self._config["sort_labels"],
show_text_field=self._config["show_label_text_field"],
completion=self._config["label_completion"],
fit_to_content=self._config["fit_to_content"],
flags=self._config["label_flags"],
)
self.labelList = LabelListWidget()
self.lastOpenDir = None
self.flag_dock = self.flag_widget = None
self.flag_dock = QtWidgets.QDockWidget(self.tr("Flags"), self)
self.flag_dock.setObjectName("Flags")
self.flag_widget = QtWidgets.QListWidget()
if config["flags"]:
self.loadFlags({k: False for k in config["flags"]})
self.flag_dock.setWidget(self.flag_widget)
self.flag_widget.itemChanged.connect(self.setDirty)
self.labelList.itemSelectionChanged.connect(self.labelSelectionChanged)
self.labelList.itemDoubleClicked.connect(self.editLabel)
self.labelList.itemChanged.connect(self.labelItemChanged)
self.labelList.itemDropped.connect(self.labelOrderChanged)
self.shape_dock = QtWidgets.QDockWidget(
self.tr("Polygon Labels"), self
)
self.shape_dock.setObjectName("Labels")
self.shape_dock.setWidget(self.labelList)
self.uniqLabelList = UniqueLabelQListWidget()
self.uniqLabelList.setToolTip(
self.tr(
"Select label to start annotating for it. "
"Press 'Esc' to deselect."
)
)
if self._config["labels"]:
for label in self._config["labels"]:
item = self.uniqLabelList.createItemFromLabel(label)
self.uniqLabelList.addItem(item)
rgb = self._get_rgb_by_label(label)
self.uniqLabelList.setItemLabel(item, label, rgb)
self.label_dock = QtWidgets.QDockWidget(self.tr(u"Label List"), self)
self.label_dock.setObjectName(u"Label List")
self.label_dock.setWidget(self.uniqLabelList)
self.fileSearch = QtWidgets.QLineEdit()
self.fileSearch.setPlaceholderText(self.tr("Search Filename"))
self.fileSearch.textChanged.connect(self.fileSearchChanged)
self.fileListWidget = QtWidgets.QListWidget()
self.fileListWidget.itemSelectionChanged.connect(
self.fileSelectionChanged
)
fileListLayout = QtWidgets.QVBoxLayout()
fileListLayout.setContentsMargins(0, 0, 0, 0)
fileListLayout.setSpacing(0)
fileListLayout.addWidget(self.fileSearch)
fileListLayout.addWidget(self.fileListWidget)
self.file_dock = QtWidgets.QDockWidget(self.tr(u"File List"), self)
self.file_dock.setObjectName(u"Files")
fileListWidget = QtWidgets.QWidget()
fileListWidget.setLayout(fileListLayout)
self.file_dock.setWidget(fileListWidget)
self.zoomWidget = ZoomWidget()
self.setAcceptDrops(True)
self.canvas = self.labelList.canvas = Canvas(
epsilon=self._config["epsilon"],
double_click=self._config["canvas"]["double_click"],
)
self.canvas.zoomRequest.connect(self.zoomRequest)
scrollArea = QtWidgets.QScrollArea()
scrollArea.setWidget(self.canvas)
scrollArea.setWidgetResizable(True)
self.scrollBars = {
Qt.Vertical: scrollArea.verticalScrollBar(),
Qt.Horizontal: scrollArea.horizontalScrollBar(),
}
self.canvas.scrollRequest.connect(self.scrollRequest)
self.canvas.newShape.connect(self.newShape)
self.canvas.shapeMoved.connect(self.setDirty)
self.canvas.selectionChanged.connect(self.shapeSelectionChanged)
self.canvas.drawingPolygon.connect(self.toggleDrawingSensitive)
self.setCentralWidget(scrollArea)
features = QtWidgets.QDockWidget.DockWidgetFeatures()
for dock in ["flag_dock", "label_dock", "shape_dock", "file_dock"]:
if self._config[dock]["closable"]:
features = features | QtWidgets.QDockWidget.DockWidgetClosable
if self._config[dock]["floatable"]:
features = features | QtWidgets.QDockWidget.DockWidgetFloatable
if self._config[dock]["movable"]:
features = features | QtWidgets.QDockWidget.DockWidgetMovable
getattr(self, dock).setFeatures(features)
if self._config[dock]["show"] is False:
getattr(self, dock).setVisible(False)
self.addDockWidget(Qt.RightDockWidgetArea, self.flag_dock)
self.addDockWidget(Qt.RightDockWidgetArea, self.label_dock)
self.addDockWidget(Qt.RightDockWidgetArea, self.shape_dock)
self.addDockWidget(Qt.RightDockWidgetArea, self.file_dock)
# Actions
action = functools.partial(utils.newAction, self)
shortcuts = self._config["shortcuts"]
quit = action(
self.tr("&Quit"),
self.close,
shortcuts["quit"],
"quit",
self.tr("Quit application"),
)
open_ = action(
self.tr("&Open"),
self.openFile,
shortcuts["open"],
"open",
self.tr("Open image or label file"),
)
opendir = action(
self.tr("&Open Dir"),
self.openDirDialog,
shortcuts["open_dir"],
"open",
self.tr(u"Open Dir"),
)
openNextImg = action(
self.tr("&Next Image"),
self.openNextImg,
shortcuts["open_next"],
"next",
self.tr(u"Open next (hold Ctl+Shift to copy labels)"),
enabled=False,
)
openPrevImg = action(
self.tr("&Prev Image"),
self.openPrevImg,
shortcuts["open_prev"],
"prev",
self.tr(u"Open prev (hold Ctl+Shift to copy labels)"),
enabled=False,
)
save = action(
self.tr("&Save"),
self.saveFile,
shortcuts["save"],
"save",
self.tr("Save labels to file"),
enabled=False,
)
saveAs = action(
self.tr("&Save As"),
self.saveFileAs,
shortcuts["save_as"],
"save-as",
self.tr("Save labels to a different file"),
enabled=False,
)
deleteFile = action(
self.tr("&Delete File"),
self.deleteFile,
shortcuts["delete_file"],
"delete",
self.tr("Delete current label file"),
enabled=False,
)
exportToEasyData = action(
self.tr("&导出到 EasyData"),
self.exportToEasyData,
shortcuts["export_to_easydata"],
"to-data",
# "labelme-Data",
self.tr(u"Export labeled data to EasyData"),
enabled=False
)
changeOutputDir = action(
self.tr("&Change Output Dir"),
slot=self.changeOutputDirDialog,
shortcut=shortcuts["save_to"],
icon="open",
tip=self.tr(u"Change where annotations are loaded/saved"),
)
saveAuto = action(
text=self.tr("Save &Automatically"),
slot=lambda x: self.actions.saveAuto.setChecked(x),
icon="save",
tip=self.tr("Save automatically"),
checkable=True,
enabled=True,
)
saveAuto.setChecked(self._config["auto_save"])
saveWithImageData = action(
# text="Save With Image Data",
text="保存图像数据",
slot=self.enableSaveImageWithData,
tip="Save image data in label file",
checkable=True,
checked=self._config["store_data"],
)
close = action(
# "&Close",
"&关闭",
self.closeFile,
shortcuts["close"],
"close",
"Close current file",
)
toggle_keep_prev_mode = action(
self.tr("Keep Previous Annotation"),
self.toggleKeepPrevMode,
shortcuts["toggle_keep_prev_mode"],
None,
self.tr('Toggle "keep pevious annotation" mode'),
checkable=True,
)
toggle_keep_prev_mode.setChecked(self._config["keep_prev"])
createMode = action(
self.tr("Create Polygons"),
lambda: self.toggleDrawMode(False, createMode="polygon"),
shortcuts["create_polygon"],
"objects",
self.tr("Start drawing polygons"),
enabled=False,
)
createRectangleMode = action(
self.tr("Create Rectangle"),
lambda: self.toggleDrawMode(False, createMode="rectangle"),
shortcuts["create_rectangle"],
"objects",
self.tr("Start drawing rectangles"),
enabled=False,
)
createCircleMode = action(
self.tr("Create Circle"),
lambda: self.toggleDrawMode(False, createMode="circle"),
shortcuts["create_circle"],
"objects",
self.tr("Start drawing circles"),
enabled=False,
)
createLineMode = action(
self.tr("Create Line"),
lambda: self.toggleDrawMode(False, createMode="line"),
shortcuts["create_line"],
"objects",
self.tr("Start drawing lines"),
enabled=False,
)
createPointMode = action(
self.tr("Create Point"),
lambda: self.toggleDrawMode(False, createMode="point"),
shortcuts["create_point"],
"objects",
self.tr("Start drawing points"),
enabled=False,
)
createLineStripMode = action(
self.tr("Create LineStrip"),
lambda: self.toggleDrawMode(False, createMode="linestrip"),
shortcuts["create_linestrip"],
"objects",
self.tr("Start drawing linestrip. Ctrl+LeftClick ends creation."),
enabled=False,
)
editMode = action(
self.tr("Edit Polygons"),
# self.tr("Edit Rectangle"),
self.setEditMode,
shortcuts["edit_polygon"],
"edit",
self.tr("Move and edit the selected polygons"),
enabled=False,
)
delete = action(
self.tr("Delete Polygons"),
# self.tr("Delete Rectangle"),
self.deleteSelectedShape,
shortcuts["delete_polygon"],
"cancel",
self.tr("Delete the selected polygons"),
enabled=False,
)
copy = action(
self.tr("Duplicate Polygons"),
# self.tr("Duplicate Rectangle"),
self.copySelectedShape,
shortcuts["duplicate_polygon"],
"copy",
self.tr("Create a duplicate of the selected polygons"),
enabled=False,
)
undoLastPoint = action(
self.tr("Undo last point"),
self.canvas.undoLastPoint,
shortcuts["undo_last_point"],
"undo",
self.tr("Undo last drawn point"),
enabled=False,
)
addPointToEdge = action(
text=self.tr("Add Point to Edge"),
slot=self.canvas.addPointToEdge,
shortcut=shortcuts["add_point_to_edge"],
icon="edit",
tip=self.tr("Add point to the nearest edge"),
enabled=False,
)
removePoint = action(
text="Remove Selected Point",
slot=self.canvas.removeSelectedPoint,
icon="edit",
tip="Remove selected point from polygon",
enabled=False,
)
undo = action(
self.tr("Undo"),
self.undoShapeEdit,
shortcuts["undo"],
"undo",
self.tr("Undo last add and edit of shape"),
enabled=False,
)
hideAll = action(
self.tr("&Hide\nPolygons"),
functools.partial(self.togglePolygons, False),
icon="eye",
tip=self.tr("Hide all polygons"),
enabled=False,
)
showAll = action(
self.tr("&Show\nPolygons"),
functools.partial(self.togglePolygons, True),
icon="eye",
tip=self.tr("Show all polygons"),
enabled=False,
)
help = action(
self.tr("&Tutorial"),
self.tutorial,
icon="help",
tip=self.tr("Show tutorial page"),
)
zoom = QtWidgets.QWidgetAction(self)
zoom.setDefaultWidget(self.zoomWidget)
self.zoomWidget.setWhatsThis(
self.tr(
"Zoom in or out of the image. Also accessible with "
"{} and {} from the canvas."
).format(
utils.fmtShortcut(
"{},{}".format(shortcuts["zoom_in"], shortcuts["zoom_out"])
),
utils.fmtShortcut(self.tr("Ctrl+Wheel")),
)
)
self.zoomWidget.setEnabled(False)
zoomIn = action(
self.tr("Zoom &In"),
functools.partial(self.addZoom, 1.1),
shortcuts["zoom_in"],
"zoom-in",
self.tr("Increase zoom level"),
enabled=False,
)
zoomOut = action(
self.tr("&Zoom Out"),
functools.partial(self.addZoom, 0.9),
shortcuts["zoom_out"],
"zoom-out",
self.tr("Decrease zoom level"),
enabled=False,
)
zoomOrg = action(
self.tr("&Original size"),
functools.partial(self.setZoom, 100),
shortcuts["zoom_to_original"],
"zoom",
self.tr("Zoom to original size"),
enabled=False,
)
fitWindow = action(
self.tr("&Fit Window"),
self.setFitWindow,
shortcuts["fit_window"],
"fit-window",
self.tr("Zoom follows window size"),
checkable=True,
enabled=False,
)
fitWidth = action(
self.tr("Fit &Width"),
self.setFitWidth,
shortcuts["fit_width"],
"fit-width",
self.tr("Zoom follows window width"),
checkable=True,
enabled=False,
)
brightnessContrast = action(
# "&Brightness Contrast",
"&亮度 对比度",
self.brightnessContrast,
None,
"color",
"Adjust brightness and contrast",
enabled=False,
)
# Group zoom controls into a list for easier toggling.
zoomActions = (
self.zoomWidget,
zoomIn,
zoomOut,
zoomOrg,
fitWindow,
fitWidth,
)
self.zoomMode = self.FIT_WINDOW
fitWindow.setChecked(Qt.Checked)
self.scalers = {
self.FIT_WINDOW: self.scaleFitWindow,
self.FIT_WIDTH: self.scaleFitWidth,
# Set to one to scale to 100% when loading files.
self.MANUAL_ZOOM: lambda: 1,
}
edit = action(
self.tr("&Edit Label"),
self.editLabel,
shortcuts["edit_label"],
"edit",
self.tr("Modify the label of the selected polygon"),
enabled=False,
)
fill_drawing = action(
self.tr("Fill Drawing Polygon"),
self.canvas.setFillDrawing,
None,
"color",
self.tr("Fill polygon while drawing"),
checkable=True,
enabled=True,
)
fill_drawing.trigger()
# Lavel list context menu.
labelMenu = QtWidgets.QMenu()
utils.addActions(labelMenu, (edit, delete))
self.labelList.setContextMenuPolicy(Qt.CustomContextMenu)
self.labelList.customContextMenuRequested.connect(
self.popLabelListMenu
)
# Store actions for further handling.
self.actions = utils.struct(
saveAuto=saveAuto,
saveWithImageData=saveWithImageData,
changeOutputDir=changeOutputDir,
save=save,
saveAs=saveAs,
open=open_,
close=close,
deleteFile=deleteFile,
exportToEasyData=exportToEasyData,
toggleKeepPrevMode=toggle_keep_prev_mode,
delete=delete,
edit=edit,
copy=copy,
undoLastPoint=undoLastPoint,
undo=undo,
addPointToEdge=addPointToEdge,
removePoint=removePoint,
createMode=createMode,
editMode=editMode,
createRectangleMode=createRectangleMode,
createCircleMode=createCircleMode,
createLineMode=createLineMode,
createPointMode=createPointMode,
createLineStripMode=createLineStripMode,
zoom=zoom,
zoomIn=zoomIn,
zoomOut=zoomOut,
zoomOrg=zoomOrg,
fitWindow=fitWindow,
fitWidth=fitWidth,
brightnessContrast=brightnessContrast,
zoomActions=zoomActions,
openNextImg=openNextImg,
openPrevImg=openPrevImg,
fileMenuActions=(open_, opendir, save, saveAs, close, quit),
# fileMenuActions=(opendir, save, saveAs, close, quit),
tool=(),
# XXX: need to add some actions here to activate the shortcut
editMenu=(
edit,
copy,
delete,
None,
undo,
undoLastPoint,
None,
addPointToEdge,
None,
toggle_keep_prev_mode,
),
# menu shown at right click
menu=(
# createMode,
createRectangleMode,
# createCircleMode,
# createLineMode,
# createPointMode,
# createLineStripMode,
editMode,
edit,
copy,
delete,
undo,
undoLastPoint,
addPointToEdge,
removePoint,
),
onLoadActive=(
close,
createMode,
createRectangleMode,
createCircleMode,
createLineMode,
createPointMode,
createLineStripMode,
editMode,
brightnessContrast,
),
onShapesPresent=(saveAs, hideAll, showAll),
)
self.canvas.edgeSelected.connect(self.canvasShapeEdgeSelected)
self.canvas.vertexSelected.connect(self.actions.removePoint.setEnabled)
self.menus = utils.struct(
file=self.menu(self.tr("&File")),
edit=self.menu(self.tr("&Edit")),
view=self.menu(self.tr("&View")),
help=self.menu(self.tr("&Help")),
recentFiles=QtWidgets.QMenu(self.tr("Open &Recent")),
labelList=labelMenu,
)
utils.addActions(
self.menus.file,
(
open_,
openNextImg,
openPrevImg,
opendir,
self.menus.recentFiles,
save,
saveAs,
saveAuto,
changeOutputDir,
saveWithImageData,
close,
deleteFile,
exportToEasyData,
None,
quit,
),
)
utils.addActions(self.menus.help, (help,))
utils.addActions(
self.menus.view,
(
self.flag_dock.toggleViewAction(),
self.label_dock.toggleViewAction(),
self.shape_dock.toggleViewAction(),
self.file_dock.toggleViewAction(),
None,
fill_drawing,
None,
hideAll,
showAll,
None,
zoomIn,
zoomOut,
zoomOrg,
None,
fitWindow,
fitWidth,
None,
brightnessContrast,
),
)
self.menus.file.aboutToShow.connect(self.updateFileMenu)
# Custom context menu for the canvas widget:
utils.addActions(self.canvas.menus[0], self.actions.menu)
utils.addActions(
self.canvas.menus[1],
(
action("&Copy here", self.copyShape),
action("&Move here", self.moveShape),
),
)
self.tools = self.toolbar("Tools")
# Menu buttons on Left
self.actions.tool = (
# open_,
opendir,
openNextImg,
openPrevImg,
save,
deleteFile,
exportToEasyData,
None,
# createMode,
createRectangleMode,
editMode,
copy,
delete,
undo,
brightnessContrast,
None,
zoom,
fitWidth,
)
self.statusBar().showMessage(self.tr("%s started.") % __appname__)
self.statusBar().show()
if output_file is not None and self._config["auto_save"]:
logger.warn(
"If `auto_save` argument is True, `output_file` argument "
"is ignored and output filename is automatically "
"set as IMAGE_BASENAME.json."
)
self.output_file = output_file
self.output_dir = output_dir
# Application state.
self.image = QtGui.QImage()
self.imagePath = None
self.recentFiles = []
self.maxRecent = 7
self.otherData = None
self.zoom_level = 100
self.fit_window = False
self.zoom_values = {} # key=filename, value=(zoom_mode, zoom_value)
self.brightnessContrast_values = {}
self.scroll_values = {
Qt.Horizontal: {},
Qt.Vertical: {},
} # key=filename, value=scroll_value
if filename is not None and osp.isdir(filename):
self.importDirImages(filename, load=False)
else:
self.filename = filename
if config["file_search"]:
self.fileSearch.setText(config["file_search"])
self.fileSearchChanged()
# XXX: Could be completely declarative.
# Restore application settings.
self.settings = QtCore.QSettings("labelme", "labelme")
# FIXME: QSettings.value can return None on PyQt4
self.recentFiles = self.settings.value("recentFiles", []) or []
size = self.settings.value("window/size", QtCore.QSize(600, 500))
position = self.settings.value("window/position", QtCore.QPoint(0, 0))
self.resize(size)
self.move(position)
# or simply:
# self.restoreGeometry(settings['window/geometry']
self.restoreState(
self.settings.value("window/state", QtCore.QByteArray())
)
# Populate the File menu dynamically.
self.updateFileMenu()
# Since loading the file may take some time,
# make sure it runs in the background.
if self.filename is not None:
self.queueEvent(functools.partial(self.loadFile, self.filename))
# Callbacks:
self.zoomWidget.valueChanged.connect(self.paintCanvas)
self.populateModeActions()
# self.firstStart = True
# if self.firstStart:
# QWhatsThis.enterWhatsThisMode()
def menu(self, title, actions=None):
menu = self.menuBar().addMenu(title)
if actions:
utils.addActions(menu, actions)
return menu
def toolbar(self, title, actions=None):
toolbar = ToolBar(title)
toolbar.setObjectName("%sToolBar" % title)
# toolbar.setOrientation(Qt.Vertical)
toolbar.setToolButtonStyle(Qt.ToolButtonTextUnderIcon)
if actions:
utils.addActions(toolbar, actions)
self.addToolBar(Qt.LeftToolBarArea, toolbar)
return toolbar
# Support Functions
def noShapes(self):
return not len(self.labelList)
def populateModeActions(self):
tool, menu = self.actions.tool, self.actions.menu
self.tools.clear()
utils.addActions(self.tools, tool)
self.canvas.menus[0].clear()
utils.addActions(self.canvas.menus[0], menu)
self.menus.edit.clear()
actions = (
# self.actions.createMode,
self.actions.createRectangleMode,
# self.actions.createCircleMode,
# self.actions.createLineMode,
# self.actions.createPointMode,
# self.actions.createLineStripMode,
self.actions.editMode,
)
utils.addActions(self.menus.edit, actions + self.actions.editMenu)
def setDirty(self):
if self._config["auto_save"] or self.actions.saveAuto.isChecked():
label_file = osp.splitext(self.imagePath)[0] + ".json"
if self.output_dir:
label_file_without_path = osp.basename(label_file)
label_file = osp.join(self.output_dir, label_file_without_path)
self.saveLabels(label_file)
return
self.dirty = True
self.actions.save.setEnabled(True)
self.actions.undo.setEnabled(self.canvas.isShapeRestorable)
title = __appname__
if self.filename is not None:
title = "{} - {}*".format(title, self.filename)
self.setWindowTitle(title)
def setClean(self):
self.dirty = False
self.actions.save.setEnabled(False)
self.actions.createMode.setEnabled(True)
self.actions.createRectangleMode.setEnabled(True)
self.actions.createCircleMode.setEnabled(True)
self.actions.createLineMode.setEnabled(True)
self.actions.createPointMode.setEnabled(True)
self.actions.createLineStripMode.setEnabled(True)
title = __appname__
if self.filename is not None:
title = "{} - {}".format(title, self.filename)
self.setWindowTitle(title)
if self.hasLabelFile():
self.actions.deleteFile.setEnabled(True)
else:
self.actions.deleteFile.setEnabled(False)
def toggleActions(self, value=True):
"""Enable/Disable widgets which depend on an opened image."""
for z in self.actions.zoomActions:
z.setEnabled(value)
for action in self.actions.onLoadActive:
action.setEnabled(value)
def canvasShapeEdgeSelected(self, selected, shape):
self.actions.addPointToEdge.setEnabled(
selected and shape and shape.canAddPoint()
)
def queueEvent(self, function):
QtCore.QTimer.singleShot(0, function)
def status(self, message, delay=5000):
self.statusBar().showMessage(message, delay)
def resetState(self):
self.labelList.clear()
self.filename = None
self.imagePath = None
self.imageData = None
self.labelFile = None
self.otherData = None
self.canvas.resetState()
def currentItem(self):
items = self.labelList.selectedItems()
if items:
return items[0]
return None
def addRecentFile(self, filename):
if filename in self.recentFiles:
self.recentFiles.remove(filename)
elif len(self.recentFiles) >= self.maxRecent:
self.recentFiles.pop()
self.recentFiles.insert(0, filename)
# Callbacks
def undoShapeEdit(self):
self.canvas.restoreShape()
self.labelList.clear()
self.loadShapes(self.canvas.shapes)
self.actions.undo.setEnabled(self.canvas.isShapeRestorable)
def tutorial(self):
url = "https://github.com/wkentaro/labelme/tree/master/examples/tutorial" # NOQA
webbrowser.open(url)
def toggleDrawingSensitive(self, drawing=True):
"""Toggle drawing sensitive.
In the middle of drawing, toggling between modes should be disabled.
"""
self.actions.editMode.setEnabled(not drawing)
self.actions.undoLastPoint.setEnabled(drawing)
self.actions.undo.setEnabled(not drawing)
self.actions.delete.setEnabled(not drawing)
def toggleDrawMode(self, edit=True, createMode="polygon"):
self.canvas.setEditing(edit)
self.canvas.createMode = createMode
if edit:
self.actions.createMode.setEnabled(True)
self.actions.createRectangleMode.setEnabled(True)
self.actions.createCircleMode.setEnabled(True)
self.actions.createLineMode.setEnabled(True)
self.actions.createPointMode.setEnabled(True)
self.actions.createLineStripMode.setEnabled(True)
else:
if createMode == "polygon":
self.actions.createMode.setEnabled(False)
self.actions.createRectangleMode.setEnabled(True)
self.actions.createCircleMode.setEnabled(True)
self.actions.createLineMode.setEnabled(True)
self.actions.createPointMode.setEnabled(True)
self.actions.createLineStripMode.setEnabled(True)
elif createMode == "rectangle":
self.actions.createMode.setEnabled(True)
self.actions.createRectangleMode.setEnabled(False)
self.actions.createCircleMode.setEnabled(True)
self.actions.createLineMode.setEnabled(True)
self.actions.createPointMode.setEnabled(True)
self.actions.createLineStripMode.setEnabled(True)
elif createMode == "line":
self.actions.createMode.setEnabled(True)
self.actions.createRectangleMode.setEnabled(True)
self.actions.createCircleMode.setEnabled(True)
self.actions.createLineMode.setEnabled(False)
self.actions.createPointMode.setEnabled(True)
self.actions.createLineStripMode.setEnabled(True)
elif createMode == "point":
self.actions.createMode.setEnabled(True)
self.actions.createRectangleMode.setEnabled(True)
self.actions.createCircleMode.setEnabled(True)
self.actions.createLineMode.setEnabled(True)
self.actions.createPointMode.setEnabled(False)
self.actions.createLineStripMode.setEnabled(True)
elif createMode == "circle":
self.actions.createMode.setEnabled(True)
self.actions.createRectangleMode.setEnabled(True)
self.actions.createCircleMode.setEnabled(False)
self.actions.createLineMode.setEnabled(True)
self.actions.createPointMode.setEnabled(True)
self.actions.createLineStripMode.setEnabled(True)
elif createMode == "linestrip":