From 4bb6be6986fb29a6dff48bc4abc5389976f3c16f Mon Sep 17 00:00:00 2001 From: Lieven Govaerts Date: Sat, 29 Dec 2018 13:57:13 +0100 Subject: [PATCH] Ensure a vertex always stays within the boundaries of the canvas. --- labelImg.py | 7 ++----- libs/canvas.py | 18 ++++++++++++++++++ 2 files changed, 20 insertions(+), 5 deletions(-) diff --git a/labelImg.py b/labelImg.py index 01bb3236..0d2ea35d 100755 --- a/labelImg.py +++ b/labelImg.py @@ -760,11 +760,8 @@ class MainWindow(QMainWindow, WindowMixin): for x, y in points: # Ensure the labels are within the bounds of the image. If not, fix them. - if x < 0 or x > self.canvas.pixmap.width() or y < 0 or y > self.canvas.pixmap.height(): - x = max(x, 0) - y = max(y, 0) - x = min(x, self.canvas.pixmap.width()) - y = min(y, self.canvas.pixmap.height()) + x, y, snapped = self.canvas.snapPointToCanvas(x, y) + if snapped: self.setDirty() shape.addPoint(QPointF(x, y)) diff --git a/libs/canvas.py b/libs/canvas.py index d026fb9f..a53414f4 100644 --- a/libs/canvas.py +++ b/libs/canvas.py @@ -326,6 +326,20 @@ class Canvas(QWidget): y2 = (rect.y() + rect.height()) - point.y() self.offsets = QPointF(x1, y1), QPointF(x2, y2) + def snapPointToCanvas(self, x, y): + """ + Moves a point x,y to within the boundaries of the canvas. + :return: (x,y,snapped) where snapped is True if x or y were changed, False if not. + """ + if x < 0 or x > self.pixmap.width() or y < 0 or y > self.pixmap.height(): + x = max(x, 0) + y = max(y, 0) + x = min(x, self.pixmap.width()) + y = min(y, self.pixmap.height()) + return x, y, True + + return x, y, False + def boundedMoveVertex(self, pos): index, shape = self.hVertex, self.hShape point = shape[index] @@ -528,6 +542,10 @@ class Canvas(QWidget): return QPointF(x3, min(max(0, y2), max(y3, y4))) else: # y3 == y4 return QPointF(min(max(0, x2), max(x3, x4)), y3) + + # Ensure the labels are within the bounds of the image. If not, fix them. + x, y, _ = self.snapPointToCanvas(x, y) + return QPointF(x, y) def intersectingEdges(self, x1y1, x2y2, points):