forked from haochenheheda/segment-anything-annotator
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathcanvas.py
1209 lines (1097 loc) · 46.2 KB
/
canvas.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
from qtpy import QtCore
from qtpy import QtGui
from qtpy import QtWidgets
from labelme import QT5
from shape import Shape
import labelme.utils
from collections import namedtuple
import cv2
import numpy as np
import torch
# TODO(unknown):
# - [maybe] Find optimal epsilon value.
CURSOR_DEFAULT = QtCore.Qt.ArrowCursor
CURSOR_POINT = QtCore.Qt.PointingHandCursor
CURSOR_DRAW = QtCore.Qt.CrossCursor
CURSOR_MOVE = QtCore.Qt.ClosedHandCursor
CURSOR_GRAB = QtCore.Qt.OpenHandCursor
MOVE_SPEED = 5.0
Click = namedtuple('Click', ['is_positive', 'coords'])
class Canvas(QtWidgets.QWidget):
zoomRequest = QtCore.Signal(int, QtCore.QPoint)
scrollRequest = QtCore.Signal(int, int)
newShape = QtCore.Signal()
selectionChanged = QtCore.Signal(list)
shapeMoved = QtCore.Signal()
drawingPolygon = QtCore.Signal(bool)
vertexSelected = QtCore.Signal(bool)
CREATE, EDIT = 0, 1
# polygon, rectangle, line, or point
_createMode = "polygon"
_fill_drawing = False
def __init__(self, *args, **kwargs):
self.epsilon = kwargs.pop("epsilon", 10.0)
self.double_click = kwargs.pop("double_click", "close")
if self.double_click not in [None, "close"]:
raise ValueError(
"Unexpected value for double_click event: {}".format(
self.double_click
)
)
self.num_backups = kwargs.pop("num_backups", 10)
self._crosshair = kwargs.pop(
"crosshair",
{
"polygon": False,
"rectangle": True,
"circle": False,
"line": False,
"point": False,
"linestrip": False,
},
)
self.app = kwargs.pop("app", None)
super(Canvas, self).__init__(*args, **kwargs)
# Initialise local state.
self.mode = self.EDIT
self.shapes = []
self.shapesBackups = []
self.current = None
self.currentPos = None
self.currentNeg = None
self.currentBox = None
self.selectedShapes = [] # save the selected shapes here
self.selectedShapesCopy = []
# self.line represents:
# - createMode == 'polygon': edge from last point to current
# - createMode == 'rectangle': diagonal line of the rectangle
# - createMode == 'line': the line
# - createMode == 'point': the point
self.line = Shape()
self.prevPoint = QtCore.QPoint()
self.prevMovePoint = QtCore.QPoint()
self.offsets = QtCore.QPoint(), QtCore.QPoint()
self.scale = 1
self.pixmap = QtGui.QPixmap()
self.visible = {}
self._hideBackround = False
self.hideBackround = False
self.hShape = None
self.prevhShape = None
self.hVertex = None
self.prevhVertex = None
self.hEdge = None
self.prevhEdge = None
self.movingShape = False
self.snapping = True
self.hShapeIsSelected = False
self._painter = QtGui.QPainter()
self._cursor = CURSOR_DEFAULT
# Menus:
# 0: right-click without selection and dragging of shapes
# 1: right-click with selection and dragging of shapes
self.menus = (QtWidgets.QMenu(), QtWidgets.QMenu())
# Set widget options.
self.setMouseTracking(True)
self.setFocusPolicy(QtCore.Qt.WheelFocus)
def fillDrawing(self):
return self._fill_drawing
def setFillDrawing(self, value):
self._fill_drawing = value
@property
def createMode(self):
return self._createMode
@createMode.setter
def createMode(self, value):
if value not in [
"polygon",
"rectangle",
"circle",
"line",
"point",
"linestrip",
]:
raise ValueError("Unsupported createMode: %s" % value)
self._createMode = value
def storeShapes(self):
shapesBackup = []
for shape in self.shapes:
shapesBackup.append(shape.copy())
if len(self.shapesBackups) > self.num_backups:
self.shapesBackups = self.shapesBackups[-self.num_backups - 1 :]
self.shapesBackups.append(shapesBackup)
@property
def isShapeRestorable(self):
# We save the state AFTER each edit (not before) so for an
# edit to be undoable, we expect the CURRENT and the PREVIOUS state
# to be in the undo stack.
if len(self.shapesBackups) < 2:
return False
return True
def restoreShape(self):
# This does _part_ of the job of restoring shapes.
# The complete process is also done in app.py::undoShapeEdit
# and app.py::loadShapes and our own Canvas::loadShapes function.
if not self.isShapeRestorable:
return
self.shapesBackups.pop() # latest
# The application will eventually call Canvas.loadShapes which will
# push this right back onto the stack.
shapesBackup = self.shapesBackups.pop()
self.shapes = shapesBackup
self.selectedShapes = []
for shape in self.shapes:
shape.selected = False
self.update()
def enterEvent(self, ev):
self.overrideCursor(self._cursor)
def leaveEvent(self, ev):
self.unHighlight()
self.restoreCursor()
def focusOutEvent(self, ev):
self.restoreCursor()
def isVisible(self, shape):
return self.visible.get(shape, True)
def drawing(self):
return self.mode == self.CREATE
def editing(self):
return self.mode == self.EDIT
def setEditing(self, value=True):
self.mode = self.EDIT if value else self.CREATE
if self.mode == self.EDIT:
# CREATE -> EDIT
self.repaint() # clear crosshair
else:
# EDIT -> CREATE
self.unHighlight()
self.deSelectShape()
def unHighlight(self):
if self.hShape:
self.hShape.highlightClear()
self.update()
self.prevhShape = self.hShape
self.prevhVertex = self.hVertex
self.prevhEdge = self.hEdge
self.hShape = self.hVertex = self.hEdge = None
def selectedVertex(self):
return self.hVertex is not None
def selectedEdge(self):
return self.hEdge is not None
def mouseMoveEvent(self, ev):
"""Update line with last point and current coordinates."""
try:
if QT5:
pos = self.transformPos(ev.localPos())
else:
pos = self.transformPos(ev.posF())
except AttributeError:
return
self.prevMovePoint = pos
self.restoreCursor()
# Polygon drawing.
if self.drawing():
self.line.shape_type = self.createMode
self.overrideCursor(CURSOR_DRAW)
if not self.current:
self.repaint() # draw crosshair
return
if self.outOfPixmap(pos):
# Don't allow the user to draw outside the pixmap.
# Project the point to the pixmap's edges.
pos = self.intersectionPoint(self.current[-1], pos)
elif (
self.snapping
and len(self.current) > 1
and self.createMode == "polygon"
and self.closeEnough(pos, self.current[0])
):
# Attract line to starting point and
# colorise to alert the user.
pos = self.current[0]
self.overrideCursor(CURSOR_POINT)
self.current.highlightVertex(0, Shape.NEAR_VERTEX)
if self.createMode in ["polygon", "linestrip"]:
self.line[0] = self.current[-1]
self.line[1] = pos
elif self.createMode == "rectangle":
self.line.points = [self.current[0], pos]
self.line.close()
elif self.createMode == "circle":
self.line.points = [self.current[0], pos]
self.line.shape_type = "circle"
elif self.createMode == "line":
self.line.points = [self.current[0], pos]
self.line.close()
elif self.createMode == "point":
#self.line.points = [self.current[0]]
#self.line.close()
pass
self.repaint()
self.current.highlightClear()
if QtCore.Qt.RightButton & ev.buttons():
if self.current:
# Add point to existing shape.
if self.createMode == "polygon":
d2 = (self.current[-1].x() - self.line[1].x()) ** 2 + (self.current[-1].y() - self.line[1].y()) ** 2
if d2 >= 80:
self.current.addPoint(self.line[1])
self.line[0] = self.current[-1]
if self.current.isClosed():
self.finalise()
elif self.createMode in ["rectangle", "circle", "line"]:
assert len(self.current.points) == 1
self.current.points = self.line.points
self.finalise()
elif self.createMode == "linestrip":
self.current.addPoint(self.line[1])
self.line[0] = self.current[-1]
if int(ev.modifiers()) == QtCore.Qt.ControlModifier:
self.finalise()
elif not self.outOfPixmap(pos):
# Create new shape.
self.current = Shape(shape_type=self.createMode)
self.current.addPoint(pos)
if self.createMode == "point":
self.setHiding()
self.update()
else:
if self.createMode == "circle":
self.current.shape_type = "circle"
self.line.points = [pos, pos]
self.setHiding()
self.drawingPolygon.emit(True)
self.update()
return
# # Polygon copy moving.
# if QtCore.Qt.RightButton & ev.buttons():
# if self.selectedShapesCopy and self.prevPoint:
# self.overrideCursor(CURSOR_MOVE)
# self.boundedMoveShapes(self.selectedShapesCopy, pos)
# self.repaint()
# elif self.selectedShapes:
# self.selectedShapesCopy = [
# s.copy() for s in self.selectedShapes
# ]
# self.repaint()
# return
# Polygon/Vertex moving.
if QtCore.Qt.LeftButton & ev.buttons():
if self.selectedVertex():
self.boundedMoveVertex(pos)
self.repaint()
self.movingShape = True
elif self.selectedShapes and self.prevPoint:
self.overrideCursor(CURSOR_MOVE)
self.boundedMoveShapes(self.selectedShapes, pos)
self.repaint()
self.movingShape = True
return
if self.editing() and QtCore.Qt.RightButton and ev.buttons():
if self.current:
index, shape = self.hVertex, self.hShape
#print(self.selectedVertex(), index, self.modified_memory[0])
if self.selectedVertex():
index, shape = self.hVertex, self.hShape
if index != self.modified_memory[0] and shape == self.modified_memory[1]:
self.start_modify_flag = False
if self.start_modify_flag == True:
d2 = (self.current[-1].x() - pos.x()) ** 2 + (self.current[-1].y() - pos.y()) ** 2
if d2 >= 80:
self.current.addPoint(pos)
self.setHiding()
self.update()
else:
if len(self.modified_memory) == 2:
self.modified_memory = self.modified_memory + [index, shape]
#print(self.selectedVertex())
#if self.selectedVertex():
# self.boundedMoveVertex(pos)
# self.repaint()
# self.movingShape = True
# Just hovering over the canvas, 2 possibilities:
# - Highlight shapes
# - Highlight vertex
# Update shape/vertex fill and tooltip value accordingly.
self.setToolTip(self.tr("Image"))
for shape in reversed([s for s in self.shapes if self.isVisible(s)]):
# Look for a nearby vertex to highlight. If that fails,
# check if we happen to be inside a shape.
index = shape.nearestVertex(pos, self.epsilon / self.scale)
index_edge = shape.nearestEdge(pos, self.epsilon / self.scale)
if index is not None:
if self.selectedVertex():
self.hShape.highlightClear()
self.prevhVertex = self.hVertex = index
self.prevhShape = self.hShape = shape
self.prevhEdge = self.hEdge
self.hEdge = None
shape.highlightVertex(index, shape.MOVE_VERTEX)
self.overrideCursor(CURSOR_POINT)
self.setToolTip(self.tr("Click & drag to move point"))
self.setStatusTip(self.toolTip())
self.update()
break
elif index_edge is not None and shape.canAddPoint():
if self.selectedVertex():
self.hShape.highlightClear()
self.prevhVertex = self.hVertex
self.hVertex = None
self.prevhShape = self.hShape = shape
self.prevhEdge = self.hEdge = index_edge
self.overrideCursor(CURSOR_POINT)
self.setToolTip(self.tr("Click to create point"))
self.setStatusTip(self.toolTip())
self.update()
break
elif shape.containsPoint(pos):
if self.selectedVertex():
self.hShape.highlightClear()
self.prevhVertex = self.hVertex
self.hVertex = None
self.prevhShape = self.hShape = shape
self.prevhEdge = self.hEdge
self.hEdge = None
self.setToolTip(
self.tr("Click & drag to move shape '%s'") % shape.label
)
self.setStatusTip(self.toolTip())
self.overrideCursor(CURSOR_GRAB)
self.update()
break
else: # Nothing found, clear highlights, reset state.
self.unHighlight()
self.vertexSelected.emit(self.hVertex is not None)
def addPointToEdge(self):
shape = self.prevhShape
index = self.prevhEdge
point = self.prevMovePoint
if shape is None or index is None or point is None:
return
shape.insertPoint(index, point)
shape.highlightVertex(index, shape.MOVE_VERTEX)
self.hShape = shape
self.hVertex = index
self.hEdge = None
self.movingShape = True
def removeSelectedPoint(self):
shape = self.prevhShape
index = self.prevhVertex
if shape is None or index is None:
return
shape.removePoint(index)
shape.highlightClear()
self.hShape = shape
self.prevhVertex = None
self.movingShape = True # Save changes
def mousePressEvent(self, ev):
if QT5:
pos = self.transformPos(ev.localPos())
else:
pos = self.transformPos(ev.posF())
if ev.button() == QtCore.Qt.LeftButton:
if self.drawing():
if self.current:
# Add point to existing shape.
if self.createMode == "polygon":
self.current.addPoint(self.line[1])
self.line[0] = self.current[-1]
if self.current.isClosed():
self.finalise()
elif self.createMode in ["circle", "line"]:
assert len(self.current.points) == 1
self.current.points = self.line.points
self.finalise()
elif self.createMode == "linestrip":
self.current.addPoint(self.line[1])
self.line[0] = self.current[-1]
if int(ev.modifiers()) == QtCore.Qt.ControlModifier:
self.finalise()
elif not self.outOfPixmap(pos):
# Create new shape.
if self.createMode == "point":
pass
elif self.createMode == "rectangle":
pass
else:
self.current = Shape(shape_type=self.createMode)
self.current.addPoint(pos)
if self.createMode == "circle":
self.current.shape_type = "circle"
self.line.points = [pos, pos]
self.setHiding()
self.drawingPolygon.emit(True)
self.update()
if self.currentBox:
if self.createMode == "rectangle":
if len(self.currentBox.points) == 1:
self.currentBox.addPoint(pos)
self.currentBox.close()
self.app.clickManualSegBBox()
self.setHiding()
self.update()
else:
self.currentBox = Shape(shape_type=self.createMode)
self.currentBox.addPoint(pos)
self.line.points = [pos, pos]
self.setHiding()
self.drawingPolygon.emit(True)
self.update()
# elif self.createMode == "linestrip":
# self.currentBox.addPoint(self.line[1])
# self.line[0] = self.currentBox[-1]
elif not self.outOfPixmap(pos):
if self.createMode == "rectangle":
self.currentBox = Shape(shape_type=self.createMode)
self.currentBox.addPoint(pos)
self.line.points = [pos, pos]
self.setHiding()
self.drawingPolygon.emit(True)
self.update()
if self.currentPos:
if self.createMode == "point":
self.currentPos.addPoint(pos)
self.setHiding()
self.update()
self.app.clickManualSegBox()
self.setHiding()
self.update()
elif not self.outOfPixmap(pos):
if self.createMode == "point":
self.currentPos = Shape(shape_type=self.createMode)
self.currentPos.addPoint(pos)
self.setHiding()
self.update()
self.app.clickManualSegBox()
self.setHiding()
self.update()
elif self.editing():
if self.selectedEdge():
self.addPointToEdge()
elif (
self.selectedVertex()
and int(ev.modifiers()) == QtCore.Qt.ShiftModifier
):
# Delete point if: left-click + SHIFT on a point
self.removeSelectedPoint()
group_mode = int(ev.modifiers()) == QtCore.Qt.ControlModifier
self.selectShapePoint(pos, multiple_selection_mode=group_mode)
self.prevPoint = pos
self.repaint()
elif ev.button() == QtCore.Qt.RightButton:
if self.createMode == "point":
self.setHiding()
self.update()
if self.drawing():
if self.current:
# Add point to existing shape.
if self.createMode == "polygon":
self.current.addPoint(self.line[1])
self.line[0] = self.current[-1]
if self.current.isClosed():
self.finalise()
elif self.createMode in ["circle", "line"]:
assert len(self.current.points) == 1
self.current.points = self.line.points
self.finalise()
elif self.createMode == "linestrip":
self.current.addPoint(self.line[1])
self.line[0] = self.current[-1]
if int(ev.modifiers()) == QtCore.Qt.ControlModifier:
self.finalise()
elif not self.outOfPixmap(pos):
# Create new shape.
if self.createMode == "point":
pass
if self.createMode == "rectangle":
pass
else:
self.current = Shape(shape_type=self.createMode)
self.current.addPoint(pos)
if self.createMode == "circle":
self.current.shape_type = "circle"
self.line.points = [pos, pos]
self.setHiding()
self.drawingPolygon.emit(True)
self.update()
if self.currentBox:
if self.createMode == "rectangle":
if len(self.currentBox.points) == 1:
self.currentBox.addPoint(pos)
self.currentBox.close()
self.app.clickManualSegBBox()
self.setHiding()
self.update()
else:
self.currentBox = Shape(shape_type=self.createMode)
self.currentBox.addPoint(pos)
self.line.points = [pos, pos]
self.setHiding()
self.drawingPolygon.emit(True)
self.update()
# elif self.createMode == "linestrip":
# self.currentBox.addPoint(self.line[1])
# self.line[0] = self.currentBox[-1]
elif not self.outOfPixmap(pos):
if self.createMode == "rectangle":
self.currentBox = Shape(shape_type=self.createMode)
self.currentBox.addPoint(pos)
self.line.points = [pos, pos]
self.setHiding()
self.drawingPolygon.emit(True)
self.update()
if self.currentNeg:
if self.createMode == "point":
self.currentNeg.addPoint(pos)
self.setHiding()
self.update()
self.app.clickManualSegBox()
self.setHiding()
self.update()
elif not self.outOfPixmap(pos):
if self.createMode == "point":
self.currentNeg = Shape(shape_type=self.createMode)
self.currentNeg.addPoint(pos)
self.setHiding()
self.update()
self.app.clickManualSegBox()
self.setHiding()
self.update()
if self.editing():
if (self.selectedVertex()
and int(ev.modifiers()) == QtCore.Qt.ShiftModifier
):
# Delete point if: left-click + SHIFT on a point
self.removeSelectedPoint()
else:
if not self.selectedVertex():
self.current = None
else:
if not self.outOfPixmap(pos) and self.selectedVertex() and (not self.current):
# Create new shape.
self.current = Shape(shape_type=self.createMode)
self.current.addPoint(pos)
self.line.points = [pos, pos]
self.start_modify_flag = True
index, shape = self.hVertex, self.hShape
self.modified_memory = [index, shape]
self.setHiding()
self.update()
elif self.current and self.selectedVertex() and len(self.modified_memory) == 4:
tmp_points = self.modified_memory[1].points
add_points = self.current.points
ind1, ind2 = self.modified_memory[0], self.modified_memory[2]
index, shape = self.hVertex, self.hShape
if ind1 < ind2:
if index <= ind2 and index >= ind1:
modified_points = tmp_points[:ind1] + add_points + tmp_points[ind2:]
elif index > ind2:
modified_points = add_points[::-1] + tmp_points[ind1:ind2]
elif index < ind1:
modified_points = add_points[::-1] + tmp_points[ind1:ind2]
elif ind1 >= ind2:
if index <= ind1 and index >= ind2:
modified_points = tmp_points[:ind2] + add_points[::-1] + tmp_points[ind1:]
elif index > ind1:
modified_points = tmp_points[ind2:ind1] + add_points
elif index < ind2:
modified_points = tmp_points[ind2:ind1] + add_points
self.current = None
self.modified_memory = None
self.hShape.points = modified_points
self.storeShapes()
self.setHiding()
self.setHiding(False)
self.update()
self.actions.save.setEnabled(True)
group_mode = int(ev.modifiers()) == QtCore.Qt.ControlModifier
self.selectShapePoint(pos, multiple_selection_mode=group_mode)
self.prevPoint = pos
self.repaint()
# elif ev.button() == QtCore.Qt.RightButton and self.editing():
# group_mode = int(ev.modifiers()) == QtCore.Qt.ControlModifier
# if not self.selectedShapes or (
# self.hShape is not None
# and self.hShape not in self.selectedShapes
# ):
# self.selectShapePoint(pos, multiple_selection_mode=group_mode)
# self.repaint()
# self.prevPoint = pos
def mouseReleaseEvent(self, ev):
if ev.button() == QtCore.Qt.RightButton:
pass
# menu = self.menus[len(self.selectedShapesCopy) > 0]
# self.restoreCursor()
# if (
# not menu.exec_(self.mapToGlobal(ev.pos()))
# and self.selectedShapesCopy
# ):
# # Cancel the move by deleting the shadow copy.
# self.selectedShapesCopy = []
# self.repaint()
elif ev.button() == QtCore.Qt.LeftButton:
if self.editing():
if (
self.hShape is not None
and self.hShapeIsSelected
and not self.movingShape
):
self.selectionChanged.emit(
[x for x in self.selectedShapes if x != self.hShape]
)
if self.movingShape and self.hShape:
index = self.shapes.index(self.hShape)
if (
self.shapesBackups[-1][index].points
!= self.shapes[index].points
):
self.storeShapes()
self.shapeMoved.emit()
self.movingShape = False
def endMove(self, copy):
assert self.selectedShapes and self.selectedShapesCopy
assert len(self.selectedShapesCopy) == len(self.selectedShapes)
if copy:
for i, shape in enumerate(self.selectedShapesCopy):
self.shapes.append(shape)
self.selectedShapes[i].selected = False
self.selectedShapes[i] = shape
else:
for i, shape in enumerate(self.selectedShapesCopy):
self.selectedShapes[i].points = shape.points
self.selectedShapesCopy = []
self.repaint()
self.storeShapes()
return True
def hideBackroundShapes(self, value):
self.hideBackround = value
if self.selectedShapes:
# Only hide other shapes if there is a current selection.
# Otherwise the user will not be able to select a shape.
self.setHiding(True)
self.update()
def setHiding(self, enable=True):
self._hideBackround = self.hideBackround if enable else False
def canCloseShape(self):
return self.drawing() and self.current and len(self.current) > 2
def mouseDoubleClickEvent(self, ev):
# We need at least 4 points here, since the mousePress handler
# adds an extra one before this handler is called.
if (
self.double_click == "close"
and self.canCloseShape()
and len(self.current) > 3
):
self.current.popPoint()
self.finalise()
def selectShapes(self, shapes):
self.setHiding()
self.selectionChanged.emit(shapes)
self.update()
def selectShapePoint(self, point, multiple_selection_mode):
"""Select the first shape created which contains this point."""
if self.selectedVertex(): # A vertex is marked for selection.
index, shape = self.hVertex, self.hShape
shape.highlightVertex(index, shape.MOVE_VERTEX)
else:
for shape in reversed(self.shapes):
if self.isVisible(shape) and shape.containsPoint(point):
self.setHiding()
if shape not in self.selectedShapes:
if multiple_selection_mode:
self.selectionChanged.emit(
self.selectedShapes + [shape]
)
else:
self.selectionChanged.emit([shape])
self.hShapeIsSelected = False
else:
self.hShapeIsSelected = True
self.calculateOffsets(point)
return
self.deSelectShape()
def calculateOffsets(self, point):
left = self.pixmap.width() - 1
right = 0
top = self.pixmap.height() - 1
bottom = 0
for s in self.selectedShapes:
rect = s.boundingRect()
if rect.left() < left:
left = rect.left()
if rect.right() > right:
right = rect.right()
if rect.top() < top:
top = rect.top()
if rect.bottom() > bottom:
bottom = rect.bottom()
x1 = left - point.x()
y1 = top - point.y()
x2 = right - point.x()
y2 = bottom - point.y()
self.offsets = QtCore.QPointF(x1, y1), QtCore.QPointF(x2, y2)
def boundedMoveVertex(self, pos):
index, shape = self.hVertex, self.hShape
point = shape[index]
if self.outOfPixmap(pos):
pos = self.intersectionPoint(point, pos)
shape.moveVertexBy(index, pos - point)
def boundedMoveShapes(self, shapes, pos):
if self.outOfPixmap(pos):
return False # No need to move
o1 = pos + self.offsets[0]
if self.outOfPixmap(o1):
pos -= QtCore.QPoint(min(0, o1.x()), min(0, o1.y()))
o2 = pos + self.offsets[1]
if self.outOfPixmap(o2):
pos += QtCore.QPoint(
min(0, self.pixmap.width() - o2.x()),
min(0, self.pixmap.height() - o2.y()),
)
# XXX: The next line tracks the new position of the cursor
# relative to the shape, but also results in making it
# a bit "shaky" when nearing the border and allows it to
# go outside of the shape's area for some reason.
# self.calculateOffsets(self.selectedShapes, pos)
dp = pos - self.prevPoint
if dp:
for shape in shapes:
shape.moveBy(dp)
self.prevPoint = pos
return True
return False
def deSelectShape(self):
if self.selectedShapes:
self.setHiding(False)
self.selectionChanged.emit([])
self.hShapeIsSelected = False
self.update()
def deleteSelected(self):
deleted_shapes = []
if self.selectedShapes:
for shape in self.selectedShapes:
self.shapes.remove(shape)
deleted_shapes.append(shape)
self.storeShapes()
self.selectedShapes = []
self.update()
return deleted_shapes
def deleteShape(self, shape):
if shape in self.selectedShapes:
self.selectedShapes.remove(shape)
if shape in self.shapes:
self.shapes.remove(shape)
self.storeShapes()
self.update()
def duplicateSelectedShapes(self):
if self.selectedShapes:
self.selectedShapesCopy = [s.copy() for s in self.selectedShapes]
self.boundedShiftShapes(self.selectedShapesCopy)
self.endMove(copy=True)
return self.selectedShapes
def boundedShiftShapes(self, shapes):
# Try to move in one direction, and if it fails in another.
# Give up if both fail.
point = shapes[0][0]
offset = QtCore.QPointF(2.0, 2.0)
self.offsets = QtCore.QPoint(), QtCore.QPoint()
self.prevPoint = point
if not self.boundedMoveShapes(shapes, point - offset):
self.boundedMoveShapes(shapes, point + offset)
def paintEvent(self, event):
if not self.pixmap:
return super(Canvas, self).paintEvent(event)
p = self._painter
p.begin(self)
p.setRenderHint(QtGui.QPainter.Antialiasing)
p.setRenderHint(QtGui.QPainter.HighQualityAntialiasing)
p.setRenderHint(QtGui.QPainter.SmoothPixmapTransform)
p.scale(self.scale, self.scale)
p.translate(self.offsetToCenter())
p.drawPixmap(0, 0, self.pixmap)
# draw crosshair
if (
self._crosshair[self._createMode]
and self.drawing()
and self.prevMovePoint
and not self.outOfPixmap(self.prevMovePoint)
):
p.setPen(QtGui.QColor(0, 0, 0))
p.drawLine(
0,
int(self.prevMovePoint.y()),
self.width() - 1,
int(self.prevMovePoint.y()),
)
p.drawLine(
int(self.prevMovePoint.x()),
0,
int(self.prevMovePoint.x()),
self.height() - 1,
)
Shape.scale = self.scale
for shape in self.shapes:
if (shape.selected or not self._hideBackround) and self.isVisible(
shape
):
shape.fill = shape.selected or shape == self.hShape
shape.paint(p)
if self.current:
self.current.paint(p)
if self.currentPos:
self.currentPos.paint(p,flag=1)
if self.currentNeg:
self.currentNeg.paint(p,flag=0)
if self.currentBox:
self.currentBox.paint(p)
if self.selectedShapesCopy:
for s in self.selectedShapesCopy:
s.paint(p)
if (
self.fillDrawing()
and self.createMode == "polygon"
and self.current is not None
and len(self.current.points) >= 2
):
drawing_shape = self.current.copy()
drawing_shape.addPoint(self.line[1])
drawing_shape.fill = True
drawing_shape.paint(p)
if len(self.app.sam_mask) > 0:
for tmp_mask in self.app.sam_mask:
drawing_shape = tmp_mask.copy()
drawing_shape.fill = True
drawing_shape.paint(p, proposal_flag=1)
p.end()
def transformPos(self, point):
"""Convert from widget-logical coordinates to painter-logical ones."""
return point / self.scale - self.offsetToCenter()
def offsetToCenter(self):
s = self.scale
area = super(Canvas, self).size()
w, h = self.pixmap.width() * s, self.pixmap.height() * s
aw, ah = area.width(), area.height()
x = (aw - w) / (2 * s) if aw > w else 0
y = (ah - h) / (2 * s) if ah > h else 0
return QtCore.QPointF(x, y)
def outOfPixmap(self, p):
w, h = self.pixmap.width(), self.pixmap.height()
return not (0 <= p.x() <= w - 1 and 0 <= p.y() <= h - 1)
def finalise(self):
assert self.current
self.current.close()
self.shapes.append(self.current)
self.storeShapes()
self.current = None
self.currentPos = None
self.currentNeg = None
self.currentBox = None
self.setHiding(False)
self.newShape.emit()
self.update()
def finaliseBox(self):
assert self.currentBox
self.currentBox.close()
self.shapes.append(self.currentBox)
self.storeShapes()
self.current = None
self.currentPos = None
self.currentNeg = None
self.currentBox = None
self.setHiding(False)
self.newShape.emit()
self.update()
def closeEnough(self, p1, p2):
# d = distance(p1 - p2)
# m = (p1-p2).manhattanLength()
# print "d %.2f, m %d, %.2f" % (d, m, d - m)
# divide by scale to allow more precision when zoomed in
return labelme.utils.distance(p1 - p2) < (self.epsilon / self.scale)
def intersectionPoint(self, p1, p2):