forked from cnr-isti-vclab/TagLab
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathTagLab.py
More file actions
2123 lines (1489 loc) · 67.7 KB
/
Copy pathTagLab.py
File metadata and controls
2123 lines (1489 loc) · 67.7 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
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
# TagLab
# A semi-automatic segmentation tool
#
# Copyright(C) 2019
# Visual Computing Lab
# ISTI - Italian National Research Council
# All rights reserved.
# This program is free software; you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation; either version 2 of the License, or
# (at your option) any later version.
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
#GNU General Public License (http://www.gnu.org/licenses/gpl.txt)
# for more details.
import sys
import os
import glob
import time
import random
import datetime
import json
import numpy as np
import numpy.ma as ma
from skimage import measure
from PyQt5.QtCore import Qt, QSize, QDir, QPoint, QPointF, QLineF, QRectF, QTimer, pyqtSlot, pyqtSignal
from PyQt5.QtGui import QPainterPath, QFont, QColor, QPolygonF, QImage, QPixmap, QIcon, QKeySequence, \
QPen, QBrush, qRgb, qRed, qGreen, qBlue
from PyQt5.QtWidgets import QApplication, QWidget, QFileDialog, QDialog, QMenuBar, QMenu, QSizePolicy, QScrollArea, QLabel, QToolButton, QPushButton, QSlider, \
QMessageBox, QGroupBox, QHBoxLayout, QVBoxLayout, QTextEdit, QLineEdit, QGraphicsView, QAction
# PYTORCH
import torch
from torch.nn.functional import upsample
from collections import OrderedDict
# DEEP EXTREME
import models.deeplab_resnet as resnet
from models.dataloaders import helpers as helpers
# CUSTOM
from source.QtImageViewerPlus import QtImageViewerPlus
from source.QtMapViewer import QtMapViewer
from source.QtMapSettingsWidget import QtMapSettingsWidget
from source.QtInfoWidget import QtInfoWidget
from source.QtCrackWidget import QtCrackWidget
from source.QtExportWidget import QtExportWidget
#from QtInfoWidget import QtInfoWidget
from source.Annotation import Annotation, Blob
from source.Labels import Labels, LabelsWidget
from source import utils
# LOGGING
import logging
# configure the logger
now = datetime.datetime.now()
LOG_FILENAME = "tool" + now.strftime("%Y-%m-%d-%H-%M") + ".log"
logging.basicConfig(level=logging.DEBUG, filemode='w', filename=LOG_FILENAME, format = '%(asctime)s %(levelname)-8s %(message)s')
logfile = logging.getLogger("tool-logger")
class TagLab(QWidget):
def __init__(self, parent=None):
super(TagLab, self).__init__(parent)
##### CUSTOM STYLE #####
self.setStyleSheet("background-color: rgb(55,55,55); color: white")
##### DATA INITIALIZATION AND SETUP #####
logfile.info("Initizialization begins..")
# MAP VIEWER preferred size (longest side)
self.MAP_VIEWER_SIZE = 400
self.working_dir = os.getcwd()
self.project_name = "NONE"
self.map_image_filename = "map.png"
self.map_acquisition_date = "YYYY-MM-DD"
self.map_px_to_mm_factor = 1.0
self.project_to_save = ""
self.recentFileActs = []
self.maxRecentFiles = 4
# ANNOTATION DATA
self.annotations = Annotation()
##### INTERFACE #####
#####################
self.mapWidget = None
self.tool_used = "MOVE" # tool currently used
self.current_selection = None # blob currently selected
ICON_SIZE = 48
BUTTON_SIZE = 54
##### TOP LAYOUT
#top_layout = QHBoxLayout()
#self.scrippsIcon = QLabel()
#pxmap = QPixmap("icons\\vclab.png")
#pxmap = pxmap.scaledToWidth(ICON_SIZE+2)
#self.scrippsIcon.setPixmap(pxmap)
#top_layout.addWidget(self.scrippsIcon)
#top_layout.addStretch()
##### LAYOUT EDITING TOOLS (VERTICAL)
flatbuttonstyle1 = "\
QPushButton:checked\
{\
background-color: rgb(100,100,100);\
}\
QPushButton:hover\
{\
border: 1px solid darkgray;\
}"
flatbuttonstyle2 = "\
QPushButton:checked\
{\
background-color: rgb(100,100,100);\
}\
QPushButton:hover\
{\
border: 1px solid rgb(255,100,100);\
}"
layout_tools = QVBoxLayout()
self.btnMove = QPushButton()
self.btnMove.setEnabled(True)
self.btnMove.setCheckable(True)
self.btnMove.setFlat(True)
self.btnMove.setStyleSheet(flatbuttonstyle1)
self.btnMove.setMinimumWidth(ICON_SIZE)
self.btnMove.setMinimumHeight(ICON_SIZE)
self.btnMove.setIcon(QIcon("icons\\move.png"))
self.btnMove.setIconSize(QSize(ICON_SIZE, ICON_SIZE))
self.btnMove.setMaximumWidth(BUTTON_SIZE)
self.btnMove.setToolTip("Move")
self.btnMove.clicked.connect(self.move)
self.btnAssign = QPushButton()
self.btnAssign.setEnabled(True)
self.btnAssign.setCheckable(True)
self.btnAssign.setFlat(True)
self.btnAssign.setStyleSheet(flatbuttonstyle1)
self.btnAssign.setMinimumWidth(ICON_SIZE)
self.btnAssign.setMinimumHeight(ICON_SIZE)
self.btnAssign.setIcon(QIcon("icons\\bucket.png"))
self.btnAssign.setIconSize(QSize(ICON_SIZE, ICON_SIZE))
self.btnAssign.setMaximumWidth(BUTTON_SIZE)
self.btnAssign.setToolTip("Assign class")
self.btnAssign.clicked.connect(self.assign)
self.btnEditBorder = QPushButton()
self.btnEditBorder.setEnabled(True)
self.btnEditBorder.setCheckable(True)
self.btnEditBorder.setFlat(True)
self.btnEditBorder.setStyleSheet(flatbuttonstyle1)
self.btnEditBorder.setMinimumWidth(ICON_SIZE)
self.btnEditBorder.setMinimumHeight(ICON_SIZE)
self.btnEditBorder.setIcon(QIcon("icons\\edit.png"))
self.btnEditBorder.setIconSize(QSize(ICON_SIZE, ICON_SIZE))
self.btnEditBorder.setMaximumWidth(BUTTON_SIZE)
self.btnEditBorder.setToolTip("Edit border")
self.btnEditBorder.clicked.connect(self.editBorder)
self.btnFreehand = QPushButton()
self.btnFreehand.setEnabled(True)
self.btnFreehand.setCheckable(True)
self.btnFreehand.setFlat(True)
self.btnFreehand.setStyleSheet(flatbuttonstyle1)
self.btnFreehand.setMinimumWidth(ICON_SIZE)
self.btnFreehand.setMinimumHeight(ICON_SIZE)
self.btnFreehand.setIcon(QIcon("icons\\pencil.png"))
self.btnFreehand.setIconSize(QSize(ICON_SIZE, ICON_SIZE))
self.btnFreehand.setMaximumWidth(BUTTON_SIZE)
self.btnFreehand.setToolTip("Freehand segmentation")
self.btnFreehand.clicked.connect(self.freehandSegmentation)
self.btnCreateCrack = QPushButton()
self.btnCreateCrack.setEnabled(True)
self.btnCreateCrack.setCheckable(True)
self.btnCreateCrack.setFlat(True)
self.btnCreateCrack.setStyleSheet(flatbuttonstyle1)
self.btnCreateCrack.setMinimumWidth(ICON_SIZE)
self.btnCreateCrack.setMinimumHeight(ICON_SIZE)
self.btnCreateCrack.setIcon(QIcon("icons\\crack.png"))
self.btnCreateCrack.setIconSize(QSize(ICON_SIZE, ICON_SIZE))
self.btnCreateCrack.setMaximumWidth(BUTTON_SIZE)
self.btnCreateCrack.setToolTip("Create crack")
self.btnCreateCrack.clicked.connect(self.createCrack)
self.btnRuler = QPushButton()
self.btnRuler.setEnabled(True)
self.btnRuler.setCheckable(True)
self.btnRuler.setFlat(True)
self.btnRuler.setStyleSheet(flatbuttonstyle1)
self.btnRuler.setMinimumWidth(ICON_SIZE)
self.btnRuler.setMinimumHeight(ICON_SIZE)
self.btnRuler.setIcon(QIcon("icons\\ruler.png"))
self.btnRuler.setIconSize(QSize(ICON_SIZE, ICON_SIZE))
self.btnRuler.setMaximumWidth(BUTTON_SIZE)
self.btnRuler.setToolTip("Measure tool")
self.btnRuler.clicked.connect(self.ruler)
self.btnDeepExtreme = QPushButton()
self.btnDeepExtreme.setEnabled(True)
self.btnDeepExtreme.setCheckable(True)
self.btnDeepExtreme.setFlat(True)
self.btnDeepExtreme.setStyleSheet(flatbuttonstyle2)
self.btnDeepExtreme.setMinimumWidth(ICON_SIZE)
self.btnDeepExtreme.setMinimumHeight(ICON_SIZE)
self.btnDeepExtreme.setIcon(QIcon("icons\\dexter.png"))
self.btnDeepExtreme.setIconSize(QSize(ICON_SIZE, ICON_SIZE))
self.btnDeepExtreme.setMaximumWidth(BUTTON_SIZE)
self.btnDeepExtreme.setToolTip("Deep Extreme")
self.btnDeepExtreme.clicked.connect(self.deepExtreme)
layout_tools.setSpacing(0)
layout_tools.addWidget(self.btnMove)
layout_tools.addWidget(self.btnAssign)
layout_tools.addWidget(self.btnFreehand)
layout_tools.addWidget(self.btnEditBorder)
layout_tools.addWidget(self.btnCreateCrack)
layout_tools.addWidget(self.btnRuler)
#layout_tools.addWidget(self.btnCutter)
layout_tools.addSpacing(10)
layout_tools.addWidget(self.btnDeepExtreme)
#layout_tools.addWidget(self.btnAutomaticSeg)
layout_tools.addStretch()
###### LAYOUT MAIN VIEW
layout_viewer = QVBoxLayout()
self.lblSlider = QLabel("Transparency: 0%")
self.sliderTrasparency = QSlider(Qt.Horizontal)
self.sliderTrasparency.setFocusPolicy(Qt.StrongFocus)
self.sliderTrasparency.setMinimumWidth(200)
self.sliderTrasparency.setStyleSheet(slider_style2)
self.sliderTrasparency.setMinimum(0)
self.sliderTrasparency.setMaximum(100)
self.sliderTrasparency.setValue(0)
self.sliderTrasparency.setTickInterval(10)
self.sliderTrasparency.valueChanged.connect(self.sliderTrasparencyChanged)
self.labelViewInfo = QLabel("100% | top:0 left:0 right:0 bottom:0 ")
layout_slider = QHBoxLayout()
layout_slider.addWidget(self.lblSlider)
layout_slider.addWidget(self.sliderTrasparency)
layout_slider.addWidget(self.labelViewInfo)
self.viewerplus = QtImageViewerPlus()
self.viewerplus.viewUpdated.connect(self.updateViewInfo)
layout_viewer.setSpacing(1)
layout_viewer.addLayout(layout_slider)
layout_viewer.addWidget(self.viewerplus)
##### LAYOUT - labels + blob info + navigation map
# LABELS
self.labels_widget = LabelsWidget()
scroll_area = QScrollArea()
scroll_area.setStyleSheet("background-color: rgb(40,40,40); border:none")
scroll_area.setHorizontalScrollBarPolicy(Qt.ScrollBarAlwaysOff)
scroll_area.setMinimumHeight(200)
scroll_area.setWidget(self.labels_widget)
groupbox_labels = QGroupBox("Labels")
layout_groupbox = QVBoxLayout()
layout_groupbox.addWidget(scroll_area)
groupbox_labels.setLayout(layout_groupbox)
# BLOB INFO
groupbox_blobpanel = QGroupBox("Segmentation Info")
lblInstance = QLabel("Instance Name: ")
self.editInstance = QLineEdit()
self.editInstance.setMinimumWidth(80)
self.editInstance.setMaximumHeight(25)
self.editInstance.setStyleSheet("background-color: rgb(40,40,40); border: none")
lblId = QLabel("Id: ")
self.editId = QLineEdit()
self.editId.setMinimumWidth(80)
self.editId.setMaximumHeight(25)
self.editId.setStyleSheet("background-color: rgb(40,40,40); border: none")
blobpanel_layoutH1 = QHBoxLayout()
blobpanel_layoutH1.addWidget(lblInstance)
blobpanel_layoutH1.addWidget(self.editInstance)
blobpanel_layoutH1.addWidget(lblId)
blobpanel_layoutH1.addWidget(self.editId)
lblcl = QLabel("Class: ")
self.lblClass = QLabel("<b>Empty</b>")
self.lblP = QLabel("Perimeter: ")
self.lblA = QLabel("Area: ")
blobpanel_layoutH2 = QHBoxLayout()
blobpanel_layoutH2.addWidget(lblcl)
blobpanel_layoutH2.addWidget(self.lblClass)
blobpanel_layoutH2.addSpacing(6)
blobpanel_layoutH2.addWidget(self.lblP)
blobpanel_layoutH2.addWidget(self.lblA)
blobpanel_layoutH2.addStretch()
lblNote = QLabel("Note:")
self.editNote = QTextEdit()
self.editNote.setMinimumWidth(100)
self.editNote.setMaximumHeight(50)
self.editNote.setStyleSheet("background-color: rgb(40,40,40); border: 1px solid rgb(90,90,90)")
self.editNote.textChanged.connect(self.noteChanged)
layout_blobpanel = QVBoxLayout()
layout_blobpanel.addLayout(blobpanel_layoutH1)
layout_blobpanel.addLayout(blobpanel_layoutH2)
layout_blobpanel.addWidget(lblNote)
layout_blobpanel.addWidget(self.editNote)
groupbox_blobpanel.setLayout(layout_blobpanel)
# INFO WIDGET
self.infoWidget = QtInfoWidget(self)
# MAP VIEWER
self.mapviewer = QtMapViewer(self.MAP_VIEWER_SIZE)
self.mapviewer.setImage(None)
layout_labels = QVBoxLayout()
self.mapviewer.setStyleSheet("background-color: rgb(40,40,40); border:none")
layout_labels.addWidget(self.infoWidget)
layout_labels.addWidget(groupbox_labels)
layout_labels.addWidget(groupbox_blobpanel)
layout_labels.addStretch()
layout_labels.addWidget(self.mapviewer)
layout_labels.setAlignment(self.mapviewer, Qt.AlignHCenter)
##### MAIN LAYOUT
main_view_layout = QHBoxLayout()
main_view_layout.addLayout(layout_tools)
main_view_layout.addLayout(layout_viewer)
main_view_layout.addLayout(layout_labels)
main_view_layout.setStretchFactor(layout_viewer, 10)
main_view_layout.setStretchFactor(layout_labels, 1)
self.menubar = self.createMenuBar()
main_layout = QVBoxLayout()
#main_layout.addLayout(top_layout)
main_layout.addWidget(self.menubar)
main_layout.addLayout(main_view_layout)
self.setLayout(main_layout)
self.setProjectTitle("NONE")
##### FURTHER INITIALIZAION #####
#################################
self.map_top = 0
self.map_left = 0
self.map_bottom = 0
self.map_right = 0
# set default opacity
self.sliderTrasparency.setValue(50)
self.transparency_value = 0.5
self.img_map = None
self.img_thumb_map = None
self.img_overlay = QImage(16, 16, QImage.Format_RGB32)
# LOAD DEEP EXTREME NETWORK
self.loadingDeepExtremeNetwork()
# EVENTS
self.labels_widget.visibilityChanged.connect(self.updateVisibility)
self.mapviewer.leftMouseButtonPressed.connect(self.updateMainView)
self.mapviewer.mouseMoveLeftPressed.connect(self.updateMainView)
self.viewerplus.leftMouseButtonPressed.connect(self.toolsOpsLeftPressed)
self.viewerplus.leftMouseButtonReleased.connect(self.toolsOpsLeftReleased)
self.viewerplus.rightMouseButtonPressed.connect(self.toolsOpsRightPressed)
self.viewerplus.mouseMoveLeftPressed.connect(self.toolsOpsMouseMove)
self.viewerplus.leftMouseButtonDoubleClicked.connect(self.selectOp)
self.viewerplus.customContextMenuRequested.connect(self.openContextMenu)
self.current_selection = None
# DRAWING SETTINGS
self.BLOB_BORDER_WIDTH = 3
self.CROSS_LINE_WIDTH = 6
# DATA FOR THE SELECTION
self.selected_blobs = []
self.MAX_SELECTED = 5 # maximum number of selected blobs
# DATA FOR THE EDITBORDER TOOL
self.editborder_points = np.array(())
self.editborder_qpath = None
self.editborder_qpath_gitem = None
# DATA FOR THE FREEHAND TOOL
self.freehand_points = np.array(())
self.freehand_qpath = None
self.freehand_qpath_gitem = None
# DATA FOR THE CREATECRACK TOOL
self.crackWidget = None
# DATA FOR THE RULER TOOL
self.ruler_points_number = 0
self.ruler_points = np.zeros((2, 2))
self.ruler_lines = []
self.ruler_text_gi = None
# DATA FOR THE DEEP EXTREME TOOL
self.extreme_points_number = 0
self.extreme_points = np.zeros((4, 2))
self.extreme_points_lines = []
# a dirty trick to adjust all the size..
self.showMinimized()
self.showMaximized()
logfile.info("Inizialization finished!")
# autosave timer
self.timer = None
self.move()
def activateAutosave(self):
self.timer = QTimer(self)
self.timer.timeout.connect(self.autosave)
self.timer.start(180000) # save every 3 minute
@pyqtSlot()
def autosave(self):
self.save(self.project_name)
# call by pressing right button
def openContextMenu(self, position):
menu = QMenu(self)
menu.setAutoFillBackground(True)
str = "QMenu::item:selected{\
background-color: rgb(110, 110, 120);\
color: rgb(255, 255, 255);\
}"
menu.setStyleSheet(str)
assignAction = QAction("Assign Class", self)
assignAction.setShortcut(QKeySequence("A"))
assignAction.setShortcutVisibleInContextMenu(True)
menu.addAction(assignAction)
deleteAction = QAction("Delete Labels", self)
deleteAction.setShortcut(QKeySequence("Del"))
deleteAction.setShortcutVisibleInContextMenu(True)
menu.addAction(deleteAction)
menu.addSeparator()
mergeAction = QAction("Merge Overlapped Labels", self)
mergeAction.setShortcuts(QKeySequence("M"))
mergeAction.setShortcutVisibleInContextMenu(True)
menu.addAction(mergeAction)
divideAction = QAction("Divide Labels", self)
divideAction.setShortcut(QKeySequence("D"))
divideAction.setShortcutVisibleInContextMenu(True)
menu.addAction(divideAction)
subtractAction = QAction("Subtract Labels", self)
subtractAction.setShortcut(QKeySequence("S"))
subtractAction.setShortcutVisibleInContextMenu(True)
menu.addAction(subtractAction)
action = menu.exec_(self.viewerplus.mapToGlobal(position))
if action == deleteAction:
self.deleteSelected()
# elif action == groupAction:
# self.group()
# elif action == ungroupAction:
# self.ungroup()
elif action == mergeAction:
self.union()
elif action == divideAction:
self.divide()
elif action == subtractAction:
self.subtract()
elif action == assignAction:
self.assign()
def setProjectTitle(self, project_name):
title = "TagLab - [Project: " + project_name + "]"
self.setWindowTitle(title)
def clampCoords(self, x, y):
xc = int(x)
yc = int(y)
if xc < 0:
xc = 0
if yc < 0:
yc = 0
if xc > self.img_map.width():
xc = self.img_map.width()
if yc > self.img_map.height():
yc = self.img_map.height()
return (xc, yc)
def createMenuBar(self):
newAct = QAction("New Project", self)
#newAct.setShortcut('Ctrl+Q')
newAct.setStatusTip("Create a new project")
newAct.triggered.connect(self.newProject)
openAct = QAction("Open Project", self)
#openAct.setShortcut('Ctrl+Q')
openAct.setStatusTip("Open an existing project")
openAct.triggered.connect(self.openProject)
saveAct = QAction("Save Project", self)
#saveAct.setShortcut('Ctrl+Q')
saveAct.setStatusTip("Save current project")
saveAct.triggered.connect(self.saveProject)
# THIS WILL BECOME "ADD MAP" TO ADD MULTIPLE MAPS (e.g. depth, different years)
loadMapAct = QAction("Load Map", self)
#saveAct.setShortcut('Ctrl+Q')
loadMapAct.setStatusTip("Set and load a map")
loadMapAct.triggered.connect(self.setMapToLoad)
exportAct = QAction("Export Data", self)
#exportAct.setShortcut('Ctrl+Q')
exportAct.setStatusTip("Export data derived from annotations")
exportAct.triggered.connect(self.exportData)
helpAct = QAction("Help", self)
#exportAct.setShortcut('Ctrl+Q')
#helpAct.setStatusTip("Help")
helpAct.triggered.connect(self.help)
aboutAct = QAction("About", self)
#exportAct.setShortcut('Ctrl+Q')
#aboutAct.setStatusTip("About")
aboutAct.triggered.connect(self.about)
menubar = QMenuBar()
menubar.setAutoFillBackground(True)
styleMenuBar = "QMenuBar::item:selected{\
background-color: rgb(110, 110, 120);\
color: rgb(255, 255, 255);\
}"
styleMenu = "QMenu::item:selected{\
background-color: rgb(110, 110, 120);\
color: rgb(255, 255, 255);\
}"
menubar.setStyleSheet(styleMenuBar)
filemenu = menubar.addMenu("&File")
filemenu.setStyleSheet(styleMenu)
filemenu.addAction(newAct)
filemenu.addAction(openAct)
filemenu.addAction(saveAct)
filemenu.addSeparator()
filemenu.addAction(loadMapAct)
filemenu.addSeparator()
filemenu.addAction(exportAct)
helpmenu = menubar.addMenu("&Help")
helpmenu.setStyleSheet(styleMenu)
helpmenu.addAction(helpAct)
helpmenu.addAction(aboutAct)
return menubar
def keyPressEvent(self, event):
key_pressed = event.text()
str = "Key '" + key_pressed + "' has been pressed."
logfile.info(str)
if event.key() == Qt.Key_Escape:
# RESET CURRENT OPERATION
self.resetSelection()
if self.tool_used == "EDITBORDER":
self.resetEditBorder()
elif self.tool_used == "FREEHAND":
self.resetFreehand()
elif self.tool_used == "RULER":
self.resetRulerTool()
elif self.tool_used == "DEEPEXTREME":
self.resetDeepExtremeTool()
elif event.key() == Qt.Key_Delete:
# DELETE SELECTED BLOBS
self.deleteSelected()
elif event.key() == Qt.Key_M:
# MERGE BETWEEN TWO BLOBS
self.union()
elif event.key() == Qt.Key_S:
# SUBTRACTION BETWEEN TWO BLOBS (A = A / B), THEN BLOB B IS DELETED
self.subtract()
elif event.key() == Qt.Key_D:
# SUBTRACTION BETWEEN TWO BLOBS (A = A / B), BLOB B IS NOT DELETED
self.divide()
elif event.key() == Qt.Key_G:
# GROUP TOGETHER THE SELECTED BLOBS
self.group()
elif event.key() == Qt.Key_U:
# UNGROUP THE BLOBS OF A GROUP (ONE BLOB OF THE GROUP SHOULD BE SELECTED)
self.ungroup()
elif event.key() == Qt.Key_A:
# ACTIVATE "ASSIGN" TOOL
self.assign()
elif event.key() == Qt.Key_H:
# ACTIVATE THE "HOLE" TOOL
self.hole()
elif event.key() == Qt.Key_4:
# ACTIVATE "DEEP EXTREME" TOOL
self.deepExtreme()
elif event.key() == Qt.Key_P:
self.drawDeepExtremePoints()
elif event.key() == Qt.Key_Space:
# APPLY THE EDITBORDER OPERATION
if self.tool_used == "EDITBORDER":
logfile.info("EDITBORDER operations")
if len(self.selected_blobs) > 0:
logfile.info("EDITBORDER operations begins..")
selected_blob = self.selected_blobs[0]
pxs = utils.draw_open_polygon(self.editborder_points[:, 1], self.editborder_points[:, 0])
pts = np.asarray(pxs)
pts = pts.transpose()
pts[:, [1, 0]] = pts[:, [0, 1]]
new_points = selected_blob.snapToBorder(pts)
logfile.info("EDITBORDER operations not done (invalid snap).")
if new_points is not None:
selected_blob.addToMask(new_points)
selected_blob.cutFromMask(new_points)
logfile.info("EDITBORDER operations ends")
self.drawBlob(selected_blob, selected=True)
self.resetEditBorder()
# APPLY THE FREEHAND OPERATION
elif self.tool_used == "FREEHAND":
logfile.info("FREEHAND operation begins..")
pxs = utils.draw_open_polygon(self.freehand_points[:, 1], self.freehand_points[:, 0])
pts = np.asarray(pxs)
pts = pts.transpose()
pts[:, [1, 0]] = pts[:, [0, 1]]
# create an empty blob
blob = Blob(None, 0, 0, 0)
flagValid = blob.createFromClosedCurve(pts)
if flagValid is True:
logfile.info("FREEHAND operation ends.")
id = len(self.annotations.seg_blobs)
blob.setId(id + 1)
self.annotations.seg_blobs.append(blob)
self.resetSelection()
self.addToSelectedList(blob)
self.drawBlob(blob, selected=True)
else:
logfile.info("FREEHAND operation not done (invalid snap).")
self.resetFreehand()
# APPLY DEEP EXTREME (IF FOUR POINTS HAVE BEEN SELECTED)
elif self.tool_used == "DEEPEXTREME" and self.extreme_points_number == 4:
self.segmentWithDeepExtreme()
self.resetDeepExtremeTool()
@pyqtSlot()
def sliderTrasparencyChanged(self):
# update transparency value
newvalue = self.sliderTrasparency.value()
str1 = "Transparency {}%".format(newvalue)
self.lblSlider.setText(str1)
self.transparency_value = self.sliderTrasparency.value() / 100.0
# update transparency of all the blobs
self.applyTransparency()
def applyTransparency(self):
for blob in self.annotations.seg_blobs:
blob.qpath_gitem.setOpacity(self.transparency_value)
@pyqtSlot()
def updateVisibility(self):
for blob in self.annotations.seg_blobs:
visibility = self.labels_widget.isClassVisible(blob.class_name)
blob.qpath_gitem.setVisible(visibility)
@pyqtSlot()
def updateViewInfo(self):
zf = self.viewerplus.zoom_factor * 100.0
topleft = self.viewerplus.mapToScene(QPoint(0, 0))
bottomright = self.viewerplus.mapToScene(self.viewerplus.viewport().rect().bottomRight())
(left, top) = self.clampCoords(topleft.x(), topleft.y())
(right, bottom) = self.clampCoords(bottomright.x(), bottomright.y())
text = "| {:6.2f}% | top: {:4d} left: {:4d} bottom: {:4d} right: {:4d}".format(zf, top, left, bottom, right)
self.map_top = top
self.map_left = left
self.map_bottom = bottom
self.map_right = right
self.labelViewInfo.setText(text)
@pyqtSlot(float, float)
def updateMainView(self, x, y):
zf = self.viewerplus.zoom_factor
xmap = float(self.img_map.width()) * x
ymap = float(self.img_map.height()) * y
h = self.map_bottom - self.map_top
w = self.map_right - self.map_left
posx = xmap - w / 2
posy = ymap - h / 2
if posx < 0:
posx = 0
if posy < 0:
posy = 0
if posx + w/2 > self.img_map.width():
posx = self.img_map.width() - w / 2 - 1
if posy + h/2 > self.img_map.height():
posy = self.img_map.height() - h / 2 - 1
posx = posx * zf;
posy = posy * zf;
self.viewerplus.horizontalScrollBar().setValue(posx)
self.viewerplus.verticalScrollBar().setValue(posy)
@pyqtSlot()
def updateMapViewer(self):
topleft = self.viewerplus.mapToScene(QPoint(0, 0))
bottomright = self.viewerplus.mapToScene(self.viewerplus.viewport().rect().bottomRight())
W = float(self.img_map.width())
H = float(self.img_map.height())
top = float(topleft.y()) / H
left = float(topleft.x()) / W
bottom = float(bottomright.y()) / H
right = float(bottomright.x()) / W
self.mapviewer.drawOverlayImage(top, left, bottom, right)
def resetAll(self):
if self.img_map is not None:
del self.img_map
self.img_map = None
if self.img_thumb_map is not None:
del self.img_thumb_map
self.img_thumb_map = None
if self.annotations:
del self.annotations
self.annotations = Annotation()
# RE-INITIALIZATION
self.mapWidget = None
self.project_name = "NONE"
self.map_image_filename = "map.png"
self.map_acquisition_date = "YYYY-MM-DD"
self.map_px_to_mm_factor = 1.0
def resetToolbar(self):
self.btnMove.setChecked(False)
self.btnAssign.setChecked(False)
self.btnEditBorder.setChecked(False)
self.btnFreehand.setChecked(False)
self.btnRuler.setChecked(False)
self.btnCreateCrack.setChecked(False)
self.btnDeepExtreme.setChecked(False)
@pyqtSlot()
def move(self):
"""
Activate the tool "move".
"""
self.resetToolbar()
self.resetTools()
self.btnMove.setChecked(True)
self.tool_used = "MOVE"
self.viewerplus.enablePan()
self.viewerplus.enableZoom()
logfile.info("MOVE tool is active")
@pyqtSlot()
def createCrack(self):
"""
Activate the tool "Create Crack".
"""
self.resetToolbar()
self.resetTools()
self.btnCreateCrack.setChecked(True)
self.tool_used = "CREATECRACK"
self.viewerplus.enablePan()
self.viewerplus.enableZoom()
logfile.info("CREATECRACK tool is active")
@pyqtSlot(float, float)
def selectOp(self, x, y):
"""
Selection operation.
"""
# NOTE: double click selection is disabled with ASSIGN, RULER and DEEPEXTREME tools
if not self.tool_used == "ASSIGN" and not self.tool_used == "RULER" and not self.tool_used == "DEEPEXTREME" :
selected_blob = self.annotations.clickedBlob(x, y)
modifiers = QApplication.queryKeyboardModifiers()
if selected_blob:
if len(self.selected_blobs) == 0:
self.addToSelectedList(selected_blob)
self.drawSelectedBlobs()
self.updatePanelInfo(selected_blob)
elif len(self.selected_blobs) > 0:
if not (modifiers & Qt.ShiftModifier):
self.resetSelection()
self.addToSelectedList(selected_blob)
self.drawSelectedBlobs()
self.updatePanelInfo(selected_blob)
else:
self.resetSelection()
@pyqtSlot()
def assign(self):
"""
Activate the tool "Assign" to assign a class to an existing blob.
"""
self.resetToolbar()
self.resetTools()
self.btnAssign.setChecked(True)
self.tool_used = "ASSIGN"
self.viewerplus.disablePan()
self.viewerplus.enableZoom()
logfile.info("ASSIGN tool is active")
@pyqtSlot()
def editBorder(self):
"""
Activate the tool "EDITBORDER" for pixel-level editing operations.
NOTE: it works one blob at a time (!)
"""
self.resetToolbar()
self.resetTools()
if len(self.selected_blobs) > 1:
self.resetSelection()
self.btnEditBorder.setChecked(True)
self.tool_used = "EDITBORDER"
pen = QPen(Qt.black)
pen.setWidth(self.BLOB_BORDER_WIDTH)
self.editborder_qpath = QPainterPath()
self.editborder_qpath_gitem = self.viewerplus.scene.addPath(self.editborder_qpath, pen, QBrush())
self.viewerplus.disablePan()
self.viewerplus.enableZoom()
logfile.info("EDITBORDER tool is active")
@pyqtSlot()
def freehandSegmentation(self):
"""
Activate the tool "FREEHAND" for manual segmentation.
"""
self.resetToolbar()
self.resetTools()
self.resetSelection()