How to use the shapely.geometry.Polygon 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 pyproj4 / pyproj / test / test_geod.py View on Github external
def test_geometry_area_perimeter__polygon():
    geod = Geod(ellps="WGS84")
    assert_almost_equal(
        geod.geometry_area_perimeter(
            Polygon(LineString([Point(1, 2), Point(3, 4), Point(5, 2)]))
        ),
        (-49187690467.58623, 1072185.2103813463),
        decimal=2,
    )
github Toblerity / Shapely / tests / test_iterops.py View on Github external
def test_iterops(self):

        coords = ((0.0, 0.0), (0.0, 1.0), (1.0, 1.0), (1.0, 0.0), (0.0, 0.0))
        polygon = Polygon(coords)
        points = [Point(0.5, 0.5), Point(2.0, 2.0)]

        # List of the points contained by the polygon
        self.assertTrue(
            all([isinstance(x, Point)
                 for x in iterops.contains(polygon, points, True)]))

        # 'True' is the default value
        self.assertTrue(
            all([isinstance(x, Point)
                 for x in iterops.contains(polygon, points)]))

        # Test a false value
        self.assertTrue(
            all([isinstance(x, Point)
                 for x in iterops.contains(polygon, points, False)]))
github SBU-BMI / quip_distro / utility / create_composite_dataset.py View on Github external
current_polygon=row[polygon_index] ;        
            new_polygon=[];            
            tmp_str=str(current_polygon);            
            tmp_str=tmp_str.replace('[','');
            tmp_str=tmp_str.replace(']','');
            split_str=tmp_str.split(':');
            for i in range(0, len(split_str)-1, 2):
              point=[float(split_str[i])/float(image_width),float(split_str[i+1])/float(image_height)];
              new_polygon.append(point);              
            tmp_poly=[tuple(i) for i in new_polygon];
            computer_polygon = Polygon(tmp_poly);
            computer_polygon = computer_polygon.buffer(0);
            has_intersects=False;
            for annotation in annotation_title_intersect_list:
              tmp_poly2=[tuple(j) for j in annotation];
              annotation_polygon = Polygon(tmp_poly2);
              annotation_polygon = annotation_polygon.buffer(0);
              if (computer_polygon.intersects(annotation_polygon)): 
                has_intersects=True;
                break;                
            has_intersects_excluded=False;
            for annotation_excluded in exclude_annotation_intersect_list:
              excluded_annotation=annotation_excluded[1];
              #print "--- excluded_annotation is ---";
              #print excluded_annotation;
              tmp_poly3=[tuple(j) for j in excluded_annotation];
              annotation_excluded_poly = Polygon(tmp_poly3);
              annotation_excluded_poly = annotation_excluded_poly.buffer(0);
              if (computer_polygon.intersects(annotation_excluded_poly)): 
                has_intersects_excluded=True;
                #print "has_intersects_excluded is true.";
                break;
github popupcad / popupcad / popupcad / graphics2d / text.py View on Github external
def generic_polys_to_shapely(self,generic_polygons,scaling):
        shapelies = [item.to_shapely(scaling = scaling) for item in generic_polygons]
        
        if len(shapelies) > 1:
            obj1 = shapelies.pop(0)
            while shapelies:
                obj1 = obj1.symmetric_difference(shapelies.pop(0))
        elif len(shapelies) ==1 :
            obj1 = shapelies[0]
        else:
            obj1 = sg.Polygon()
        return obj1
github qurator-spk / sbb_textline_detector / qurator / sbb_textline_detector / main.py View on Github external
def find_polygons_size_filter(self, contours, median_area, scaler_up=1.2, scaler_down=0.8):
        found_polygons_early = list()

        for c in contours:
            if len(c) < 3:  # A polygon cannot have less than 3 points
                continue

            polygon = geometry.Polygon([point[0] for point in c])
            area = polygon.area
            # Check that polygon has area greater than minimal area
            if area >= median_area * scaler_down and area <= median_area * scaler_up:
                found_polygons_early.append(
                    np.array([point for point in polygon.exterior.coords], dtype=np.uint))
        return found_polygons_early
github OpenGeoscience / geonotebook / geonotebook / annotations.py View on Github external
def subset(self, raster_data, **kwargs):
        # It is possible our user has drawn a polygon where part of the
        # shape is outside the dataset,  intersect with the rasterdata
        # shape to make sure we don't try to select/mask data that is
        # outside the bounds of our dataset.

        # Convert the image corner coordinates to WGS84
        trgt_srs = CRS.from_string("EPSG:4326")
        src_srs = raster_data.crs
        transformed = [transform_coordinates(src_srs, trgt_srs, [i[0]], [i[1]])
                       for i in raster_data.shape.exterior.coords]
        reprojected_data_extent = sPolygon(transformed)
        clipped = self.intersection(reprojected_data_extent)

        # Polygon is completely outside the dataset, return whatever
        # would have been returned by get_data()
        if not bool(clipped):
            ul = raster_data.index(self.bounds[0], self.bounds[1])
            lr = raster_data.index(self.bounds[2], self.bounds[3])
            window = self.get_data_window(ul[0], ul[1], lr[0], lr[1])

            return raster_data.get_data(window=window, **kwargs)

        ul = raster_data.index(clipped.bounds[0], clipped.bounds[1])
        lr = raster_data.index(clipped.bounds[2], clipped.bounds[3])
        window = self.get_data_window(ul[0], ul[1], lr[0], lr[1])

        data = raster_data.get_data(window=window, **kwargs)
github gboeing / osmnx / osmnx / buildings.py View on Github external
response_jsons = []

    # pass server memory allocation in bytes for the query to the API
    # if None, pass nothing so the server will use its default allocation size
    # otherwise, define the query's maxsize parameter value as whatever the
    # caller passed in
    if memory is None:
        maxsize = ''
    else:
        maxsize = '[maxsize:{}]'.format(memory)

    # define the query to send the API
    if by_bbox:
        # turn bbox into a polygon and project to local UTM
        polygon = Polygon([(west, south), (east, south), (east, north), (west, north)])
        geometry_proj, crs_proj = project_geometry(polygon)

        # subdivide it if it exceeds the max area size (in meters), then project
        # back to lat-long
        geometry_proj_consolidated_subdivided = consolidate_subdivide_geometry(geometry_proj, max_query_area_size=max_query_area_size)
        geometry, _ = project_geometry(geometry_proj_consolidated_subdivided, crs=crs_proj, to_latlong=True)
        log('Requesting building footprints data within bounding box from API in {:,} request(s)'.format(len(geometry)))
        start_time = time.time()

        # loop through each polygon rectangle in the geometry (there will only
        # be one if original bbox didn't exceed max area size)
        for poly in geometry:
            # represent bbox as south,west,north,east and round lat-longs to 8
            # decimal places (ie, within 1 mm) so URL strings aren't different
            # due to float rounding issues (for consistent caching)
            west, south, east, north = poly.bounds
github postgis-t / postgis-t / src / python / TestTrajectory.py View on Github external
def test_intersection_verificar_se_interpolacao_retorna_o_valor_correto(self):

        line = LineString([(0, 0, 1), (2, 2, 2), (0, 2, 3)])
        polygon = Polygon([(1, 1), (1, 2), (1, 3), (4, 3), (4, 1), (1, 1)])

        result = LineString([(1, 1, 1.5), (2, 2, 2), (1, 2, 2.5)])
        inter = line.intersection(polygon)

        resultTime = np.array(result)[:, 2]
        time = np.array(inter)[:, 2]

        assert (time[0] == resultTime[0])
        assert (time[1] == resultTime[1])
        assert (time[2] == resultTime[2])
    pass
github pwcazenave / PyFVCOM / PyFVCOM / mesh_prep.py View on Github external
def close_channels(modified_boundary_poly, islands_dict, resolution, remove_small_islands_first=True, remove_small_islands_last=False):
    """


    """

    ## Simplify the islands first so there are (hopefully!) less things to intersect with the boundary
    
    # Convert into polygons, remove any with area < resolution^2 as they are too tiny to consider, and buffer    
    poly_islands = {}
    islands_to_process = []
    counter = 0
    for this_island in islands_dict.values():
        this_poly = sg.Polygon(this_island)        
        if not remove_small_islands_first:
            poly_islands[counter] = this_poly.buffer(resolution)
            islands_to_process.append(counter)
            counter += 1
        elif this_poly.area > resolution**2:
            poly_islands[counter] = this_poly.buffer(resolution)
            islands_to_process.append(counter)
            counter += 1

    bdry_poly = sg.Polygon(modified_boundary_poly)    
    poly_islands[counter] = bdry_poly.buffer(resolution)
    islands_to_process.append(counter)
    counter += 1

    # Loop over polygons, if they intersect then merge (and remove holes) and put at the bottom of the list