How to use the shapely.geometry.LinearRing function in shapely

To help you get started, we’ve selected a few shapely examples, based on popular ways it is used in public projects.

Secure your code as it's written. Use Snyk Code to scan source code in minutes - no build needed - and fix issues immediately.

github OGGM / oggm / oggm / core / preprocessing / geometry.py View on Github external
sr = region_sizes.pop(am)
        for ss in region_sizes:
            if (ss / sr) > 0.2:
                log.warning('(%s) this blob was unusually large', gdir.rgi_id)
        mask[:] = 0
        mask[np.where(regions == (am+1))] = 1

    c = cntr.Cntr(x, y, mask)
    nlist = c.trace(0.5)
    if len(nlist) == 0:
        raise RuntimeError('Mask polygon is empty')
    # The first half are the coordinates. The other stuffs I dont know
    ngeoms = len(nlist)//2 - 1

    # First is the exterior, the rest are nunataks
    e_line = shpg.LinearRing(nlist[0])
    i_lines = [shpg.LinearRing(ipoly) for ipoly in nlist[1:ngeoms+1]]

    poly = shpg.Polygon(e_line, i_lines).buffer(0)
    if not poly.is_valid:
        raise RuntimeError('Mask polygon not valid.')
    poly_no = shpg.Polygon(e_line).buffer(0)
    if not poly_no.is_valid:
        raise RuntimeError('Mask polygon not valid.')
    return poly, poly_no
github SciTools / cartopy / lib / cartopy / crs.py View on Github external
def _set_boundary(self, coords):
        self._boundary = sgeom.LinearRing(coords.T)
        mins = np.min(coords, axis=1)
        maxs = np.max(coords, axis=1)
        self._x_limits = mins[0], maxs[0]
        self._y_limits = mins[1], maxs[1]
        self._threshold = np.diff(self._x_limits)[0] * 0.02
github abey79 / hatched / hatched / hatched.py View on Github external
def _build_mask(cnt):
    lr = [LinearRing(p[:, [1, 0]]) for p in cnt if len(p) >= 4]

    mask = None
    for r in lr:
        if mask is None:
            mask = Polygon(r)
        else:
            if r.is_ccw:
                mask = mask.union(Polygon(r).buffer(0.5))
            else:
                mask = mask.difference(Polygon(r).buffer(-0.5))

    return mask
github david-zwicker / video-analysis / video / analysis / regions.py View on Github external
if resolution is None:
        # determine resolution from minimal distance of consecutive points
        dist_min = np.inf
        for p1, p2 in itertools.izip(np.roll(points, 1, axis=0), points):
            dist = curves.point_distance(p1, p2)
            if dist > 0:
                dist_min = min(dist_min, dist)
        resolution = 0.5*dist_min
        
        # limit the resolution such that there are at most 2048 points
        dim_max = np.max(np.ptp(points, axis=0)) #< longest dimension
        resolution = max(resolution, dim_max/2048)

    # build a linear ring with integer coordinates
    ps_int = np.array(np.asarray(points)/resolution, np.int)
    ring = geometry.LinearRing(ps_int)

    # get the image of the linear ring by plotting it into a mask
    x_min, y_min, x_max, y_max = ring.bounds
    shape = ((y_max - y_min) + 3, (x_max - x_min) + 3)
    x_off, y_off = int(x_min - 1), int(y_min - 1)
    mask = np.zeros(shape, np.uint8)
    cv2.fillPoly(mask, [ps_int], 255, offset=(-x_off, -y_off))

    # find the contour of this mask to recover the exterior contour
    contours = cv2.findContours(mask, cv2.RETR_EXTERNAL,
                                cv2.CHAIN_APPROX_SIMPLE,
                                offset=(x_off, y_off))[1]
    return np.array(np.squeeze(contours))*resolution
github sbochkar / coverage_path_planning / pkg / discritizers / line / min_alt_discrt.py View on Github external
Thigns to watch out for:
		What to do with invalid polygons
		Narrow corridors between holes may result in no lines even when
			there is space for it. Because of equidistance between lines

		We can get disconnected polygons if there narrow corridors

		The uncovered area in the end of the polygon can be handled easily here
	Returns a set of lines and their coordinates
	"""


	P = rotation.rotate_polygon(P, -theta)

	# Parallel offset the boundaries of ext and holes
	lr_ext = LinearRing(P[0])
	offset_ext = lr_ext.parallel_offset(width/2, side='left', join_style=1)

	lr_new_holes = []
	for hole in P[1]:
		lr_hole = LinearRing(hole)
		offset_hole = lr_hole.parallel_offset(width/2, side='left', join_style=1)
		lr_new_holes.append(offset_hole)

	if offset_ext.is_empty:
		print offset_ext
		print("Line generation ERROR: Shrunk polygon is not valid")
		return []
	
	shrunk_polygon = Polygon(offset_ext, lr_new_holes)

	if not shrunk_polygon.is_valid:
github sbochkar / coverage_path_planning / pkg / decompositions / min_alt / altitudes.py View on Github external
print("p1_v_i:%d p1_w_i:%d"%(p1_v_idx, p1_w_idx))
	print("p2_v_i:%d p2_w_i:%d"%(p2_v_idx, p2_w_idx))

	if (p1_v_idx == 0) and (p1_w_idx == 1): left_chain = p1[1:]+[p1[0]]
	elif (p1_v_idx == 0) and (p1_w_idx == len(p1-1)): left_chain = p1[:]
	elif p1_v_idx < p1_w_idx: left_chain = p1[p1_w_idx:]+p1[:p1_v_idx+1]
	elif p1_w_idx < p1_v_idx: left_chain = p1[p1_v_idx:]+p1[:p1_w_idx+1]

	if (p2_v_idx == 0) and (p2_w_idx == 1): right_chain = p2[1:]
	elif (p2_v_idx == 0) and (p2_w_idx == len(p2-1)): right_chain = p2[:]
	elif p2_v_idx < p2_w_idx: right_chain = p2[p2_w_idx:]+p2[:p2_v_idx]
	elif p2_w_idx < p2_v_idx: right_chain = p2[p2_v_idx:]+p2[:p2_w_idx]

	print left_chain
	print right_chain
	lr_left = LinearRing(left_chain); lr_right = LinearRing(right_chain)

	if lr_left.is_ccw:
		if lr_right.is_ccw: fuse = left_chain+right_chain
		else: 				fuse = left_chain+right_chain[::-1]
	else:
		if lr_right.is_ccw: fuse = left_chain+right_chain[::-1]
		else: 				fuse = left_chain+right_chain

	return fuse
github huskyroboticsteam / 2016-17 / Prototyping / Rover / BBB / path_finding.py View on Github external
Finds the point closest to point p that is outside of the area and at least epsilon away from it.
    Assumes that the area doesn't have holes.
    Internal use only.
    Args:
        p (Point): The point
        area (MultiPolygon or Polygon): the area
    Returns (Point): the desired point
    """
    if area.is_empty:
        return p
    area = area.buffer(epsilon)
    if not area.contains(p):
        return p
    poly = [a for a in to_multi_polygon(area) if a.contains(p)][0]
    assert poly.contains(p)
    poly_ext = LinearRing(poly.exterior.coords)
    d = poly_ext.project(p)
    return poly_ext.interpolate(d)
github sbochkar / coverage_path_planning / pkg / costs / dubins_cost.py View on Github external
def has_collision(P, edge):

	exterior = LinearRing(P[0])
	holes = P[1]
	segment = LineString(edge)

	if exterior.intersects(segment): return True

	for hole in holes:
		interior = LinearRing(hole)
		if interior.intersects(segment): return True
	return False
github OGGM / oggm / oggm / core / centerlines.py View on Github external
log.debug('(%s) we had to cut a blob from the catchment', rid)
        # Check the size of those
        region_sizes = [np.sum(regions == r) for r in np.arange(1, nregions+1)]
        am = np.argmax(region_sizes)
        # Check not a strange glacier
        sr = region_sizes.pop(am)
        for ss in region_sizes:
            if (ss / sr) > 0.2:
                log.warning('(%s) this blob was unusually large', rid)
        mask[:] = 0
        mask[np.where(regions == (am+1))] = 1

    nlist = measure.find_contours(mask, 0.5)
    # First is the exterior, the rest are nunataks
    e_line = shpg.LinearRing(nlist[0][:, ::-1])
    i_lines = [shpg.LinearRing(ipoly[:, ::-1]) for ipoly in nlist[1:]]

    poly = shpg.Polygon(e_line, i_lines).buffer(0)
    if not poly.is_valid:
        raise GeometryError('Mask to polygon conversion error.')
    poly_no = shpg.Polygon(e_line).buffer(0)
    if not poly_no.is_valid:
        raise GeometryError('Mask to polygon conversion error.')
    return poly, poly_no
github sbochkar / coverage_path_planning / pkg / costs / dubins_cost.py View on Github external
def has_collision(P, edge):

	exterior = LinearRing(P[0])
	holes = P[1]
	segment = LineString(edge)

	if exterior.intersects(segment): return True

	for hole in holes:
		interior = LinearRing(hole)
		if interior.intersects(segment): return True
	return False