예제 #1
0
    def test_scaling(self):
        test_factor = 10000
        test_clip = _modify_vertices(PATH_CLIP_1, addend=0.23591)
        test_subj_1 = _modify_vertices(PATH_SUBJ_1, addend=0.28591)
        test_subj_2 = _modify_vertices(PATH_SUBJ_2, addend=0.52391)

        pyclipper.SCALING_FACTOR = test_factor
        pc = pyclipper.Pyclipper()
        self.add_paths(pc, test_clip, [test_subj_1, test_subj_2])
        scaled_solution = pc.Execute(*self.default_args)

        pyclipper.SCALING_FACTOR = 1
        pc = pyclipper.Pyclipper()
        self.add_paths(pc,
                       test_clip, [test_subj_1, test_subj_2],
                       multiplier=test_factor)
        manualy_scaled = pc.Execute(*self.default_args)

        self.assertEqual(len(scaled_solution), len(manualy_scaled))

        manualy_scaled[0] = _modify_vertices(manualy_scaled[0],
                                             multiplier=1.0 / test_factor)
        manualy_scaled[1] = _modify_vertices(manualy_scaled[1],
                                             multiplier=1.0 / test_factor)

        self.assertTrue(
            _do_solutions_match(manualy_scaled, scaled_solution, test_factor))
예제 #2
0
def union_polys(polys):
    '''
    returns a list of lists of polygon points.
    First member of each list is an outer contour,
    the remaining members are holes.
    '''
    pc = pyclipper.Pyclipper()
    pc.AddPaths(polys, pyclipper.PT_SUBJECT, True)
    union = pc.Execute2(pyclipper.CT_UNION, pyclipper.PFT_POSITIVE,
                        pyclipper.PFT_POSITIVE)

    def collect_outers_and_holes(root_node, result=None):
        if result is None:
            result = []
        for n in root_node.Childs:
            assert n.IsHole == False
            outer_and_holes = [np.asarray(n.Contour)]
            if len(n.Childs) > 0:
                for c in n.Childs:
                    assert c.IsHole
                    outer_and_holes.append(np.asarray(c.Contour))
                    if len(c.Childs) > 0:
                        collect_outers_and_holes(c, result)
            result.append(outer_and_holes)
        return result

    return collect_outers_and_holes(union)
예제 #3
0
 def setUp(self):
     self.pc = pyclipper.Pyclipper()
     self.add_default_paths(self.pc)
     self.default_args = [
         pyclipper.CT_INTERSECTION, pyclipper.PFT_EVENODD,
         pyclipper.PFT_EVENODD
     ]
예제 #4
0
def iou_score(box1, box2):
    """Returns the Intersection-over-Union score, defined as the area of
    the intersection divided by the intersection over the union of
    the two bounding boxes. This measure is symmetric.

    Args:
        box1: The coordinates for box 1 as a list of (x, y) coordinates
        box2: The coordinates for box 2 in same format as box1.
    """
    if len(box1) == 2:
        x1, y1 = box1[0]
        x2, y2 = box1[1]
        box1 = np.array([[x1, y1], [x2, y1], [x2, y2], [x1, y2]])
    if len(box2) == 2:
        x1, y1 = box2[0]
        x2, y2 = box2[1]
        box2 = np.array([[x1, y1], [x2, y1], [x2, y2], [x1, y2]])
    if any(cv2.contourArea(np.int32(box)[:, np.newaxis, :]) == 0 for box in [box1, box2]):
        warnings.warn('A box with zero area was detected.')
        return 0
    pc = pyclipper.Pyclipper()
    pc.AddPath(np.int32(box1), pyclipper.PT_SUBJECT, closed=True)
    pc.AddPath(np.int32(box2), pyclipper.PT_CLIP, closed=True)
    intersection_solutions = pc.Execute(pyclipper.CT_INTERSECTION, pyclipper.PFT_EVENODD,
                                        pyclipper.PFT_EVENODD)
    union_solutions = pc.Execute(pyclipper.CT_UNION, pyclipper.PFT_EVENODD, pyclipper.PFT_EVENODD)
    union = sum(cv2.contourArea(np.int32(points)[:, np.newaxis, :]) for points in union_solutions)
    intersection = sum(
        cv2.contourArea(np.int32(points)[:, np.newaxis, :]) for points in intersection_solutions)
    return intersection / union
예제 #5
0
def make_valid_pyclipper(shape):
    """
    Use the pyclipper library to "union" a polygon on its own. This operation
    uses the even-odd rule to determine which points are in the interior of
    the polygon, and can reconstruct the orientation of the polygon from that.
    The pyclipper library is robust, and uses integer coordinates, so should
    not produce any additional degeneracies.

    Before cleaning the polygon, we remove all degenerate inners. This is
    useful to remove inners which have collapsed to points or lines, which can
    interfere with the cleaning process.
    """

    # drop all degenerate inners
    clean_shape = _drop_degenerate_inners(shape)

    pc = pyclipper.Pyclipper()

    try:
        pc.AddPaths(_coords(clean_shape), pyclipper.PT_SUBJECT, True)

        # note: Execute2 returns the polygon tree, not the list of paths
        result = pc.Execute2(pyclipper.CT_UNION, pyclipper.PFT_EVENODD)

    except pyclipper.ClipperException:
        return MultiPolygon([])

    return _polytree_to_shapely(result)
예제 #6
0
def clip(a, b):
    """ return polygon of a-b
    """
    if len(a) == 3:  # triangle base case.
        return a

    pc = pyclipper.Pyclipper()
    try:
        pc.AddPath(a, pyclipper.PT_SUBJECT, True)
    except pyclipper.ClipperException as e:
        print(a)
        raise e
    try:
        pc.AddPath(b, pyclipper.PT_CLIP, True)
    except pyclipper.ClipperException as e:
        print(b)
        raise e

    paths = pc.Execute(pyclipper.CT_INTERSECTION, pyclipper.PFT_EVENODD,
                       pyclipper.PFT_EVENODD)

    if len(paths) > 0:
        return paths[0]
    else:
        return a
예제 #7
0
def random_rotate_points(bboxes, img):
    '''
    @msg: 图片随机旋转后,坐标点的映射位置
    @param {bboxes:旋转前的坐标点, img:图片} 
    @return: {bboxes:旋转后的坐标点,angle:旋转角度}
    '''
    h, w = img.shape[0:2]
    x_center, y_center = w / 2, h / 2
    max_angle = 10
    angle = random.random() * 2 * max_angle - max_angle
    bboxes_rotate = []
    for idx in range(len(bboxes)):
        for i in range(len(bboxes[idx])):
            bboxes[idx][i] = np.array([
                rotate_position(angle, pos[0], pos[1], x_center, y_center)
                for pos in bboxes[idx][i]
            ])

        #解决越界问题
        clip = np.array(((0, 0), (0, h), (w, h), (w, 0)))
        pc = pyclipper.Pyclipper()
        pc.AddPath(clip, pyclipper.PT_CLIP, True)
        pc.AddPaths(bboxes[idx], pyclipper.PT_SUBJECT, True)
        bbox_rotate = pc.Execute(pyclipper.CT_INTERSECTION,
                                 pyclipper.PFT_EVENODD)
        bboxes_rotate.append(np.array(bbox_rotate))

    return bboxes_rotate, angle
예제 #8
0
def getroomcontour(origin, room):
    room_fname = os.path.join(suncg_root, "room", origin, room + "f.obj")
    if (not os.path.isfile(room_fname)):
        room_fname = os.path.join(
            os.path.split(housef)[0].replace(house_root, room_root),
            room["modelId"] + "c.obj")
    with open(room_fname, "r") as inf:
        lines = inf.read().split("\n")
        vertices_lines = lfilter(lambda x: x.startswith("v "), lines)
        vertices = np.array(
            lmap(lambda x: lmap(float,
                                x.split()[1:]), vertices_lines))[:, [0, 2]]
        faces_lines = lfilter(lambda x: x.startswith("f "), lines)
        faces = lmap(
            lambda x: lmap(lambda y: int(y.split("/")[0]) - 1,
                           x.split()[1:]), faces_lines)
        paths = pyclipper.scale_to_clipper([vertices[faces[0]]])
        for face in faces:
            if (np.abs(area(vertices[face])) < 1e-5):
                continue
            pc = pyclipper.Pyclipper()
            pc.AddPaths(paths, pyclipper.PT_SUBJECT, True)
            clipface = pyclipper.scale_to_clipper(vertices[face])
            pc.AddPath(clipface, pyclipper.PT_CLIP, True)
            paths = pc.Execute(pyclipper.CT_UNION, pyclipper.PFT_EVENODD,
                               pyclipper.PFT_EVENODD)
        paths = pyclipper.scale_from_clipper(paths)

    return paths
예제 #9
0
def bin_locus(locus_list):
    clipper = pyclipper.Pyclipper()
    for locus in locus_list:
        clipper.AddPath(pyclipper.scale_to_clipper(locus), pyclipper.PT_SUBJECT)

    merged_locus = np.array(pyclipper.scale_from_clipper(clipper.Execute(pyclipper.CT_UNION, pyclipper.PFT_NONZERO)))
    return merged_locus
예제 #10
0
def paths(accessor, width, height):
    pc = pyclipper.Pyclipper()

    for y in range(height):
        for x in range(width):
            if not accessor[x, y]:
                continue

            pc.AddPath([
                (x, y),
                (x + 1, y),
                (x + 1, y + 1),
                (x, y + 1),
            ], pyclipper.PT_SUBJECT, True)

    result = pc.Execute2(
        pyclipper.CT_UNION,
        pyclipper.PFT_EVENODD,
        pyclipper.PFT_EVENODD,
    )

    def descend_node(node):
        if node.Contour:
            yield node.IsHole, node.Contour + [node.Contour[0]]
        for child in node.Childs[::-1]:
            yield from descend_node(child)

    yield from descend_node(result)
예제 #11
0
    def trim(self, trimPoly):
        if len(self.polygons) > 0 and len(trimPoly.polygons) > 0:

            polytrim = pyclipper.Pyclipper()  #Pyclipper
            polytrim.AddPaths(
                [[[int(self.scaling * p[0]),
                   int(self.scaling * p[1])] for p in pat]
                 for pat in trimPoly.polygons],
                poly_type=pyclipper.PT_CLIP,
                closed=True)
            polytrim.AddPaths(
                [[[int(self.scaling * p[0]),
                   int(self.scaling * p[1])] for p in pat]
                 for pat in self.polygons],
                poly_type=pyclipper.PT_SUBJECT,
                closed=True)
            try:
                trimmed = polytrim.Execute(pyclipper.CT_INTERSECTION,
                                           pyclipper.PFT_EVENODD,
                                           pyclipper.PFT_EVENODD)
                trimmed = pyclipper.SimplifyPolygons(trimmed)
                self.polygons = [[[
                    float(x[0]) / self.scaling,
                    float(x[1]) / self.scaling, self.zlevel
                ] for x in poly] for poly in trimmed]
            except:
                print("clipping intersection error")
예제 #12
0
    def _clip_patch(self, subject, patch_coord, patch_dim):
        w, h = patch_dim
        clipper = (
            (0, 0),
            (w, 0),
            (w, h),
            (0, h),
        )

        subject_relative = self._make_coordinates_relative(
            patch_coord,
            subject,
        )

        pc = pyclipper.Pyclipper()
        pc.AddPath(clipper, pyclipper.PT_CLIP, True)
        pc.AddPaths(subject_relative, pyclipper.PT_SUBJECT, True)

        solution = pc.Execute(
            pyclipper.CT_INTERSECTION,
            pyclipper.PFT_EVENODD,
            pyclipper.PFT_EVENODD,
        )

        solution = [[tuple(c) for c in s] for s in solution]
        return solution
예제 #13
0
def boolean(subj, clip=None, clip_type=None, closed=True):
    """ Apply boolean operation of polygons. """
    if clip is None and len(subj) <= 1: return subj
    pc = pyclipper.Pyclipper()
    sc = constants.CLIPPER_SCALE
    if clip is not None:
        clip_pts = reverse_points(clip)
        pc.AddPaths(clip_pts, pyclipper.PT_CLIP, True)
    subj_pts = reverse_points(subj)
    pc.AddPaths(subj_pts, pyclipper.PT_SUBJECT, closed)
    ct = {
        'or': pyclipper.CT_UNION,
        'and': pyclipper.CT_INTERSECTION,
        'not': pyclipper.CT_DIFFERENCE,
        'xor': pyclipper.CT_XOR
    }
    if clip_type not in ct:
        print("jointype '{}' unknown.".format(jointype))
        print("jointype should be one of 'or', 'and', 'not', 'xor'.")
        print("Using default ('or')")
        clip_type = 'or'
    value = pc.Execute(ct[clip_type], pyclipper.PFT_NONZERO,
                       pyclipper.PFT_NONZERO)
    value = clean_points(pts=value)
    return value
예제 #14
0
def prep_3D_polys(poly1, poly2):
    # type: (Polygon3D, Polygon3D) -> pc.Pyclipper
    """Prepare two 3D polygons for clipping operations.

    Parameters
    ----------
    poly1 : Polygon3D
        The subject polygon.
    poly2 : Polygon3D
        The clip polygon.

    Returns
    -------
    pc.Pyclipper object

    """
    if not poly1.is_coplanar(poly2):
        return False
    poly1 = poly1.project_to_2D()
    poly2 = poly2.project_to_2D()

    s1 = pc.scale_to_clipper(poly1.vertices_list)
    s2 = pc.scale_to_clipper(poly2.vertices_list)
    clipper = pc.Pyclipper()
    clipper.AddPath(s1, poly_type=pc.PT_SUBJECT, closed=True)
    clipper.AddPath(s2, poly_type=pc.PT_CLIP, closed=True)

    return clipper
예제 #15
0
    def __check_direct_edge(self, point0, point1):

        pc = pyclipper.Pyclipper()
        pc.AddPath([point0, point1], pyclipper.PT_SUBJECT, False)
        pc.AddPath(self.bound, pyclipper.PT_CLIP, True)
        result = pyclipper.OpenPathsFromPolyTree(
            pc.Execute2(pyclipper.CT_DIFFERENCE, pyclipper.PFT_EVENODD,
                        pyclipper.PFT_EVENODD))
        if len(result) != 0:
            return False
        for poly in self.holes:
            pc.Clear()
            pc.AddPath([point0, point1], pyclipper.PT_SUBJECT, False)
            pc.AddPath(poly, pyclipper.PT_CLIP, True)
            result = pyclipper.OpenPathsFromPolyTree(
                pc.Execute2(pyclipper.CT_DIFFERENCE, pyclipper.PFT_EVENODD,
                            pyclipper.PFT_EVENODD))

            if len(result) != 1 or \
                result[0][0][0] != point0[0] or\
                result[0][0][1] != point0[1] or\
                result[0][1][0] != point1[0] or\
                result[0][1][1] != point1[1]:

                return False

        return True
예제 #16
0
파일: Polygon.py 프로젝트: BCN3D/Uranium
    def intersectionConvexHulls(self, other: "Polygon") -> "Polygon":
        """Computes the intersection of the convex hulls of this and another
        polygon.

        :param other: The other polygon to intersect convex hulls with.
        :return: The intersection of the two polygons' convex hulls.
        """
        me = self.getConvexHull()
        him = other.getConvexHull()

        # If either polygon has no surface area, then the intersection is empty.
        if len(me.getPoints()) <= 2 or len(him.getPoints()) <= 2:
            return Polygon()

        clipper = pyclipper.Pyclipper()
        clipper.AddPath(me._clipperPoints(), pyclipper.PT_SUBJECT, closed=True)
        clipper.AddPath(other._clipperPoints(), pyclipper.PT_CLIP, closed=True)

        points = clipper.Execute(pyclipper.CT_INTERSECTION,
                                 pyclipper.PFT_NONZERO, pyclipper.PFT_NONZERO)
        if len(points) == 0:
            return Polygon()
        points = points[
            0]  # Intersection between convex hulls should result in a single (convex) simple polygon. Take just the one polygon.
        if points[0] == points[
                -1]:  # Represent closed polygons without closing vertex.
            points.pop()
        return self._fromClipperPoints(numpy.array(points))
예제 #17
0
파일: Polygon.py 프로젝트: BCN3D/Uranium
    def intersectsPolygon(self,
                          other: "Polygon") -> Optional[Tuple[float, float]]:
        """Check to see whether this polygon intersects with another polygon.

        :param other: :type{Polygon} The polygon to check for intersection.
        :return: A tuple of the x and y distance of intersection, or None if no intersection occurred.
        """
        if not self.isValid() or not other.isValid():
            return None

        clipper = pyclipper.Pyclipper()
        try:
            clipper.AddPath(self._clipperPoints(),
                            pyclipper.PT_SUBJECT,
                            closed=True)
            clipper.AddPath(other._clipperPoints(),
                            pyclipper.PT_CLIP,
                            closed=True)
            intersection_points = clipper.Execute(pyclipper.CT_INTERSECTION)
        except pyclipper.ClipperException:
            # Invalid geometry, such as a zero-area polygon.
            return None

        if len(intersection_points) == 0:
            return None

        # Find the bounds of the intersection area.
        mini = (math.inf, math.inf)
        maxi = (-math.inf, -math.inf)
        for poly in intersection_points:  # Each simple polygon in the complex intersection multi-polygon.
            for vertex in poly:
                mini = (min(mini[0], vertex[0]), min(mini[1], vertex[1]))
                maxi = (max(maxi[0], vertex[0]), max(maxi[1], vertex[1]))
        return float(maxi[0] - mini[0]) / self.CLIPPER_PRECISION, float(
            maxi[1] - mini[1]) / self.CLIPPER_PRECISION
예제 #18
0
    def _merge_intersecting_meshes(self, contour):
        def dist_longer_than(p1, p2, d):
            x = p2[0] - p1[0]
            y = p2[1] - p1[1]
            return d * d < x**2 + y**2

        pc = pyclipper.Pyclipper()

        for intersections in contour:
            if len(intersections) > 1:
                path = []

                for intersection in intersections:
                    if not path or path and dist_longer_than(
                            path[-1], intersection.xy,
                            self.MIN_DIST_BETWEEN_POINTS):
                        path.append(intersection.xy)

                if len(path) > 3:
                    pc.AddPath(path, pyclipper.PT_SUBJECT, True)

        try:
            solution = pc.Execute(pyclipper.CT_UNION, pyclipper.PFT_NONZERO,
                                  pyclipper.PFT_NONZERO)

            for outline in solution:
                self.outlines.append(outline)
        except pyclipper.ClipperException:
            # Nothing to clip, i.e. no paths were added to the Pyclipper instance
            raise EmptyLayerException
예제 #19
0
def inter_layers(_subj, _clip, closed):
    if len(_clip) == 0:
        return []
    pc = pyclipper.Pyclipper()
    try:
        pc.AddPaths(_clip, pyclipper.PT_CLIP, True)
    except:
        raise RuntimeError

    try:
        pc.AddPaths(_subj, pyclipper.PT_SUBJECT, closed)
    except:
        raise RuntimeError

    if closed:
        solution = pc.Execute(pyclipper.CT_INTERSECTION,
                              pyclipper.PFT_EVENODD,
                              pyclipper.PFT_EVENODD)
    else:
        solution = pc.Execute2(pyclipper.CT_INTERSECTION,
                               pyclipper.PFT_EVENODD,
                               pyclipper.PFT_EVENODD)
        solution = pyclipper.PolyTreeToPaths(solution)

    return solution
예제 #20
0
def angusj(subj, clip=None, method=None, closed=True):
    """ Angusj clipping library """

    pc = pyclipper.Pyclipper()

    setattr(pc, 'StrictlySimple', True)

    if clip is not None:
        pc.AddPaths(clip, pyclipper.PT_CLIP, True)

    pc.AddPaths(subj, pyclipper.PT_SUBJECT, closed)

    subj = None
    if method == 'difference':
        subj = pc.Execute(pyclipper.CT_DIFFERENCE, pyclipper.PFT_EVENODD,
                          pyclipper.PFT_EVENODD)
    elif method == 'union':
        subj = pc.Execute(pyclipper.CT_UNION, pyclipper.PFT_NONZERO,
                          pyclipper.PFT_NONZERO)
    elif method == 'intersection':
        subj = pc.Execute(pyclipper.CT_INTERSECTION, pyclipper.PFT_NONZERO,
                          pyclipper.PFT_NONZERO)
    elif method == 'exclusive':
        subj = pc.Execute(pyclipper.CT_XOR, pyclipper.PFT_NONZERO,
                          pyclipper.PFT_NONZERO)
    else:
        raise ValueError('please specify a clipping method')

    return subj
예제 #21
0
def roundoff(tau, R_pz, dist_mod, xy, nd, n_t1, n_t2, vertexes, xyc):

    r_tc = R_pz / tau
    v_tc = np.add(np.array(dist_mod / tau * nd), xy)  #circle's center

    point1 = r_tc * np.array([-n_t1[1], n_t1[0]
                              ]) + v_tc  #intersection of leg2 with the circle
    point2 = r_tc * np.array([n_t2[1], -n_t2[0]
                              ]) + v_tc  #intersection of leg1 with the circle

    legs_points = [[point1[0], point1[1]], [point2[0], point2[1]],
                   list(vertexes[0]),
                   list(vertexes[1])]

    #Define the circle's coordinates
    circle_lst = [list(map(list, np.flipud(xyc * r_tc)))]
    circle1 = np.array(circle_lst[0])
    circle1 = np.add(circle1, v_tc)  #add center of circle

    legs = pyclipper.Pyclipper()
    legs.AddPath(pyclipper.scale_to_clipper(legs_points), pyclipper.PT_SUBJECT,
                 True)

    circle_cut = tuple(map(tuple, circle1))
    legs.AddPath(pyclipper.scale_to_clipper(circle_cut), pyclipper.PT_CLIP,
                 True)

    union = pyclipper.scale_from_clipper(
        legs.Execute(pyclipper.CT_UNION, pyclipper.PFT_NONZERO,
                     pyclipper.PFT_NONZERO))
    union = np.array(union[0])
    #PUT THE UNION IN TUPLE SO IT CAN BE ADDED AS AN OBJECT TO A PYCLIPPER OBJECT
    VO_round = tuple(map(tuple, union))

    return VO_round, legs_points
예제 #22
0
def softnms(boxes, box_scores, char_scores=None, overlapThresh=0.3,
                          threshold=0.8, neighbourThresh=0.5, num_neig=0):
    scores = box_scores.copy()
    new_boxes = boxes[:, 0: 8].copy()
    if char_scores is not None:
        new_char_scores = char_scores.copy()
    polygons = [pyclipper.scale_to_clipper(poly.reshape((-1, 2))) for poly in new_boxes]
    areas = [pyclipper.scale_from_clipper(pyclipper.scale_from_clipper(
             pyclipper.Area(poly))) for poly in polygons]
    areas = [abs(_) for _ in areas]
    N = boxes.shape[0]
    order = np.arange(N)
    i = 0
    while i < N:
        max_pos = scores[order[i: N]].argmax() + i
        order[i], order[max_pos] = order[max_pos], order[i]
        pos = i + 1
        neighbours = list()
        while pos < N:
            try:
                pc = pyclipper.Pyclipper()
                pc.AddPath(polygons[order[i]], pyclipper.PT_CLIP, True)
                pc.AddPaths([polygons[order[pos]]], pyclipper.PT_SUBJECT, True)
                solution = pc.Execute(pyclipper.CT_INTERSECTION)
                if len(solution) == 0:
                    inter = 0
                else:
                    inter = pyclipper.scale_from_clipper(
                        pyclipper.scale_from_clipper(
                            pyclipper.Area(solution[0])))
            except Exception:
                inter = 0
            union = areas[order[i]] + areas[order[pos]] - inter
            iou = inter / union if union > 0 else 0
            if iou > neighbourThresh:
                neighbours.append(order[pos])
            weight = np.exp(-(iou **2) / 0.5)
            scores[order[pos]] *= weight
            if scores[order[pos]] < threshold:
                order[pos], order[N - 1] = order[N - 1], order[pos]
                N -= 1
                pos -= 1
            pos += 1
        if len(neighbours) >= num_neig:
            neighbours.append(order[i])
            temp_scores = box_scores[neighbours].reshape((-1, 1))
            new_boxes[order[i], :8] = (boxes[neighbours, :8] * temp_scores).sum(axis=0) / temp_scores.sum()
            if char_scores is not None:
                new_char_scores[order[i], :] = (char_scores[neighbours, :] * temp_scores).sum(axis=0) / temp_scores.sum()
        else:
            order[i], order[N - 1] = order[N - 1], order[i]
            N -= 1
            i -= 1
        i += 1
    keep = [order[_] for _ in range(N)]
    if char_scores is not None:
        return keep, new_boxes, new_char_scores
    else:
        return keep, new_boxes
예제 #23
0
def clip_poly(clip,polygons):

    pc = pyclipper.Pyclipper()
    pc.AddPath(clip, pyclipper.PT_CLIP, True)
    pc.AddPaths(polygons, pyclipper.PT_SUBJECT, True)
    solution = pc.Execute(pyclipper.CT_INTERSECTION, pyclipper.PFT_EVENODD, pyclipper.PFT_EVENODD)

    return solution
예제 #24
0
def raster_area(edgepath, delta, ymin1, ymax1, xmin1, xmax1):
    #
    # raster a 2D region
    #
    # find row-edge intersections
    #
    xyscale = float(sxyscale.get())
    overlap = float(soverlap.get())
    tooldia = (float(sdia.get()) / xyscale) * (10 ** gerber_data.fraction)
    rastlines = []
    starty = ymin1
    endy = ymax1
    startx = round(xmax1, 2)
    endx = round(xmin1, 2)
    numrows = int(math.floor((endy - starty) / (tooldia * overlap)))
    crast = pyclipper.Pyclipper()
    edgepath = offset_poly(edgepath, delta)
    result = []

    for row in range(numrows + 1):
        rastlines.append([])
        rastlines[row].append([startx, round((starty + row * (tooldia * overlap)), 4)])
        rastlines[row].append([endx, round((starty + row * (tooldia * overlap)), 4)])
        startx, endx = endx, startx

    crast.AddPaths(pcb_edges, pyclipper.PT_CLIP,True)
    crast.AddPaths(rastlines, pyclipper.PT_SUBJECT, False)
    rastlines = crast.Execute2(pyclipper.CT_INTERSECTION, pyclipper.PFT_EVENODD, pyclipper.PFT_EVENODD)

    crast.Clear()
    rastlines = pyclipper.PolyTreeToPaths(rastlines)

    ##
    crast.AddPaths(edgepath, pyclipper.PT_CLIP, True)
    crast.AddPaths(rastlines, pyclipper.PT_SUBJECT, False)
    rastlines = crast.Execute2(pyclipper.CT_DIFFERENCE, pyclipper.PFT_POSITIVE, pyclipper.PFT_POSITIVE)

    crast.Clear()

    rastlines = pyclipper.PolyTreeToPaths(rastlines)
    # polyclip.sort(key=lambda x: (x[0][1],x[0][0]))
    # polyclip.sort(key=lambda x: x[0][1])
    # polyclip.sort(key=lambda x: x[0][0])
    rastltor = []
    rastrtol = []
    for segs in rastlines:
        if (segs[0][0] < segs[1][0]):
            rastltor.append(segs)
        else:
            rastrtol.append(segs)
    rastltor.sort(key=lambda x: (x[0][1], x[0][0]))
    rastrtol.sort(key=lambda x: (x[0][1], -x[0][0]))

    result.extend(rastltor)
    result.extend(rastrtol)
    result.sort(key=lambda x: x[0][1])

    return result
예제 #25
0
 def joinPolys(self, clip, subj):
     pc = pyclipper.Pyclipper()
     pc.AddPath(pyclipper.scale_to_clipper(clip), pyclipper.PT_CLIP, True)
     pc.AddPath(pyclipper.scale_to_clipper(subj), pyclipper.PT_SUBJECT,
                True)
     solution = pyclipper.scale_from_clipper(
         pc.Execute(pyclipper.CT_UNION, pyclipper.PFT_EVENODD,
                    pyclipper.PFT_EVENODD))
     return solution
예제 #26
0
def verifcontrainte(rect, polygone):
	try:
		pc = pyclipper.Pyclipper()
		pc.AddPath(polygone, pyclipper.PT_SUBJECT, True)
		pc.AddPath(rect, pyclipper.PT_CLIP, True)
		clip = pc.Execute(pyclipper.CT_INTERSECTION, pyclipper.PFT_EVENODD, pyclipper.PFT_EVENODD)
		return (clip!=[]) and (len(clip[0])==len(rect)) and all(list(map(lambda e:list(e) in clip[0], rect)))
	except pyclipper.ClipperException:
		return False
예제 #27
0
def intersection(poly1, poly2):
    old_stdout = sys.stdout
    sys.stdout = mystdout = StringIO()
    c = pyclipper.Pyclipper()
    c.add_polygon(poly1)
    c.sub_polygon(poly2)
    result = c.execute(0)
    sys.stdout = old_stdout
    return result
예제 #28
0
def get_intersection(polys):
    pc = pyclipper.Pyclipper()
    # PT_SUBJECT
    # PT_CLIP
    for poly in polys[:-1]:
        pc.AddPath(poly, pyclipper.PT_SUBJECT, True)
    pc.AddPath(polys[-1], pyclipper.PT_CLIP, True)
    return pc.Execute(pyclipper.CT_INTERSECTION, pyclipper.PFT_NONZERO,
                      pyclipper.PFT_NONZERO)
예제 #29
0
 def getClipSolutions(self, clip, subj):
     pc = pyclipper.Pyclipper()
     pc.AddPath(pyclipper.scale_to_clipper(clip), pyclipper.PT_CLIP, True)
     pc.AddPaths(pyclipper.scale_to_clipper(subj), pyclipper.PT_SUBJECT,
                 True)
     solution = pyclipper.scale_from_clipper(
         pc.Execute(pyclipper.CT_XOR, pyclipper.PFT_EVENODD,
                    pyclipper.PFT_EVENODD))
     return solution
예제 #30
0
 def intersectionOfShapes(self, mask, polys):
     pc = pyclipper.Pyclipper()
     pc.AddPaths(pyclipper.scale_to_clipper(mask), pyclipper.PT_CLIP, True)
     pc.AddPaths(pyclipper.scale_to_clipper(polys), pyclipper.PT_SUBJECT,
                 True)
     solution = pyclipper.scale_from_clipper(
         pc.Execute(pyclipper.CT_INTERSECTION, pyclipper.PFT_EVENODD,
                    pyclipper.PFT_EVENODD))
     return solution