Skip to content

Commit 4bb6be6

Browse files
lgovtzutalin
authored andcommitted
Ensure a vertex always stays within the boundaries of the canvas.
1 parent a0fa187 commit 4bb6be6

File tree

2 files changed

+20
-5
lines changed

2 files changed

+20
-5
lines changed

labelImg.py

Lines changed: 2 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -760,11 +760,8 @@ def loadLabels(self, shapes):
760760
for x, y in points:
761761

762762
# Ensure the labels are within the bounds of the image. If not, fix them.
763-
if x < 0 or x > self.canvas.pixmap.width() or y < 0 or y > self.canvas.pixmap.height():
764-
x = max(x, 0)
765-
y = max(y, 0)
766-
x = min(x, self.canvas.pixmap.width())
767-
y = min(y, self.canvas.pixmap.height())
763+
x, y, snapped = self.canvas.snapPointToCanvas(x, y)
764+
if snapped:
768765
self.setDirty()
769766

770767
shape.addPoint(QPointF(x, y))

libs/canvas.py

Lines changed: 18 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -326,6 +326,20 @@ def calculateOffsets(self, shape, point):
326326
y2 = (rect.y() + rect.height()) - point.y()
327327
self.offsets = QPointF(x1, y1), QPointF(x2, y2)
328328

329+
def snapPointToCanvas(self, x, y):
330+
"""
331+
Moves a point x,y to within the boundaries of the canvas.
332+
:return: (x,y,snapped) where snapped is True if x or y were changed, False if not.
333+
"""
334+
if x < 0 or x > self.pixmap.width() or y < 0 or y > self.pixmap.height():
335+
x = max(x, 0)
336+
y = max(y, 0)
337+
x = min(x, self.pixmap.width())
338+
y = min(y, self.pixmap.height())
339+
return x, y, True
340+
341+
return x, y, False
342+
329343
def boundedMoveVertex(self, pos):
330344
index, shape = self.hVertex, self.hShape
331345
point = shape[index]
@@ -528,6 +542,10 @@ def intersectionPoint(self, p1, p2):
528542
return QPointF(x3, min(max(0, y2), max(y3, y4)))
529543
else: # y3 == y4
530544
return QPointF(min(max(0, x2), max(x3, x4)), y3)
545+
546+
# Ensure the labels are within the bounds of the image. If not, fix them.
547+
x, y, _ = self.snapPointToCanvas(x, y)
548+
531549
return QPointF(x, y)
532550

533551
def intersectingEdges(self, x1y1, x2y2, points):

0 commit comments

Comments
 (0)