-
Notifications
You must be signed in to change notification settings - Fork 53
/
annotator.py
1417 lines (1255 loc) · 49.8 KB
/
annotator.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
import sys
import functools
import cv2
import glob
import os
import os.path as osp
import imgviz
import html
import json
import math
import argparse
import numpy as np
import tempfile
import torch
import base64
from PyQt5.QtWidgets import QWidget, QApplication, QMainWindow, QApplication, QPushButton, QLabel, QFileDialog, QProgressBar, QComboBox, QScrollArea, QDockWidget, QMessageBox
from PyQt5.QtGui import QPixmap, QIcon, QImage
from PyQt5.Qt import QSize
from qtpy.QtCore import Qt
from qtpy import QtCore
from qtpy import QtGui, QtWidgets
from canvas import Canvas
import utils
from utils.download_model import download_model
from labelme.widgets import ToolBar, UniqueLabelQListWidget, LabelDialog, LabelListWidget, LabelListWidgetItem, ZoomWidget
from labelme import PY2
from labelme.label_file import LabelFile
from labelme.label_file import LabelFileError
from shape import Shape
from PIL import Image
from collections import namedtuple
Click = namedtuple('Click', ['is_positive', 'coords'])
from segment_anything import sam_model_registry, SamPredictor
LABEL_COLORMAP = imgviz.label_colormap()
class MainWindow(QMainWindow):
FIT_WINDOW, FIT_WIDTH, MANUAL_ZOOM = 0, 1, 2
def __init__(self, parent=None, global_w=1000, global_h=1800, model_type='vit_b', keep_input_size=True, max_size=1080):
super(MainWindow, self).__init__(parent)
self.resize(global_w, global_h)
self.model_type = model_type
self.keep_input_size = keep_input_size
self.max_size = float(max_size)
self.setWindowTitle('segment-anything-annotator')
self.canvas = Canvas(self,
epsilon=10.0,
double_click='close',
num_backups=10,
app=self,
)
self._noSelectionSlot = False
self.current_output_dir = 'output'
os.makedirs(self.current_output_dir, exist_ok=True)
self.current_output_filename = ''
self.canvas.zoomRequest.connect(self.zoomRequest)
self.memory_shapes = []
self.sam_mask = []
self.sam_mask_proposal = []
self.image_encoded_flag = False
self.min_point_dis = 4
self.predictor = None
self.scroll_values = {
Qt.Horizontal: {},
Qt.Vertical: {},
}
self.scrollArea = QScrollArea(self)
self.scrollArea.setWidget(self.canvas)
self.scrollArea.setWidgetResizable(True)
self.scrollBars = {
Qt.Vertical: self.scrollArea.verticalScrollBar(),
Qt.Horizontal: self.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.uniqLabelList = UniqueLabelQListWidget()
self.uniqLabelList.setToolTip(
self.tr(
"Select label to start annotating for it. "
"Press 'Esc' to deselect."
)
)
self.labelDialog = LabelDialog(
parent=self,
labels=[],
sort_labels=False,
show_text_field=True,
completion='contains',
fit_to_content={'column': True, 'row': False},
)
self.labelList = LabelListWidget()
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 = QDockWidget(
self.tr("Polygon Labels"), self
)
self.shape_dock.setObjectName("Labels")
self.shape_dock.setWidget(self.labelList)
self.category_list = [i.strip() for i in open('categories.txt', 'r', encoding='utf-8').readlines()]
self.labelDialog = LabelDialog(
parent=self,
labels=self.category_list,
sort_labels=False,
show_text_field=True,
completion='contains',
fit_to_content={'column': True, 'row': False},
)
self.zoom_values = {}
self.video_directory = ''
self.video_list = []
self.video_len = len(self.video_list)
self.img_list = []
self.img_len = len(self.img_list)
self.current_img_index = 0
self.current_img = ''
self.current_img_data = ''
self.button_next = QPushButton('Next Image', self)
self.button_next.clicked.connect(self.clickButtonNext)
self.button_last = QPushButton('Last Image', self)
self.button_last.clicked.connect(self.clickButtonLast)
self.img_progress_bar = QProgressBar(self)
self.img_progress_bar.setMinimum(0)
self.img_progress_bar.setMaximum(1)
self.img_progress_bar.setValue(0)
self.button_proposal1 = QPushButton('Proposal1', self)
self.button_proposal1.clicked.connect(self.choose_proposal1)
self.button_proposal1.setShortcut('1')
self.button_proposal2 = QPushButton('Proposal2', self)
self.button_proposal2.clicked.connect(self.choose_proposal2)
self.button_proposal2.setShortcut('2')
self.button_proposal3 = QPushButton('Proposal3', self)
self.button_proposal3.clicked.connect(self.choose_proposal3)
self.button_proposal3.setShortcut('3')
self.button_proposal4 = QPushButton('Proposal4', self)
self.button_proposal4.clicked.connect(self.choose_proposal4)
self.button_proposal4.setShortcut('4')
self.button_proposal_list = [self.button_proposal1, self.button_proposal2, self.button_proposal3, self.button_proposal4]
self.class_on_flag = True
self.class_on_text = QLabel("Class On", self)
#naive layout
self.scrollArea.move(int(0.02 * global_w), int(0.08 * global_h))
self.scrollArea.resize(int(0.75 * global_w), int(0.7 * global_h))
self.shape_dock.move(int(0.79 * global_w), int(0.08 * global_h))
self.shape_dock.resize(int(0.2 * global_w), int(0.7 * global_h))
self.button_next.move(int(0.18 * global_w), int(0.85 * global_h))
self.button_next.resize(int(0.1 * global_w),int(0.04 * global_h))
self.button_last.move(int(0.01 * global_w), int(0.85 * global_h))
self.button_last.resize(int(0.1 * global_w),int(0.04 * global_h))
self.class_on_text.move(int(0.01 * global_w), int(0.9 * global_h))
self.img_progress_bar.move(int(0.01 * global_w), int(0.8 * global_h))
self.img_progress_bar.resize(int(0.3 * global_w),int(0.04 * global_h))
self.button_proposal1.resize(int(0.17 * global_w),int(0.14 * global_h))
self.button_proposal1.move(int(0.33 * global_w), int(0.8 * global_h))
self.button_proposal2.resize(int(0.17 * global_w),int(0.14 * global_h))
self.button_proposal2.move(int(0.50 * global_w), int(0.8 * global_h))
self.button_proposal3.resize(int(0.17 * global_w),int(0.14 * global_h))
self.button_proposal3.move(int(0.67 * global_w), int(0.8 * global_h))
self.button_proposal4.resize(int(0.17 * global_w),int(0.14 * global_h))
self.button_proposal4.move(int(0.84 * global_w), int(0.8 * global_h))
self.zoomWidget = ZoomWidget()
action = functools.partial(utils.newAction, self)
categoryFile = action(
self.tr("Category File"),
lambda: self.clickCategoryChoose(),
'None',
"objects",
self.tr("Category File"),
enabled=True,
)
imageDirectory = action(
self.tr("Image Directory"),
lambda: self.clickFileChoose(),
'None',
"objects",
self.tr("Image Directory"),
enabled=True,
)
LoadSAM = action(
self.tr("Load SAM"),
lambda: self.clickLoadSAM(),
'None',
"objects",
self.tr("Load SAM"),
enabled=True,
)
AutoSeg = action(
self.tr("AutoSeg"),
lambda: self.clickAutoSeg(),
'None',
"objects",
self.tr("AutoSeg"),
enabled=False,
)
promptSeg = action(
self.tr("Accept"),
lambda: self.addSamMask(),
'a',
"objects",
self.tr("Accept"),
enabled=False,
)
saveDirectory = action(
self.tr("Save Directory"),
lambda: self.clickSaveChoose(),
'None',
"objects",
self.tr("Save Directory"),
enabled=True,
)
createMode = action(
self.tr("Manual Polygons"),
lambda: self.toggleDrawMode(False, createMode="polygon"),
'Ctrl+W',
"objects",
self.tr("Start drawing polygons"),
enabled=True,
)
createPointMode = action(
self.tr("Point Prompt"),
lambda: self.toggleDrawMode(False, createMode="point"),
'None',
"objects",
self.tr("Point Prompt"),
enabled=True,
)
createRectangleMode = action(
self.tr("Box Prompt"),
lambda: self.toggleDrawMode(False, createMode="rectangle"),
'None',
"objects",
self.tr("Box Prompt"),
enabled=True,
)
cleanPrompt = action(
self.tr("Reject"),
lambda: self.cleanPrompt(),
'r',
"objects",
self.tr("Reject"),
enabled=True,
)
self.switchClass = action(
self.tr("Class On/Off"),
lambda: self.clickSwitchClass(),
'none',
"objects",
self.tr("Class On/Off"),
enabled=True,
)
editMode = action(
self.tr("Edit Polygons"),
self.setEditMode,
'None',
"edit",
self.tr("Move and edit the selected polygons"),
enabled=False,
)
saveAs = action(
self.tr("&Save As"),
self.saveFileAs,
'ALT+s',
"save-as",
self.tr("Save labels to a different file"),
enabled=True,
)
undoLastPoint = action(
self.tr("Undo last point"),
self.canvas.undoLastPoint,
'U',
"undo",
self.tr("Undo last drawn point"),
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,
)
undo = action(
self.tr("Undo"),
self.undoShapeEdit,
'Ctrl+U',
"undo",
self.tr("Undo last add and edit of shape"),
enabled=False,
)
save = action(
self.tr("&Save"),
self.saveFile,
'S',
"save",
self.tr("Save labels to file"),
enabled=False,
)
delete = action(
self.tr("Delete Polygons"),
self.deleteSelectedShape,
'd',
"cancel",
self.tr("Delete the selected polygons"),
enabled=False,
)
duplicate = action(
self.tr("Duplicate Polygons"),
self.duplicateSelectedShape,
'None',
"copy",
self.tr("Create a duplicate of the selected polygons"),
enabled=False,
)
reduce_point = action(
self.tr("Reduce Points"),
self.reducePoint,
'None',
"copy",
self.tr("Reduce Points"),
enabled=True,
)
edit = action(
self.tr("&Edit Label"),
self.editLabel,
'None',
"edit",
self.tr("Modify the label of the selected polygon"),
enabled=False,
)
self.actions = utils.struct(
categoryFile=categoryFile,
imageDirectory=imageDirectory,
saveDirectory=saveDirectory,
switchClass=self.switchClass,
loadSAM=LoadSAM,
#autoSeg=AutoSeg,
promptSeg=promptSeg,
cleanPrompt=cleanPrompt,
createMode=createMode,
createPointMode=createPointMode,
createRectangleMode=createRectangleMode,
editMode=editMode,
undoLastPoint=undoLastPoint,
undo=undo,
delete=delete,
edit=edit,
duplicate=duplicate,
reduce_point=reduce_point,
save=save,
onShapesPresent=(saveAs, hideAll, showAll),
menu=(
createMode,
editMode,
undoLastPoint,
undo,
save,
)
)
# 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.toolbar = self.addToolBar('Tool')
self.toolbar.addAction(categoryFile)
self.toolbar.addAction(imageDirectory)
self.toolbar.addAction(saveDirectory)
self.toolbar.addAction(self.switchClass)
self.toolbar.addAction(LoadSAM)
#self.toolbar.addAction(AutoSeg)
self.toolbar.addAction(promptSeg)
self.toolbar.addAction(cleanPrompt)
self.toolbar.addAction(createMode)
self.toolbar.addAction(createPointMode)
self.toolbar.addAction(createRectangleMode)
self.toolbar.addAction(editMode)
self.toolbar.addAction(undoLastPoint)
self.toolbar.addAction(undo)
self.toolbar.addAction(delete)
self.toolbar.addAction(edit)
self.toolbar.addAction(duplicate)
self.toolbar.addAction(reduce_point)
self.toolbar.addAction(save)
self.toolbar.setToolButtonStyle(Qt.ToolButtonTextOnly)
zoom = QtWidgets.QWidgetAction(self)
zoom.setDefaultWidget(self.zoomWidget)
self.zoomWidget.setWhatsThis(
str(
self.tr(
"Zoom in or out of the image. Also accessible with "
"{} from the canvas."
)
).format(
#utils.fmtShortcut(
# "{},{}".format(shortcuts["zoom_in"], shortcuts["zoom_out"])
#),
utils.fmtShortcut(self.tr("Ctrl+Wheel")),
)
)
self.zoomWidget.setEnabled(True)
self.zoomWidget.valueChanged.connect(self.paintCanvas)
self.canvas.actions = self.actions
def saveFileAs(self, _value=False):
assert not self.image.isNull(), "cannot save empty image"
self._saveFile(self.saveFileDialog())
def saveFile(self, _value=False):
# assert not self.image.isNull(), "cannot save empty image"
# if self.labelFile:
# # DL20180323 - overwrite when in directory
# self._saveFile(self.labelFile.filename)
# elif self.output_file:
# self._saveFile(self.output_file)
# self.close()
# else:
# self._saveFile(self.saveFileDialog())
#self._saveFile(self.saveFileDialog())
#print(self.current_output_filename)
self._saveFile(self.current_output_filename)
def _saveFile(self, filename):
if filename and self.saveLabels(filename):
self.setClean()
def saveLabels(self, filename):
lf = LabelFile()
def format_shape(s):
data = s.other_data.copy()
data.update(
dict(
label=s.label.encode("utf-8") if PY2 else s.label,
points=[[p.x(), p.y()] for p in s.points],
group_id=s.group_id,
description="",
shape_type=s.shape_type,
flags=s.flags,
)
)
return data
shapes = [format_shape(item.shape()) for item in self.labelList]
imageData = base64.b64encode(self.current_img_data).decode("utf-8")
save_data = {
"version": "1.0.0",
"flags": {},
"shapes": shapes,
"imagePath": self.current_img,
"imageData": imageData,
"imageHeight": self.raw_h,
"imageWidth": self.raw_w
}
with open(filename, 'w') as f:
json.dump(save_data, f)
return True
def setClean(self):
self.dirty = False
self.actions.save.setEnabled(False)
self.actions.createMode.setEnabled(True)
def saveFileDialog(self):
caption = self.tr("Choose File")
filters = self.tr("Label files")
if self.output_dir:
dlg = QtWidgets.QFileDialog(
self, caption, self.output_dir, filters
)
else:
dlg = QtWidgets.QFileDialog(
self, caption, self.currentPath(), filters
)
dlg.setDefaultSuffix(LabelFile.suffix[1:])
dlg.setAcceptMode(QtWidgets.QFileDialog.AcceptSave)
dlg.setOption(QtWidgets.QFileDialog.DontConfirmOverwrite, False)
dlg.setOption(QtWidgets.QFileDialog.DontUseNativeDialog, False)
basename = os.path.basename(self.current_img)[:-4]
if self.output_dir:
default_labelfile_name = osp.join(
self.output_dir, basename + LabelFile.suffix
)
else:
default_labelfile_name = osp.join(
self.currentPath(), basename + LabelFile.suffix
)
filename = dlg.getSaveFileName(
self,
self.tr("Choose File"),
default_labelfile_name,
self.tr("Label files (*%s)") % LabelFile.suffix,
)
if isinstance(filename, tuple):
filename, _ = filename
return filename
def currentPath(self):
#return osp.dirname(str(self.filename)) if self.filename else "."
return "."
def loadAnno(self, filename):
with open(filename,'r') as f:
data = json.load(f)
for shape in data['shapes']:
label = shape["label"]
try:
ttt = int(label)
label = self.category_list[ttt]
except:
pass
points = shape["points"]
shape_type = shape["shape_type"]
flags = shape["flags"]
group_id = shape["group_id"]
if not points:
# skip point-empty shape
continue
shape = Shape(
label=label,
shape_type=shape_type,
group_id=group_id,
flags=flags
)
for x, y in points:
shape.addPoint(QtCore.QPointF(x, y))
shape.close()
self.addLabel(shape)
self.canvas.loadShapes([item.shape() for item in self.labelList])
def clickButtonNext(self):
if self.actions.save.isEnabled():
self.saveFile()
if self.current_img_index < self.img_len - 1:
self.current_img_index += 1
self.current_img = self.img_list[self.current_img_index]
self.loadImg()
def clickButtonLast(self):
if self.actions.save.isEnabled():
self.saveFile()
if self.current_img_index > 0:
self.current_img_index -= 1
self.current_img = self.img_list[self.current_img_index]
self.loadImg()
def choose_proposal1(self):
if len(self.sam_mask_proposal) > 0:
self.sam_mask = self.sam_mask_proposal[0]
self.canvas.setHiding()
self.canvas.update()
def choose_proposal2(self):
if len(self.sam_mask_proposal) > 1:
self.sam_mask = self.sam_mask_proposal[1]
self.canvas.setHiding()
self.canvas.update()
def choose_proposal3(self):
if len(self.sam_mask_proposal) > 2:
self.sam_mask = self.sam_mask_proposal[2]
self.canvas.setHiding()
self.canvas.update()
def choose_proposal4(self):
if len(self.sam_mask_proposal) > 3:
self.sam_mask = self.sam_mask_proposal[3]
self.canvas.setHiding()
self.canvas.update()
def loadImg(self):
self.raw_h, self.raw_w = cv2.imread(self.current_img).shape[:2]
pixmap = QPixmap(self.current_img)
#pixmap = pixmap.scaled(int(0.75 * global_w), int(0.7 * global_h))
self.canvas.loadPixmap(pixmap)
self.img_progress_bar.setValue(self.current_img_index)
img_name = os.path.basename(self.current_img)[:-4]
self.current_output_filename = osp.join(self.current_output_dir, img_name + '.json')
self.labelList.clear()
if os.path.isfile(self.current_output_filename):
self.loadAnno(self.current_output_filename)
self.image_encoded_flag = False
self.current_img_data = LabelFile.load_image_file(self.current_img)
def clickFileChoose(self):
directory = QFileDialog.getExistingDirectory(self, 'choose target fold','.')
if directory == '':
return
#self.img_list = glob.glob(directory + '/*.{jpg,png,JPG,PNG}')
self.img_list = glob.glob(directory + '/*.jpg') + glob.glob(directory + '/*.png')
self.img_list.sort()
self.img_len = len(self.img_list)
if self.img_len == 0:
return
self.current_img_index = 0
self.current_img = self.img_list[self.current_img_index]
self.img_progress_bar.setMinimum(0)
self.img_progress_bar.setMaximum(self.img_len-1)
self.loadImg()
def clickSaveChoose(self):
directory = QFileDialog.getExistingDirectory(self, 'choose target fold','.')
if directory == '':
return
else:
self.current_output_dir = directory
os.makedirs(self.current_output_dir, exist_ok=True)
self.loadImg()
return directory
def clickSwitchClass(self):
if self.class_on_flag:
self.class_on_flag = False
self.class_on_text.setText('Class Off')
else:
self.class_on_flag = True
self.class_on_text.setText('Class On')
def clickCategoryChoose(self):
filename, _ = QFileDialog.getOpenFileName(self, 'choose target file','.')
try:
with open(filename, 'r') as f:
data = f.readlines()
self.category_list = [i.strip() for i in data]
self.category_list.sort()
self.labelDialog = LabelDialog(
parent=self,
labels=self.category_list,
sort_labels=False,
show_text_field=True,
completion='contains',
fit_to_content={'column': True, 'row': False},
)
except Exception as e:
pass
def clickLoadSAM(self):
download_model(self.model_type)
self.sam = sam_model_registry[self.model_type](checkpoint='{}.pth'.format(self.model_type))
self.device = "cuda" if torch.cuda.is_available() else "cpu"
self.sam.to(device=self.device)
self.predictor = SamPredictor(self.sam)
self.actions.loadSAM.setEnabled(False)
#self.actions.autoSeg.setEnabled(True)
self.actions.promptSeg.setEnabled(True)
def clickAutoSeg(self):
pass
def getMaxId(self):
max_id = -1
for label in self.labelList:
if label.shape().group_id != None:
max_id = max(max_id, int(label.shape().group_id))
return max_id
def show_proposals(self, masks=None, flag=1):
if flag != 1:
img = cv2.imread(self.current_img)
if len(img.shape) == 2:
img = cv2.cvtColor(img, cv2.COLOR_GRAY2BGR)
img = cv2.cvtColor(img, cv2.COLOR_BGR2RGB)
for msk_idx in range(masks.shape[0]):
tmp_mask = masks[msk_idx]
tmp_vis = img.copy()
tmp_vis[tmp_mask > 0] = 0.5 * tmp_vis[tmp_mask > 0] + 0.5 * np.array([30,30,220])
tmp_vis = cv2.resize(tmp_vis,(int(0.17 * global_w),int(0.14 * global_h)))
tmp_vis = tmp_vis.astype(np.uint8)
pixmap = QPixmap.fromImage(QImage(tmp_vis, tmp_vis.shape[1], tmp_vis.shape[0], tmp_vis.shape[1] * 3 , QImage.Format_RGB888))
#self.button_proposal_list[msk_idx].setPixmap(pixmap)
self.button_proposal_list[msk_idx].setIcon(QIcon(pixmap))
self.button_proposal_list[msk_idx].setIconSize(QSize(tmp_vis.shape[1], tmp_vis.shape[0]))
self.button_proposal_list[msk_idx].setShortcut(str(msk_idx+1))
else:
for idx, button_proposal in enumerate(self.button_proposal_list):
button_proposal.setText('proprosal{}'.format(idx))
button_proposal.setIconSize(QSize(0,0))
self.button_proposal_list[idx].setShortcut(str(idx+1))
def transform_input(self, image, box=None, points=None):
if self.keep_input_size == True:
return image, box, points
else:
h,w = image.shape[:2]
scale_ratio = self.max_size / max(h,w)
image = cv2.resize(image, (int(w*scale_ratio), int(h*scale_ratio)))
if box is not None:
box = box * scale_ratio
if points is not None:
points = points * scale_ratio
return image, box, points
def transform_output(self, masks, size):
if self.keep_input_size == True:
return masks
else:
h,w = size
N = masks.shape[0]
new_masks = np.zeros((N,h,w), dtype=np.uint8)
for idx in range(N):
new_masks[idx] = cv2.resize(masks[idx], (w,h))
return new_masks
def clickManualSegBBox(self):
Box = self.canvas.currentBox
if self.predictor is None or self.current_img == '' or Box == None:
return
img = cv2.imread(self.current_img)[:,:,::-1]
rh, rw = img.shape[:2]
input_box = np.array([Box[0].x(), Box[0].y(), Box[1].x(), Box[1].y()])
img, input_box, _ = self.transform_input(img, box=input_box)
if self.image_encoded_flag == False:
self.predictor.set_image(img)
self.image_encoded_flag = True
masks, iou_prediction, _ = self.predictor.predict(
point_coords=None,
point_labels=None,
box=input_box[None, :],
multimask_output=True,
)
masks = self.transform_output(masks.astype(np.uint8), (rh,rw))
target_idx = np.argmax(iou_prediction)
self.show_proposals(masks, 0)
self.sam_mask_proposal = []
for msk_idx in range(masks.shape[0]):
mask = masks[msk_idx].astype(np.uint8)
points_list = cv2.findContours(mask, cv2.RETR_TREE, cv2.CHAIN_APPROX_SIMPLE)[0]
shape_type = 'polygon'
tmp_sam_mask = []
for points in points_list:
area = cv2.contourArea(points)
if area < 100 and len(points_list) > 1:
continue
pointsx = points[:,0,0]
pointsy = points[:,0,1]
shape = Shape(
label='Object',
shape_type=shape_type,
group_id=self.getMaxId() + 1,
)
for point_index in range(pointsx.shape[0]):
shape.addPoint(QtCore.QPointF(pointsx[point_index], pointsy[point_index]))
shape.close()
#self.addLabel(shape)
tmp_sam_mask.append(shape)
if msk_idx == target_idx:
self.sam_mask = tmp_sam_mask
self.sam_mask_proposal.append(tmp_sam_mask)
def clickManualSegBox(self):
ClickPos = self.canvas.currentPos
ClickNeg = self.canvas.currentNeg
if self.predictor is None or self.current_img == '' or (ClickPos == None and ClickNeg == None):
return
img = cv2.imread(self.current_img)[:,:,::-1]
rh, rw = img.shape[:2]
input_clicks = []
input_types = []
if ClickPos != None:
for pos in ClickPos:
input_clicks.append([int(pos.x()), int(pos.y())])
input_types.append(1)
if ClickNeg != None:
for neg in ClickNeg:
input_clicks.append([int(neg.x()), int(neg.y())])
input_types.append(0)
if len(input_clicks) == 0:
input_clicks = None
input_types = None
else:
input_clicks = np.array(input_clicks)
input_types = np.array(input_types)
img, _, input_clicks = self.transform_input(img, points=input_clicks)
if self.image_encoded_flag == False:
self.predictor.set_image(img)
self.image_encoded_flag = True
masks, iou_prediction, _ = self.predictor.predict(
point_coords=input_clicks,
point_labels=input_types,
multimask_output=True,
)
masks = self.transform_output(masks.astype(np.uint8), (rh,rw))
target_idx = np.argmax(iou_prediction)
self.show_proposals(masks,0)
self.sam_mask_proposal = []
for msk_idx in range(masks.shape[0]):
mask = masks[msk_idx].astype(np.uint8)
points_list = cv2.findContours(mask, cv2.RETR_TREE, cv2.CHAIN_APPROX_SIMPLE)[0]
shape_type = 'polygon'
tmp_sam_mask = []
for points in points_list:
area = cv2.contourArea(points)
if area < 100 and len(points_list) > 1:
continue
pointsx = points[:,0,0]
pointsy = points[:,0,1]
shape = Shape(
label='Object',
shape_type=shape_type,
group_id=self.getMaxId() + 1,
)
for point_index in range(pointsx.shape[0]):
shape.addPoint(QtCore.QPointF(pointsx[point_index], pointsy[point_index]))
shape.close()
#self.addLabel(shape)
tmp_sam_mask.append(shape)
if msk_idx == target_idx:
self.sam_mask = tmp_sam_mask
self.sam_mask_proposal.append(tmp_sam_mask)
def addSamMask(self):
if len(self.sam_mask) > 0:
label = 'Object'
group_id = self.getMaxId() + 1
if self.class_on_flag:
xx = self.labelDialog.popUp(
text=label,
flags={},
group_id=group_id,
)
if len(xx) == 4:
label, _, group_id,_ = xx
else:
label, _, group_id = xx
if label == None:
label = 'Object'
if type(group_id) != int:
group_id=self.getMaxId() + 1
for sam_mask in self.sam_mask:
sam_mask.label = label
sam_mask.group_id = group_id
self.addLabel(sam_mask)
self.canvas.currentBox = None
self.canvas.currentPos = None
self.canvas.currentNeg = None
self.sam_mask = []
self.sam_mask_proposal = []
self.show_proposals()
self.canvas.loadShapes([item.shape() for item in self.labelList])
self.actions.save.setEnabled(True)
self.actions.editMode.setEnabled(True)
def cleanPrompt(self):
self.canvas.currentBox = None
self.canvas.currentPos = None
self.canvas.currentNeg = None
self.canvas.current = None
self.sam_mask = []
self.sam_mask_proposal = []
self.show_proposals()
self.canvas.setHiding()
self.canvas.update()
self.actions.editMode.setEnabled(True)
def zoomRequest(self, delta, pos):
canvas_width_old = self.canvas.width()
units = 1.1
if delta < 0:
units = 0.9
self.addZoom(units)
canvas_width_new = self.canvas.width()
if canvas_width_old != canvas_width_new:
canvas_scale_factor = canvas_width_new / canvas_width_old
x_shift = round(pos.x() * canvas_scale_factor) - pos.x()
y_shift = round(pos.y() * canvas_scale_factor) - pos.y()
self.setScroll(
Qt.Horizontal,
self.scrollBars[Qt.Horizontal].value() + x_shift,
)
self.setScroll(
Qt.Vertical,
self.scrollBars[Qt.Vertical].value() + y_shift,
)
def scrollRequest(self, delta, orientation):
units = -delta * 0.1 # natural scroll
bar = self.scrollBars[orientation]
value = bar.value() + bar.singleStep() * units
self.setScroll(orientation, value)
def newShape(self):
"""Pop-up and give focus to the label editor.
position MUST be in global coordinates.
"""
items = self.uniqLabelList.selectedItems()
text = None
if items:
text = items[0].data(Qt.UserRole)
flags = {}
group_id = None
if not text:
previous_text = self.labelDialog.edit.text()
xx = self.labelDialog.popUp(text)
if len(xx) == 4:
text, flags, group_id, _ = xx
else:
text, flags, group_id = xx
if not text:
self.labelDialog.edit.setText(previous_text)
if text and not self.validateLabel(text):
self.errorMessage(
self.tr("Invalid label"),
self.tr("Invalid label '{}' with validation type '{}'").format(
text, self._config["validate_label"]
),
)