Python shapely.ops.linemerge() Examples

The following are 12 code examples of shapely.ops.linemerge(). You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may also want to check out all available functions/classes of the module shapely.ops , or try the search function .
Example #1
Source File: postprocess.py    From argus-tgs-salt with MIT License 5 votes vote down vote up
def draw_v_pair(pair, strip, l):
    # Drow polligons between two masks from test
    if l > 0:
        roi_points = [(0, 0), (img_side_len, 0),
                      (img_side_len*l, img_side_len), (0, img_side_len)]
        roi_poly = Polygon(roi_points)
        top_tile = find_points(pair[0])
        bottom_tile = find_points(pair[1])
        top_tile_pos, top_tile_neg = top_tile
        bottom_tile_pos, bottom_tile_neg = bottom_tile
        v_shift = l * img_side_len

        square_points = [(0, 0), (img_side_len, 0), (img_side_len, v_shift), (0, v_shift)]
        square_poly = Polygon(square_points)
        lines = []
        for i in range(len(top_tile_pos[bottom])):
            line = LineString([(top_tile_pos[bottom][i], 0),
                               (bottom_tile_pos[top][i], v_shift),
                               (bottom_tile_neg[top][i], v_shift),
                               (top_tile_neg[bottom][i], 0)])
            lines.append(line)

        merged = linemerge([square_poly.boundary, *lines])
        borders = unary_union(merged)
        polygons = []
        for poly in polygonize(borders):
            polygons.append(poly)
        masks = [mask_for_polygons([polygons[i]], (v_shift, img_side_len))
                 for i in range(0, len(polygons), 2)]
        mask = (np.any(masks, axis=0)*255).astype(np.uint8)
        return mask
    return None 
Example #2
Source File: drawing.py    From xy with MIT License 5 votes vote down vote up
def linemerge(self):
        lines = ops.linemerge([geometry.LineString(x) for x in self.paths])
        return Drawing.from_shapely(lines) 
Example #3
Source File: connectivity_potential.py    From CityEnergyAnalyst with MIT License 5 votes vote down vote up
def snap_points(points, lines, tolerance, crs):
    length = lines.shape[0]
    for i in range(length):
        for point in points.geometry:
            line = lines.loc[i, "geometry"]
            line._crs = crs
            point._crs = crs
            point_inline_projection = line.interpolate(line.project(point))
            point_inline_projection._crs = crs
            distance_to_line = point.distance(point_inline_projection)
            if (point.x, point.y) in line.coords:
                x = "nothing"
            else:
                if distance_to_line < tolerance:
                    buff = point.buffer(0.1)
                    ### Split the line on the buffer
                    geometry = split(line, buff)
                    geometry._crs = crs
                    line_1_points = [tuple(xy) for xy in geometry[0].coords[:-1]]
                    line_1_points.append((point.x, point.y))
                    line_2_points = []
                    line_2_points.append((point.x, point.y))
                    line_2_points.extend([x for x in geometry[-1].coords[1:]])
                    ### Stitch together the first segment, the interpolated point, and the last segment
                    new_line = linemerge((LineString(line_1_points), LineString(line_2_points)))
                    lines.loc[i, "geometry"] = new_line

    G = points["geometry"].apply(lambda geom: geom.wkb)
    points = points.loc[G.drop_duplicates().index]

    G = lines["geometry"].apply(lambda geom: geom.wkb)
    lines = lines.loc[G.drop_duplicates().index]

    return points, lines 
Example #4
Source File: connectivity_potential.py    From CityEnergyAnalyst with MIT License 5 votes vote down vote up
def one_linestring_per_intersection(lines, crs):
    """ Move line endpoints to intersections of line segments.

    Given a list of touching or possibly intersecting LineStrings, return a
    list LineStrings that have their endpoints at all crossings and
    intersecting points and ONLY there.

    Args:
        a list of LineStrings or a MultiLineString

    Returns:
        a list of LineStrings
    """
    lines_merged = linemerge(lines)

    # intersecting multiline with its bounding box somehow triggers a first intersection
    try:
        bounding_box = box(*lines_merged.bounds)
        lines_merged = lines_merged.intersection(bounding_box)
    except:
        # if the bounding_box fails, then revert to lines merge.
        print('bounding box method did not work, falling to a more simple method, no need to worry')

    # merge the result
    lines_merged = linemerge(lines_merged)

    lines = [line for line in lines_merged]
    df = gdf(geometry=lines, crs=crs)
    return df 
Example #5
Source File: runways.py    From traffic with MIT License 5 votes vote down vote up
def shape(self) -> base.BaseGeometry:
        return linemerge(shape(x["geometry"]) for x in self.geojson()) 
Example #6
Source File: flightplan.py    From traffic with MIT License 5 votes vote down vote up
def shape(self) -> LineString:
        return linemerge([x.shape for x in self._parse() if x is not None]) 
Example #7
Source File: alien_letter.py    From vpype with MIT License 5 votes vote down vote up
def generate() -> MultiLineString:
    """
    A python module called by the `script` command must implement this function, which takes
    no arguments and return a MultiLineString object.
    :return: resulting MultiLineString
    """
    segs = []

    # horizontal segments
    for i in range(math.floor(N / 2)):
        for j in range(M):
            append_maybe([(i, j), (i + 1, j)], segs)

    # add half horizontal segments
    if N % 2 == 0:
        for j in range(M):
            append_maybe([((N / 2) - 1, j), (N / 2, j)], segs)

    # add vertical segments
    for i in range(math.ceil(N / 2)):
        for j in range(M - 1):
            append_maybe([(i, j), (i, j + 1)], segs)

    half_mls = MultiLineString(segs)
    other_mls = affinity.translate(affinity.scale(half_mls, -1, 1, origin=(0, 0)), N - 1, 0)

    return ops.linemerge(ops.unary_union([half_mls, other_mls])) 
Example #8
Source File: base.py    From pvfactors with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def merge_surfaces(self):
        """Merge all surfaces in the shade collection into one contiguous
        surface, even if they're not contiguous, by using bounds."""
        if len(self.list_surfaces) > 1:
            merged_lines = linemerge(self.list_surfaces)
            minx, miny, maxx, maxy = merged_lines.bounds
            surf_1 = self.list_surfaces[0]
            new_pvsurf = PVSurface(
                coords=[(minx, miny), (maxx, maxy)],
                shaded=self.shaded, normal_vector=surf_1.n_vector,
                param_names=surf_1.param_names)
            self.list_surfaces = [new_pvsurf]
            self.update_geom_collection(self.list_surfaces) 
Example #9
Source File: handibot-polygons.py    From axi with MIT License 5 votes vote down vote up
def polygon(n, r, br, notch=False):
    p = regular_polygon(n, 0, 0, r)
    g = geometry.Polygon(p)
    g = g.buffer(br).exterior
    if notch:
        g = g.difference(polygon_splits(n, 0, 0, r * 2, br * 2))
        g = ops.linemerge(g)
    p = axi.shapely_to_paths(g)
    return axi.Drawing(p).origin() 
Example #10
Source File: sections.py    From py-pdf-parser with MIT License 5 votes vote down vote up
def __plot_edges(self, to_plot: List, edges: List, vertices: List, label: str):
        lines = []
        for edge_idx in to_plot:
            edge = edges[edge_idx]
            start_vertex = vertices[edge.start]
            end_vertex = vertices[edge.end]
            # Note it could be that the edge is supposed to be parabola (edge.is_linear
            # will be false), but in our case we always have boxes with 90 degree
            # corners. If it's a parabola then the focus is one of these corners, and by
            # drawing a line instead of a parabola we at worse cut through this point,
            # which is fine.
            lines.append(
                geometry.LineString(
                    [[start_vertex.X, start_vertex.Y], [end_vertex.X, end_vertex.Y]]
                )
            )
        merged_line = ops.linemerge(geometry.MultiLineString(lines))
        kwargs = {"label": label, "alpha": 0.5, "color": self.__colour_mapping[label]}
        # Merged line is either a MultiLineString which means we need to draw multiple
        # lines, or it is a LineString which means we only need to draw one.
        if isinstance(merged_line, geometry.MultiLineString):
            for line in merged_line:
                xs, ys = self.__simplify_outlines(line)
                self.__ax.plot(xs, ys, **kwargs)
                kwargs.pop(
                    "label", None
                )  # Only pass label once for single legend entry
        else:
            xs, ys = self.__simplify_outlines(merged_line)
            self.__ax.plot(xs, ys, **kwargs) 
Example #11
Source File: postprocess.py    From argus-tgs-salt with MIT License 4 votes vote down vote up
def find_fit_corners(tile1, tile2, left):
    # Draw missed corners polygons
    c = can_be_corner(tile1, tile2, left)
    ret = None
    if c is not None:
        x1 = c[0][0]
        x2 = c[1][0]
        y1 = c[0][1]
        y2 = c[1][1]
        pol = fit_third_order(x1, x2, y1, y2, c[0][2], c[1][2])
        if pol is not None:
            pol_points = []
            if left:
                pol_points.append((min(y1,y2), min(x1, x2)))
            else:
                pol_points.append((min(y1,y2), max(x1, x2)))
            pol_points_a = []
            for x_i in range(min(x1, x2), max(x1, x2)+1):
                y_i = int(poly_3(*pol, x_i))
                pol_points_a.append((int(y_i), int(x_i)))
            if all([0<=x[0]<=img_side_len for x in pol_points_a])\
                    and all([0<=x[1]<=img_side_len for x in pol_points_a]):
                pol_points.extend(pol_points_a)
            if left:
                pol_points.append((max(y1, y2), max(x1, x2)))
                pol_points.append((img_side_len, 0))
            else:
                pol_points.append((max(y1,y2), min(x1, x2)))
                pol_points.append((img_side_len, img_side_len))
            
            square_points = [(0, 0), (img_side_len, 0),
                             (img_side_len, img_side_len),
                             (0, img_side_len)]
            square_poly = Polygon(square_points)
            line = LineString(pol_points)

            merged = linemerge([square_poly.boundary, line])
            borders = unary_union(merged)
            polygons = []
            for poly in polygonize(borders):
                polygons.append(poly)
            if len(polygons) > 1:
                return mask_for_polygons([polygons[1]],
                                         (img_side_len, img_side_len)) 
Example #12
Source File: segmentation.py    From kraken with Apache License 2.0 4 votes vote down vote up
def _interpolate_lines(clusters, elongation_offset, extent, st_map, end_map):
    """
    Interpolates the baseline clusters and sets the correct line direction.
    """
    logger.debug('Reticulating splines')
    lines = []
    extent = geom.Polygon([(0, 0), (extent[1]-1, 0), (extent[1]-1, extent[0]-1), (0, extent[0]-1), (0, 0)])
    f_st_map = maximum_filter(st_map, size=20)
    f_end_map = maximum_filter(end_map, size=20)
    for cluster in clusters[1:]:
        # find start-end point
        points = [point for edge in cluster for point in edge]
        dists = squareform(pdist(points))
        i, j = np.unravel_index(dists.argmax(), dists.shape)
        # build adjacency matrix for shortest path algo
        adj_mat = np.full_like(dists, np.inf)
        for l, r in cluster:
            idx_l = points.index(l)
            idx_r = points.index(r)
            adj_mat[idx_l, idx_r] = dists[idx_l, idx_r]
        # shortest path
        _, pr = shortest_path(adj_mat, directed=False, return_predecessors=True, indices=i)
        k = j
        line = [points[j]]
        while pr[k] != -9999:
            k = pr[k]
            line.append(points[k])
        # smooth line
        line = np.array(line[::-1])
        line = approximate_polygon(line[:,[1,0]], 1)
        lr_dir = line[0] - line[1]
        lr_dir = (lr_dir.T  / np.sqrt(np.sum(lr_dir**2,axis=-1))) * elongation_offset/2
        line[0] = line[0] + lr_dir
        rr_dir = line[-1] - line[-2]
        rr_dir = (rr_dir.T  / np.sqrt(np.sum(rr_dir**2,axis=-1))) * elongation_offset/2
        line[-1] = line[-1] + rr_dir
        ins = geom.LineString(line).intersection(extent)
        if ins.type == 'MultiLineString':
            ins = linemerge(ins)
            # skip lines that don't merge cleanly
            if ins.type != 'LineString':
                continue
        line = np.array(ins, dtype='uint')
        l_end = tuple(line[0])[::-1]
        r_end = tuple(line[-1])[::-1]
        if f_st_map[l_end] - f_end_map[l_end] > 0.2 and f_st_map[r_end] - f_end_map[r_end] < -0.2:
            pass
        elif f_st_map[l_end] - f_end_map[l_end] < -0.2 and f_st_map[r_end] - f_end_map[r_end] > 0.2:
            line = line[::-1]
        else:
            logger.debug('Insufficient marker confidences in output. Defaulting to upright line.')
            if line[0][0] > line[-1][0]:
                line = line[::-1]
        lines.append(line.tolist())
    return lines