def rotateUseRad(self, rad, rotate_point=None): if checkAnyNone(self.pt1, self.pt2): return self if not rotate_point: rotate_point = self.midPoint() pt1 = self.pt1.rotate(rad, rotate_point) pt2 = self.pt2.rotate(rad, rotate_point) self.initPts(pt1, pt2) return self
def distance(self, pt, mode=0): if mode > 0 and checkAnyNone(self.pt1, self.pt2): mode = 0 if mode == 0: # 点到直线的垂直距离, 线上最近距离点可能在延长线上 if self.d: return abs(self.a * pt.x + self.b * pt.y + self.c) / self.d else: return np.sqrt(np.power(self.pt1.x - pt.x, 2) + np.power(self.pt1.y - pt.y, 2)) elif mode == 1: # 点到线段的距离, 线上最近距离点在线段上 x, y = pt.x, pt.y x1, y1, x2, y2 = self.x1, self.y1, self.x2, self.y2 cross = (x2 - x1) * (x - x1) + (y2 - y1) * (y - y1) if cross <= 0: return math.sqrt((x - x1) * (x - x1) + (y - y1) * (y - y1)) d2 = (x2 - x1) * (x2 - x1) + (y2 - y1) * (y2 - y1) if cross >= d2: return math.sqrt((x - x2) ** 2 + (y - y2) ** 2) r = cross / float(d2) px = x1 + (x2 - x1) * r py = y1 + (y2 - y1) * r return math.sqrt((x - px) ** 2 + (py - y) ** 2) else: print('line.distance模式不支持 %d' % (mode))
def getLen(self): if checkAnyNone(self.pt1, self.pt2): return -1 return self.pt1.distance(self.pt2)
def __str__(self): if checkAnyNone(self.pt1, self.pt2): return 'GLine a:%.3f b:%.3f c:%.3f' % (self.a, self.b, self.c) else: return 'GLine X1:%d Y1:%d X2:%d Y2:%d' % (self.x1, self.y1, self.x2, self.y2)
def move(self, x, y): if checkAnyNone(self.pt1, self.pt2): return self pt1 = self.pt1.move(x, y) pt2 = self.pt2.move(x, y) self.initPts(pt1, pt2) return self
def distanceWithLine(self, line): if checkAnyNone(self.pt1, self.pt2, line.pt1, line.pt2): return -1 if isLineSegCross(self.pt1, self.pt2, line.pt1, line.pt2): return 0 return min(self.distance(line.pt1, mode=1), self.distance(line.pt2, mode=1), line.distance(self.pt1, mode=1), line.distance(self.pt2, mode=1))
def draw(self, img, color=255, thickness=1, **kwargs): if checkAnyNone(self.pt1, self.pt2): return cv2.line(img, self.pt1.getPoint(), self.pt2.getPoint(), color, thickness, **kwargs)
def midPoint(self): if checkAnyNone(self.pt1, self.pt2): return None return GPoint((self.x1 + self.x2) / 2., (self.y1 + self.y2) / 2.)
def midLine(self, line): if checkAnyNone(self.pt1, self.pt2, line.pt1, line.pt2): return None if self.pt1.distance(line.pt1) > self.pt1.distance(line.pt2): return GLine(self.pt1.midpoint(line.pt2), self.pt2.midpoint(line.pt1)) else: return GLine(self.pt1.midpoint(line.pt1), self.pt2.midpoint(line.pt2))