-
Notifications
You must be signed in to change notification settings - Fork 605
/
cityscapesLabelTool.py
2881 lines (2494 loc) · 108 KB
/
cityscapesLabelTool.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
#!/usr/bin/env python
# -*- coding: utf-8 -*-
#################
# Import modules
#################
from __future__ import print_function, absolute_import, division
# get command line parameters
import sys
# walk directories
import glob
# access to OS functionality
import os
# (de)serialize config file
import json
# call processes
import subprocess
# get the user name
import getpass
# xml parsing
import xml.etree.ElementTree as ET
# copy stuff
import copy
# import pyqt for everything graphical
from PyQt5 import QtCore, QtGui, QtWidgets
#################
# Helper classes
#################
from cityscapesscripts.helpers.version import version as VERSION
# annotation helper
from cityscapesscripts.helpers.annotation import Point, Annotation, CsPoly
from cityscapesscripts.helpers.labels import name2label, assureSingleInstanceName
# Helper class that contains the current configuration of the Gui
# This config is loaded when started and saved when leaving
class configuration:
# Constructor
def __init__(self):
# The filename of the image we currently working on
self.currentFile = ""
# The filename of the labels we currently working on
self.currentLabelFile = ""
# The filename of the corrections we currently working on
self.currentCorrectionFile = ""
# The path where the Cityscapes dataset is located
self.csPath = ""
# The path of the images of the currently loaded city
self.city = ""
# The name of the currently loaded city
self.cityName = ""
# The type of the current annotations
self.gtType = ""
# The split, where the currently loaded city belongs to
self.split = ""
# The path of the labels. In this folder we expect a folder for each city
# Within these city folders we expect the label with a filename matching
# the images, except for the extension
self.labelPath = ""
# The path to store correction markings
self.correctionPath = ""
# The transparency of the labels over the image
self.transp = 0.5
# The zoom toggle
self.zoom = False
# The zoom factor
self.zoomFactor = 1.0
# The size of the zoom window. Currently there is no setter or getter for that
self.zoomSize = 400 # px
# The highlight toggle
self.highlight = False
# The highlight label
self.highlightLabelSelection = ""
# Screenshot file
self.screenshotFilename = "%i"
# Correction mode
self.correctionMode = False
# Warn before saving that you are overwriting files
self.showSaveWarning = True
# Load from given filename
def load(self, filename):
if os.path.isfile(filename):
with open(filename, 'r') as f:
jsonText = f.read()
jsonDict = json.loads(jsonText)
for key in jsonDict:
if key in self.__dict__:
self.__dict__[key] = jsonDict[key]
self.fixConsistency()
# Make sure the config is consistent.
# Automatically called after loading
def fixConsistency(self):
if self.currentFile:
self.currentFile = os.path.normpath(self.currentFile)
if self.currentLabelFile:
self.currentLabelFile = os.path.normpath(self.currentLabelFile)
if self.currentCorrectionFile:
self.currentCorrectionFile = os.path.normpath(
self.currentCorrectionFile)
if self.csPath:
self.csPath = os.path.normpath(self.csPath)
if not os.path.isdir(self.csPath):
self.csPath = ""
if self.city:
self.city = os.path.normpath(self.city)
if not os.path.isdir(self.city):
self.city = ""
if self.labelPath:
self.labelPath = os.path.normpath(self.labelPath)
if self.correctionPath:
self.correctionPath = os.path.normpath(self.correctionPath)
if self.city:
self.cityName == os.path.basename(self.city)
if not os.path.isfile(self.currentFile) or os.path.dirname(self.currentFile) != self.city:
self.currentFile = ""
if not os.path.isfile(self.currentLabelFile) or \
not os.path.isdir(os.path.join(self.labelPath, self.cityName)) or \
os.path.dirname(self.currentLabelFile) != os.path.join(self.labelPath, self.cityName):
self.currentLabelFile = ""
if not os.path.isfile(self.currentCorrectionFile) or \
not os.path.isdir(os.path.join(self.correctionPath, self.cityName)) or \
os.path.dirname(self.currentCorrectionFile) != os.path.join(self.correctionPath, self.cityName):
self.currentCorrectionFile = ""
# Save to given filename (using pickle)
def save(self, filename):
with open(filename, 'w') as f:
f.write(json.dumps(self.__dict__,
default=lambda o: o.__dict__, sort_keys=True, indent=4))
def enum(**enums):
return type('Enum', (), enums)
class CorrectionBox:
types = enum(TO_CORRECT=1, TO_REVIEW=2, RESOLVED=3, QUESTION=4)
def __init__(self, rect=None, annotation=""):
self.type = CorrectionBox.types.TO_CORRECT
self.bbox = rect
self.annotation = annotation
self.selected = False
return
def get_colour(self):
if self.type == CorrectionBox.types.TO_CORRECT:
return QtGui.QColor(255, 0, 0)
elif self.type == CorrectionBox.types.TO_REVIEW:
return QtGui.QColor(255, 255, 0)
elif self.type == CorrectionBox.types.RESOLVED:
return QtGui.QColor(0, 255, 0)
elif self.type == CorrectionBox.types.QUESTION:
return QtGui.QColor(0, 0, 255)
def select(self):
if not self.selected:
self.selected = True
return
def unselect(self):
if self.selected:
self.selected = False
return
# Read the information from the given object node in an XML file
# The node must have the tag object and contain all expected fields
def readFromXMLNode(self, correctionNode):
if not correctionNode.tag == 'correction':
return
typeNode = correctionNode.find('type')
self.type = int(typeNode.text)
annotationNode = correctionNode.find('annotation')
self.annotation = annotationNode.text
bboxNode = correctionNode.find('bbox')
x = float(bboxNode.find('x').text)
y = float(bboxNode.find('y').text)
width = float(bboxNode.find('width').text)
height = float(bboxNode.find('height').text)
self.bbox = QtCore.QRectF(x, y, width, height)
# Append the information to a node of an XML file
# Creates an object node with all children and appends to the given node
# Usually the given node is the root
def appendToXMLNode(self, node):
# New object node
correctionNode = ET.SubElement(node, 'correction')
correctionNode.tail = "\n"
correctionNode.text = "\n"
# Name node
typeNode = ET.SubElement(correctionNode, 'type')
typeNode.tail = "\n"
typeNode.text = str(int(self.type))
# Deleted node
annotationNode = ET.SubElement(correctionNode, 'annotation')
annotationNode.tail = "\n"
annotationNode.text = str(self.annotation)
# Polygon node
bboxNode = ET.SubElement(correctionNode, 'bbox')
bboxNode.text = "\n"
bboxNode.tail = "\n"
xNode = ET.SubElement(bboxNode, 'x')
xNode.tail = "\n"
yNode = ET.SubElement(bboxNode, 'y')
yNode.tail = "\n"
xNode.text = str(int(round(self.bbox.x())))
yNode.text = str(int(round(self.bbox.y())))
wNode = ET.SubElement(bboxNode, 'width')
wNode.tail = "\n"
hNode = ET.SubElement(bboxNode, 'height')
hNode.tail = "\n"
wNode.text = str(int(round(self.bbox.width())))
hNode.text = str(int(round(self.bbox.height())))
#################
# Main GUI class
#################
# The main class which is a QtGui -> Main Window
class CityscapesLabelTool(QtWidgets.QMainWindow):
#############################
# Construction / Destruction
#############################
# Constructor
def __init__(self):
# Construct base class
super(CityscapesLabelTool, self).__init__()
# The filename of where the config is saved and loaded
configDir = os.path.dirname(__file__)
self.configFile = os.path.join(configDir, "cityscapesLabelTool.conf")
# This is the configuration.
self.config = configuration()
self.config.load(self.configFile)
# Other member variables
# The width that we actually use to show the image
self.w = 0
# The height that we actually use to show the image
self.h = 0
# The horizontal offset where we start drawing within the widget
self.xoff = 0
# The vertical offset where we start drawing withing the widget
self.yoff = 0
# A gap that we leave around the image as little border
self.bordergap = 20
# The scale that was used, ie
# self.w = self.scale * self.image.width()
# self.h = self.scale * self.image.height()
self.scale = 1.0
# Filenames of all images in current city
self.images = []
# Image extension
self.imageExt = "_leftImg8bit.png"
# Ground truth extension
self.gtExt = "{}_polygons.json"
# Current image as QImage
self.image = QtGui.QImage()
# Index of the current image within the city folder
self.idx = 0
# All annotated objects in current image
self.annotation = None
# The XML ElementTree representing the corrections for the current image
self.correctionXML = None
# A list of changes that we did on the current annotation
# Each change is simply a descriptive string
self.changes = []
# The current object the mouse points to. It's index in self.annotation.objects
self.mouseObj = -1
# The currently selected objects. Their index in self.annotation.objects
self.selObjs = []
# The objects that are highlighted. List of object instances
self.highlightObjs = []
# A label that is selected for highlighting
self.highlightObjLabel = None
# Texture for highlighting
self.highlightTexture = None
# The position of the mouse
self.mousePos = None
# TODO: NEEDS BETTER EXPLANATION/ORGANISATION
self.mousePosOrig = None
# The position of the mouse scaled to label coordinates
self.mousePosScaled = None
# If the mouse is outside of the image
self.mouseOutsideImage = True
# The position of the mouse upon enabling the zoom window
self.mousePosOnZoom = None
# The button state of the mouse
self.mouseButtons = 0
# A list of objects with changed layer
self.changedLayer = []
# A list of objects with changed polygon
self.changedPolygon = []
# A polygon that is drawn by the user
self.drawPoly = QtGui.QPolygonF()
# Treat the polygon as being closed
self.drawPolyClosed = False
# A point of this poly that is dragged
self.draggedPt = -1
# A list of toolbar actions that need an image
self.actImage = []
# A list of toolbar actions that need an image that is not the first
self.actImageNotFirst = []
# A list of toolbar actions that need an image that is not the last
self.actImageNotLast = []
# A list of toolbar actions that need changes
self.actChanges = []
# A list of toolbar actions that need a drawn polygon or selected objects
self.actPolyOrSelObj = []
# A list of toolbar actions that need a closed drawn polygon
self.actClosedPoly = []
# A list of toolbar actions that need selected objects
self.actSelObj = []
# A list of toolbar actions that need a single active selected object
self.singleActSelObj = []
# Toggle status of auto-doing screenshots
self.screenshotToggleState = False
# Toggle status of the play icon
self.playState = False
# Temporary zero transparency
self.transpTempZero = False
# Toggle correction mode on and off
self.correctAction = []
self.corrections = []
self.selected_correction = -1
self.in_progress_bbox = None
self.in_progress_correction = None
self.mousePressEvent = []
# Default label
self.defaultLabel = 'static'
if not self.defaultLabel in name2label:
print('The {0} label is missing in the internal label definitions.'.format(
self.defaultLabel))
return
# Last selected label
self.lastLabel = self.defaultLabel
# Setup the GUI
self.initUI()
# Initially clear stuff
self.deselectAllObjects()
self.clearPolygon()
self.clearChanges()
# If we already know a city from the saved config -> load it
self.loadCity()
self.imageChanged()
# Destructor
def __del__(self):
self.config.save(self.configFile)
# Construct everything GUI related. Called by constructor
def initUI(self):
# Create a toolbar
self.toolbar = self.addToolBar('Tools')
# Add the tool buttons
iconDir = os.path.join(os.path.dirname(__file__), 'icons')
# Loading a new city
loadAction = QtWidgets.QAction(QtGui.QIcon(
os.path.join(iconDir, 'open.png')), '&Tools', self)
loadAction.setShortcuts(['o'])
self.setTip(loadAction, 'Open city')
loadAction.triggered.connect(self.selectCity)
self.toolbar.addAction(loadAction)
# Open previous image
backAction = QtWidgets.QAction(QtGui.QIcon(
os.path.join(iconDir, 'back.png')), '&Tools', self)
backAction.setShortcut('left')
backAction.setStatusTip('Previous image')
backAction.triggered.connect(self.prevImage)
self.toolbar.addAction(backAction)
self.actImageNotFirst.append(backAction)
# Open next image
nextAction = QtWidgets.QAction(QtGui.QIcon(
os.path.join(iconDir, 'next.png')), '&Tools', self)
nextAction.setShortcut('right')
self.setTip(nextAction, 'Next image')
nextAction.triggered.connect(self.nextImage)
self.toolbar.addAction(nextAction)
self.actImageNotLast.append(nextAction)
# Play
playAction = QtWidgets.QAction(QtGui.QIcon(
os.path.join(iconDir, 'play.png')), '&Tools', self)
playAction.setShortcut(' ')
playAction.setCheckable(True)
playAction.setChecked(False)
self.setTip(playAction, 'Play all images')
playAction.triggered.connect(self.playImages)
self.toolbar.addAction(playAction)
self.actImageNotLast.append(playAction)
self.playAction = playAction
# Select image
selImageAction = QtWidgets.QAction(QtGui.QIcon(
os.path.join(iconDir, 'shuffle.png')), '&Tools', self)
selImageAction.setShortcut('i')
self.setTip(selImageAction, 'Select image')
selImageAction.triggered.connect(self.selectImage)
self.toolbar.addAction(selImageAction)
self.actImage.append(selImageAction)
# Save the current image
saveAction = QtWidgets.QAction(QtGui.QIcon(
os.path.join(iconDir, 'save.png')), '&Tools', self)
saveAction.setShortcut('s')
self.setTip(saveAction, 'Save changes')
saveAction.triggered.connect(self.save)
self.toolbar.addAction(saveAction)
self.actChanges.append(saveAction)
# Clear the currently edited polygon
clearPolAction = QtWidgets.QAction(QtGui.QIcon(
os.path.join(iconDir, 'clearpolygon.png')), '&Tools', self)
clearPolAction.setShortcuts(['q', 'Esc'])
self.setTip(clearPolAction, 'Clear polygon')
clearPolAction.triggered.connect(self.clearPolygonAction)
self.toolbar.addAction(clearPolAction)
self.actPolyOrSelObj.append(clearPolAction)
# Create new object from drawn polygon
newObjAction = QtWidgets.QAction(QtGui.QIcon(
os.path.join(iconDir, 'newobject.png')), '&Tools', self)
newObjAction.setShortcuts(['n'])
self.setTip(newObjAction, 'New object')
newObjAction.triggered.connect(self.newObject)
self.toolbar.addAction(newObjAction)
self.actClosedPoly.append(newObjAction)
# Delete the currently selected object
deleteObjectAction = QtWidgets.QAction(QtGui.QIcon(
os.path.join(iconDir, 'deleteobject.png')), '&Tools', self)
deleteObjectAction.setShortcuts(['d', 'delete'])
self.setTip(deleteObjectAction, 'Delete object')
deleteObjectAction.triggered.connect(self.deleteObject)
self.toolbar.addAction(deleteObjectAction)
self.actSelObj.append(deleteObjectAction)
# Undo changes in current image, ie. reload labels from file
undoAction = QtWidgets.QAction(QtGui.QIcon(
os.path.join(iconDir, 'undo.png')), '&Tools', self)
undoAction.setShortcut('u')
self.setTip(undoAction, 'Undo all unsaved changes')
undoAction.triggered.connect(self.undo)
self.toolbar.addAction(undoAction)
self.actChanges.append(undoAction)
# Modify the label of a selected object
labelAction = QtWidgets.QAction(QtGui.QIcon(
os.path.join(iconDir, 'modify.png')), '&Tools', self)
labelAction.setShortcuts(['m', 'l'])
self.setTip(labelAction, 'Modify label')
labelAction.triggered.connect(self.modifyLabel)
self.toolbar.addAction(labelAction)
self.actSelObj.append(labelAction)
# Move selected object a layer up
layerUpAction = QtWidgets.QAction(QtGui.QIcon(
os.path.join(iconDir, 'layerup.png')), '&Tools', self)
layerUpAction.setShortcuts(['Up'])
self.setTip(layerUpAction, 'Move object a layer up')
layerUpAction.triggered.connect(self.layerUp)
self.toolbar.addAction(layerUpAction)
self.singleActSelObj.append(layerUpAction)
# Move selected object a layer down
layerDownAction = QtWidgets.QAction(QtGui.QIcon(
os.path.join(iconDir, 'layerdown.png')), '&Tools', self)
layerDownAction.setShortcuts(['Down'])
self.setTip(layerDownAction, 'Move object a layer down')
layerDownAction.triggered.connect(self.layerDown)
self.toolbar.addAction(layerDownAction)
self.singleActSelObj.append(layerDownAction)
# Enable/disable zoom. Toggle button
zoomAction = QtWidgets.QAction(QtGui.QIcon(
os.path.join(iconDir, 'zoom.png')), '&Tools', self)
zoomAction.setShortcuts(['z'])
zoomAction.setCheckable(True)
zoomAction.setChecked(self.config.zoom)
self.setTip(zoomAction, 'Enable/disable permanent zoom')
zoomAction.toggled.connect(self.zoomToggle)
self.toolbar.addAction(zoomAction)
self.actImage.append(zoomAction)
# Highlight objects of a certain class
highlightAction = QtWidgets.QAction(QtGui.QIcon(
os.path.join(iconDir, 'highlight.png')), '&Tools', self)
highlightAction.setShortcuts(['g'])
highlightAction.setCheckable(True)
highlightAction.setChecked(self.config.highlight)
self.setTip(highlightAction,
'Enable/disable highlight of certain object class')
highlightAction.toggled.connect(self.highlightClassToggle)
self.toolbar.addAction(highlightAction)
self.actImage.append(highlightAction)
# Decrease transparency
minusAction = QtWidgets.QAction(QtGui.QIcon(
os.path.join(iconDir, 'minus.png')), '&Tools', self)
minusAction.setShortcut('-')
self.setTip(minusAction, 'Decrease transparency')
minusAction.triggered.connect(self.minus)
self.toolbar.addAction(minusAction)
# Increase transparency
plusAction = QtWidgets.QAction(QtGui.QIcon(
os.path.join(iconDir, 'plus.png')), '&Tools', self)
plusAction.setShortcut('+')
self.setTip(plusAction, 'Increase transparency')
plusAction.triggered.connect(self.plus)
self.toolbar.addAction(plusAction)
# Take a screenshot
screenshotAction = QtWidgets.QAction(QtGui.QIcon(
os.path.join(iconDir, 'screenshot.png')), '&Tools', self)
screenshotAction.setShortcut('t')
self.setTip(screenshotAction, 'Take a screenshot')
screenshotAction.triggered.connect(self.screenshot)
self.toolbar.addAction(screenshotAction)
self.actImage.append(screenshotAction)
# Take a screenshot in each loaded frame
screenshotToggleAction = QtWidgets.QAction(QtGui.QIcon(
os.path.join(iconDir, 'screenshotToggle.png')), '&Tools', self)
screenshotToggleAction.setShortcut('Ctrl+t')
screenshotToggleAction.setCheckable(True)
screenshotToggleAction.setChecked(False)
self.setTip(screenshotToggleAction,
'Take a screenshot in each loaded frame')
screenshotToggleAction.toggled.connect(self.screenshotToggle)
self.toolbar.addAction(screenshotToggleAction)
self.actImage.append(screenshotToggleAction)
# Display path to current image in message bar
displayFilepathAction = QtWidgets.QAction(QtGui.QIcon(
os.path.join(iconDir, 'filepath.png')), '&Tools', self)
displayFilepathAction.setShortcut('f')
self.setTip(displayFilepathAction, 'Show path to current image')
displayFilepathAction.triggered.connect(self.displayFilepath)
self.toolbar.addAction(displayFilepathAction)
# Open correction mode
self.correctAction = QtWidgets.QAction(QtGui.QIcon(
os.path.join(iconDir, 'checked6.png')), '&Tools', self)
self.correctAction.setShortcut('c')
self.correctAction.setCheckable(True)
self.correctAction.setChecked(self.config.correctionMode)
if self.config.correctionMode:
self.correctAction.setIcon(QtGui.QIcon(
os.path.join(iconDir, 'checked6_red.png')))
self.setTip(self.correctAction, 'Toggle correction mode')
self.correctAction.triggered.connect(self.toggleCorrectionMode)
self.toolbar.addAction(self.correctAction)
# Display help message
helpAction = QtWidgets.QAction(QtGui.QIcon(
os.path.join(iconDir, 'help19.png')), '&Tools', self)
helpAction.setShortcut('h')
self.setTip(helpAction, 'Help')
helpAction.triggered.connect(self.displayHelpMessage)
self.toolbar.addAction(helpAction)
# Close the application
exitAction = QtWidgets.QAction(QtGui.QIcon(
os.path.join(iconDir, 'exit.png')), '&Tools', self)
# exitAction.setShortcuts(['Esc'])
self.setTip(exitAction, 'Exit')
exitAction.triggered.connect(self.close)
self.toolbar.addAction(exitAction)
# The default text for the status bar
self.defaultStatusbar = 'Ready'
# Create a statusbar. Init with default
self.statusBar().showMessage(self.defaultStatusbar)
# Enable mouse move events
self.setMouseTracking(True)
self.toolbar.setMouseTracking(True)
# Open in full screen
screenShape = QtWidgets.QDesktopWidget().screenGeometry()
self.resize(screenShape.width(), screenShape.height())
# Set a title
self.applicationTitle = 'Cityscapes Label Tool v{}'.format(VERSION)
self.setWindowTitle(self.applicationTitle)
# And show the application
self.show()
#############################
# Toolbar call-backs
#############################
# The user pressed "select city"
# The purpose of this method is to set these configuration attributes:
# - self.config.city : path to the folder containing the images to annotate
# - self.config.cityName : name of this folder, i.e. the city
# - self.config.labelPath : path to the folder to store the polygons
# - self.config.correctionPath : path to store the correction boxes in
# - self.config.gtType : type of ground truth, e.g. gtFine or gtCoarse
# - self.config.split : type of split, e.g. train, val, test
# The current implementation uses the environment variable 'CITYSCAPES_DATASET'
# to determine the dataset root folder and search available data within.
# Annotation types are required to start with 'gt', e.g. gtFine or gtCoarse.
# To add your own annotations you could create a folder gtCustom with similar structure.
#
# However, this implementation could be easily changed to a completely different folder structure.
# Just make sure to specify all three paths and a descriptive name as 'cityName'.
# The gtType and split can be left empty.
def selectCity(self):
# Reset the status bar to this message when leaving
restoreMessage = self.statusBar().currentMessage()
csPath = self.config.csPath
if not csPath or not os.path.isdir(csPath):
if 'CITYSCAPES_DATASET' in os.environ:
csPath = os.environ['CITYSCAPES_DATASET']
else:
csPath = os.path.join(os.path.dirname(
os.path.realpath(__file__)), '..', '..')
availableCities = []
annotations = sorted(glob.glob(os.path.join(csPath, 'gt*')))
annotations = [os.path.basename(a) for a in annotations]
splits = ["train_extra", "train", "val", "test"]
for gt in annotations:
for split in splits:
cities = glob.glob(os.path.join(csPath, gt, split, '*'))
cities.sort()
availableCities.extend(
[(split, gt, os.path.basename(c)) for c in cities if os.path.isdir(c)])
# List of possible labels
items = [split + ", " + gt + ", " +
city for (split, gt, city) in availableCities]
# default
previousItem = self.config.split + ", " + \
self.config.gtType + ", " + self.config.cityName
default = 0
if previousItem in items:
default = items.index(previousItem)
# Specify title
dlgTitle = "Select city"
message = dlgTitle
question = dlgTitle
message = "Select city for editing"
question = "Which city would you like to edit?"
self.statusBar().showMessage(message)
if items:
# Create and wait for dialog
(item, ok) = QtWidgets.QInputDialog.getItem(
self, dlgTitle, question, items, default, False)
# Restore message
self.statusBar().showMessage(restoreMessage)
if ok and item:
(split, gt, city) = [str(i) for i in item.split(', ')]
self.config.city = os.path.normpath(
os.path.join(csPath, "leftImg8bit", split, city))
self.config.cityName = city
self.config.labelPath = os.path.normpath(
os.path.join(csPath, gt, split, city))
self.config.correctionPath = os.path.normpath(
os.path.join(csPath, gt+'_corrections', split, city))
self.config.gtType = gt
self.config.split = split
self.deselectAllObjects()
self.clearPolygon()
self.loadCity()
self.imageChanged()
else:
warning = ""
warning += "The data was not found. Please:\n\n"
warning += " - make sure the scripts folder is in the Cityscapes root folder\n"
warning += "or\n"
warning += " - set CITYSCAPES_DATASET to the Cityscapes root folder\n"
warning += " e.g. 'export CITYSCAPES_DATASET=<root_path>'\n"
reply = QtWidgets.QMessageBox.information(
self, "ERROR!", warning, QtWidgets.QMessageBox.Ok)
if reply == QtWidgets.QMessageBox.Ok:
sys.exit()
return
# Switch to previous image in file list
# Load the image
# Load its labels
# Update the mouse selection
# View
def prevImage(self):
if not self.images:
return
if self.idx > 0:
if self.checkAndSave():
self.idx -= 1
self.imageChanged()
return
# Switch to next image in file list
# Load the image
# Load its labels
# Update the mouse selection
# View
def nextImage(self):
if not self.images:
return
if self.idx < len(self.images)-1:
if self.checkAndSave():
self.idx += 1
self.imageChanged()
elif self.playState:
self.playState = False
self.playAction.setChecked(False)
if self.playState:
QtCore.QTimer.singleShot(0, self.nextImage)
return
# Play images, i.e. auto-switch to next image
def playImages(self, status):
self.playState = status
if self.playState:
QtCore.QTimer.singleShot(0, self.nextImage)
# switch correction mode on and off
def toggleCorrectionMode(self):
if not self.config.correctionMode:
self.config.correctionMode = True
iconDir = os.path.join(os.path.dirname(sys.argv[0]), 'icons')
self.correctAction.setIcon(QtGui.QIcon(
os.path.join(iconDir, 'checked6_red.png')))
else:
self.config.correctionMode = False
iconDir = os.path.join(os.path.dirname(sys.argv[0]), 'icons')
self.correctAction.setIcon(QtGui.QIcon(
os.path.join(iconDir, 'checked6.png')))
self.update()
return
# Switch to a selected image of the file list
# Ask the user for an image
# Load the image
# Load its labels
# Update the mouse selection
# View
def selectImage(self):
if not self.images:
return
dlgTitle = "Select image to load"
self.statusBar().showMessage(dlgTitle)
items = ["{}: {}".format(num, os.path.basename(i))
for (num, i) in enumerate(self.images)]
(item, ok) = QtWidgets.QInputDialog.getItem(
self, dlgTitle, "Image", items, self.idx, False)
if (ok and item):
idx = items.index(item)
if idx != self.idx and self.checkAndSave():
self.idx = idx
self.imageChanged()
else:
# Restore the message
self.statusBar().showMessage(self.defaultStatusbar)
# Save labels
def save(self):
# Status
saved = False
# Message to show at the status bar when done
message = ""
# Only save if there are changes, labels, an image filename and an image
if self.changes and (self.annotation or self.corrections) and self.config.currentFile and self.image:
if self.annotation:
# set image dimensions
self.annotation.imgWidth = self.image.width()
self.annotation.imgHeight = self.image.height()
# Determine the filename
# If we have a loaded label file, then this is also the filename
filename = self.config.currentLabelFile
# If not, then generate one
if not filename:
filename = self.getLabelFilename(True)
if filename:
proceed = True
# warn user that he is overwriting an old file
if os.path.isfile(filename) and self.config.showSaveWarning:
msgBox = QtWidgets.QMessageBox(self)
msgBox.setWindowTitle("Overwriting")
msgBox.setText(
"Saving overwrites the original file and it cannot be reversed. Do you want to continue?")
msgBox.addButton(QtWidgets.QMessageBox.Cancel)
okAndNeverAgainButton = msgBox.addButton(
'OK and never ask again', QtWidgets.QMessageBox.AcceptRole)
okButton = msgBox.addButton(QtWidgets.QMessageBox.Ok)
msgBox.setDefaultButton(QtWidgets.QMessageBox.Ok)
msgBox.setIcon(QtWidgets.QMessageBox.Warning)
msgBox.exec_()
# User clicked on "OK"
if msgBox.clickedButton() == okButton:
pass
# User clicked on "OK and never ask again"
elif msgBox.clickedButton() == okAndNeverAgainButton:
self.config.showSaveWarning = False
else:
# Do nothing
message += "Nothing saved, no harm has been done. "
proceed = False
# Save JSON file
if proceed:
try:
self.annotation.toJsonFile(filename)
saved = True
message += "Saved labels to {0} ".format(filename)
except IOError as e:
message += "Error writing labels to {0}. Message: {1} ".format(
filename, e.strerror)
else:
message += "Error writing labels. Cannot generate a valid filename. "
if self.corrections or self.config.currentCorrectionFile:
# Determine the filename
# If we have a loaded label file, then this is also the filename
filename = self.config.currentCorrectionFile
# If not, then generate one
if not filename:
filename = self.getCorrectionFilename(True)
if filename:
# Prepare the root
root = ET.Element('correction')
root.text = "\n"
root.tail = "\n"
# Add the filename of the image that is annotated
filenameNode = ET.SubElement(root, 'filename')
filenameNode.text = os.path.basename(
self.config.currentFile)
filenameNode.tail = "\n"
# Add the folder where this image is located in
# For compatibility with the LabelMe Tool, we need to use the folder
# StereoDataset/cityName
folderNode = ET.SubElement(root, 'folder')
folderNode.text = "StereoDataset/" + self.config.cityName
folderNode.tail = "\n"
# The name of the tool. Here, we do not follow the output of the LabelMe tool,
# since this is crap anyway
sourceNode = ET.SubElement(root, 'source')
sourceNode.text = "\n"
sourceNode.tail = "\n"
sourceImageNode = ET.SubElement(sourceNode, 'sourceImage')
sourceImageNode.text = "Label Cities"
sourceImageNode.tail = "\n"
sourceAnnotationNode = ET.SubElement(
sourceNode, 'sourceAnnotation')
sourceAnnotationNode.text = "mcLabelTool"
sourceAnnotationNode.tail = "\n"
# The image size
imagesizeNode = ET.SubElement(root, 'imagesize')
imagesizeNode.text = "\n"
imagesizeNode.tail = "\n"
nrowsNode = ET.SubElement(imagesizeNode, 'nrows')
nrowsNode.text = str(self.image.height())
nrowsNode.tail = "\n"
ncolsNode = ET.SubElement(imagesizeNode, 'ncols')
ncolsNode.text = str(self.image.height())
ncolsNode.tail = "\n"
# Add all objects
for correction in self.corrections:
correction.appendToXMLNode(root)
# Create the actual XML tree
self.correctionXML = ET.ElementTree(root)
# Save XML file
try:
self.correctionXML.write(filename)
saved = True
message += "Saved corrections to {0} ".format(filename)
except IOError as e:
message += "Error writing corrections to {0}. Message: {1} ".format(
filename, e.strerror)
else:
message += "Error writing corrections. Cannot generate a valid filename. "
# Clear changes
if saved:
self.clearChanges()
else:
message += "Nothing to save "
saved = True
# Show the status message
self.statusBar().showMessage(message)
return saved
# Undo changes, ie. reload labels
def undo(self):
# check if we really want to do this in case there are multiple changes
if len(self.changes) > 1:
# Backup of status message
restoreMessage = self.statusBar().currentMessage()
# Create the dialog
dlgTitle = "Undo changes?"
self.statusBar().showMessage(dlgTitle)
text = "Do you want to undo the following changes?\n"
for c in self.changes:
text += "- " + c + '\n'
buttons = QtWidgets.QMessageBox.Ok | QtWidgets.QMessageBox.Cancel
ret = QtWidgets.QMessageBox.question(
self, dlgTitle, text, buttons, QtWidgets.QMessageBox.Ok)
proceed = False
# If the user selected yes -> undo
if ret == QtWidgets.QMessageBox.Ok:
proceed = True
self.statusBar().showMessage(restoreMessage)
# If we do not proceed -> return
if not proceed:
return
# Clear labels to force a reload
self.annotation = None
# Reload
self.imageChanged()
# Clear the drawn polygon and update
def clearPolygonAction(self):
self.deselectAllObjects()
self.clearPolygon()
self.update()
# Create a new object from the current polygon
def newObject(self):
# Default label
label = self.lastLabel
# Ask the user for a label
(label, ok) = self.getLabelFromUser(label)
if ok and label:
# Append and create the new object
self.appendObject(label, self.drawPoly)
# Clear the drawn polygon
self.deselectAllObjects()
self.clearPolygon()