def polygonEnvelope(polygon): # 多边形的顶点序列 partList = polygon.partList # 两个顶点 rt = Point() lb = Point() rt.x = lb.x = partList[0][0].x rt.y = lb.y = partList[0][0].y for i in range(len(partList)): for k in range(len(partList[i])): if partList[i][k].x < lb.x: lb.x = partList[i][k].x if partList[i][k].x > rt.x: rt.x = partList[i][k].x if partList[i][k].y < lb.y: lb.y = partList[i][k].y if partList[i][k].y > rt.y: rt.y = partList[i][k].y envelope = Envelope() envelope.rtPoint = rt envelope.lbPoint = lb return envelope
def getEnvelopeGravity(envelopeList): # rtPoint = Point() lbPoint = Point() rtPoint.x = lbPoint.x = envelopeList[0].rtPoint.x rtPoint.y = lbPoint.y = envelopeList[0].lbPoint.y for envelope in envelopeList: rt = envelope.rtPoint lb = envelope.lbPoint if lb.x < lbPoint.x: lbPoint.x = lb.x if lb.y < lbPoint.y: lbPoint.y = lb.y if rt.x > rtPoint.x: rtPoint.x = rt.x if rt.y > rtPoint.y: rtPoint.y = rt.y envelope = Envelope() envelope.lbPoint = lbPoint envelope.rtPoint = rtPoint gravity = Point() gravity.x = (rtPoint.x + lbPoint.x) / 2 gravity.y = (rtPoint.y + lbPoint.y) / 2 return gravity, envelope pass
def calculateGravity(pointList): # 重心坐标 gravity = Point() p1 = pointList[0] p2 = pointList[1] x1 = p1.x y1 = p1.y sum_x = 0 sum_y = 0 sum_area = 0 for i in range(2, len(pointList)): x2 = p2.x y2 = p2.y p3 = pointList[i] x3 = p3.x y3 = p3.y area = ((x2 - x1) * (y3 - y1) - (x3 - x1) * (y2 - y1)) / 2.0 sum_x += (x1 + x2 + x3) * area sum_y += (y1 + y2 + y3) * area sum_area += area p2 = p3 gravity.x = sum_x / sum_area / 3.0 gravity.y = sum_y / sum_area / 3.0 return gravity
def polygonCatercorner(polygon): # 获得外包矩形 polygon.envelope = polygonEnvelope(polygon) # 正对角线长度 dis = pointDistance(polygon.envelope.lbPoint, polygon.envelope.rtPoint) # 将重心移到原点 gravity = polygon.gravity partList = [] for part in polygon.partList: p = [] for pnt in part: point = Point() point.x = pnt.x - gravity.x point.y = pnt.y - gravity.y p.append(point) partList.append(p) return dis, partList