Пример #1
0
def test_geometries():

    # geometries_from_bbox - bounding box query to return empty GeoDataFrame
    gdf = ox.geometries_from_bbox(0.009, -0.009, 0.009, -0.009, tags={"building": True})

    # geometries_from_bbox - successful
    north, south, east, west = ox.utils_geo.bbox_from_point(location_point, dist=500)
    tags = {"landuse": True, "building": True, "highway": True}
    gdf = ox.geometries_from_bbox(north, south, east, west, tags=tags)
    fig, ax = ox.plot_footprints(gdf)

    # geometries_from_point - tests multipolygon creation
    gdf = ox.geometries_from_point((48.15, 10.02), tags={"landuse": True}, dist=2000)

    # geometries_from_place - includes test of list of places
    tags = {"amenity": True, "landuse": ["retail", "commercial"], "highway": "bus_stop"}
    gdf = ox.geometries_from_place([place1], tags=tags)

    # geometries_from_address - includes testing overpass settings and snapshot from 2019
    ox.settings.overpass_settings = '[out:json][timeout:200][date:"2019-10-28T19:20:00Z"]'
    gdf = ox.geometries_from_address(address, tags=tags)

    # geometries_from_xml - tests error handling of clipped XMLs with incomplete geometry
    gdf = ox.geometries_from_xml("tests/input_data/planet_10.068,48.135_10.071,48.137.osm")

    # test loading a geodataframe from a local .osm xml file
    with bz2.BZ2File("tests/input_data/West-Oakland.osm.bz2") as f:
        handle, temp_filename = tempfile.mkstemp(suffix=".osm")
        os.write(handle, f.read())
        os.close(handle)
    for filename in ("tests/input_data/West-Oakland.osm.bz2", temp_filename):
        gdf = ox.geometries_from_xml(filename)
        assert "Willow Street" in gdf["name"].values
    os.remove(temp_filename)
Пример #2
0
def get_footprints(perimeter=None,
                   point=None,
                   radius=None,
                   footprint='building'):

    if perimeter is not None:
        # Boundary defined by polygon (perimeter)
        footprints = ox.geometries_from_polygon(
            union(perimeter.geometry),
            tags={footprint: True} if type(footprint) == str else footprint)
        perimeter = union(ox.project_gdf(perimeter).geometry)

    elif (point is not None) and (radius is not None):
        # Boundary defined by circle with radius 'radius' around point
        footprints = ox.geometries_from_point(
            point,
            dist=radius,
            tags={footprint: True} if type(footprint) == str else footprint)
        perimeter = GeoDataFrame(geometry=[Point(point[::-1])],
                                 crs=footprints.crs)
        perimeter = ox.project_gdf(perimeter).geometry[0].buffer(radius)

    if len(footprints) > 0:
        footprints = ox.project_gdf(footprints)

    footprints = [[x] if type(x) == Polygon else x for x in footprints.geometry
                  if type(x) in [Polygon, MultiPolygon]]
    footprints = list(
        np.concatenate(footprints)) if len(footprints) > 0 else []
    footprints = [pathify(x) for x in footprints if x.within(perimeter)]

    return footprints, perimeter
Пример #3
0
def osm_gdf_from_point(center_point, tags, dist=1000):
    """Create GeoDataFrame of OSM entities within some distance N, S, E, W of a point.

    Args:
        center_point (tuple): The (lat, lng) center point around which to get the geometries.
        tags (dict): Dict of tags used for finding objects in the selected area. Results returned are the union, not intersection of each individual tag. Each result matches at least one given tag. The dict keys should be OSM tags, (e.g., building, landuse, highway, etc) and the dict values should be either True to retrieve all items with the given tag, or a string to get a single tag-value combination, or a list of strings to get multiple values for the given tag. For example, tags = {‘building’: True} would return all building footprints in the area. tags = {‘amenity’:True, ‘landuse’:[‘retail’,’commercial’], ‘highway’:’bus_stop’} would return all amenities, landuse=retail, landuse=commercial, and highway=bus_stop.
        dist (int, optional): Distance in meters. Defaults to 1000.

    Returns:
        GeoDataFrame: A GeoDataFrame of OSM entities.
    """
    check_package("osmnx",
                  "https://osmnx.readthedocs.io/en/stable/#installation")
    import osmnx as ox

    gdf = ox.geometries_from_point(center_point, tags, dist)
    return gdf
Пример #4
0
def create_square_from_osm(crop_size: float,
                           crop_status: bool,
                           outfile: str,
                           c_osm: int,
                           point,
                           dpi=100,
                           dist=2000,
                           default_width=6):
    """

    :param crop_size: Crop size of the output
    :param crop_status: Determine whether the output will be cropped or not
    :param outfile: Outfile name
    :param c_osm: count of osm image
    :param point: (lat, long)
    :param dpi: dpi for the output image
    :param dist: distance from the given point
    :param default_width: default width for the roads
    :return:
    """
    network_type = 'drive'

    fp = f'./images/{outfile}-osm-{c_osm}.png'

    tag_building = TagTypes.building
    tag_nature = TagTypes.nature
    tag_water = TagTypes.water

    bbox = ox.utils_geo.bbox_from_point(point, dist=dist)

    try:
        G = ox.graph_from_point(point,
                                network_type=network_type,
                                dist=dist,
                                truncate_by_edge=True,
                                retain_all=True,
                                clean_periphery=True)
        gdf_building = ox.geometries_from_point(point, tag_building, dist=dist)
        gdf_nature = ox.geometries_from_point(point, tag_nature, dist=dist)
        gdf_water = ox.geometries_from_point(point, tag_water, dist=dist)

        fig, ax = ox.plot_figure_ground(G,
                                        default_width=default_width,
                                        show=False,
                                        close=True)

        if not gdf_nature.empty:
            # print('nature')
            fig, ax = ox.plot_footprints(gdf_nature,
                                         ax=ax,
                                         bbox=bbox,
                                         color='green',
                                         filepath=fp,
                                         dpi=dpi,
                                         show=False,
                                         save=True,
                                         close=True)
        if not gdf_water.empty:
            # print('water')
            fig, ax = ox.plot_footprints(gdf_water,
                                         ax=ax,
                                         bbox=bbox,
                                         color='blue',
                                         filepath=fp,
                                         dpi=dpi,
                                         show=False,
                                         save=True,
                                         close=True)
        if not gdf_building.empty:
            # print('building')
            fig, ax = ox.plot_footprints(gdf_building,
                                         ax=ax,
                                         bbox=bbox,
                                         filepath=fp,
                                         dpi=dpi,
                                         save=True,
                                         show=False,
                                         close=True)

        if crop_status:
            image = Image.open(fp)
            image = crop_image(image=image, size=crop_size)
            image.save(f"./images/{outfile}-osm-{c_osm}.png")
        return True

    except:
        return False
Пример #5
0
def get_historical_buildings_fromOSM(place,
                                     download_method,
                                     epsg=None,
                                     distance=1000):
    """    
    The function downloads and cleans buildings footprint geometries and create a buildings GeoDataFrames for the area of interest.
    The function exploits OSMNx functions for downloading the data as well as for projecting it.
    The land use classification for each building is extracted. Only relevant columns are kept.   
            
    Parameters
    ----------
    place: string, tuple
        name of cities or areas in OSM: when using "from point" please provide a (lat, lon) tuple to create the bounding box around it; when using "distance_from_address"
        provide an existing OSM address; when using "OSMplace" provide an OSM place name
    download_method: string, {"from_point", "distance_from_address", "OSMplace"}
        it indicates the method that should be used for downloading the data.
    epsg: int
        epsg of the area considered; if None OSMNx is used for the projection
    distance: float
        Specify distance from address or point
    
    Returns
    -------
    GeoDataFrames
    """

    columns = ['geometry', 'historic']

    if download_method == "distance_from_address":
        historic_buildings = ox.geometries_from_address(
            address=place, dist=distance, tags={"building": True})
    elif download_method == "OSMplace":
        historic_buildings = ox.geometries_from_place(place,
                                                      tags={"building": True})
    elif download_method == "from_point":
        historic_buildings = ox.geometries_from_point(center_point=place,
                                                      dist=distance,
                                                      tags={"building": True})
    else:
        raise downloadError(
            'Provide a download method amongst {"from_point", "distance_from_address", "OSMplace"}'
        )

    if 'heritage' in historic_buildings:
        columns.append('heritage')
    historic_buildings = historic_buildings[columns]

    if 'heritage' in historic_buildings:
        historic_buildings = historic_buildings[~(
            historic_buildings.historic.isnull()
            & historic_buildings.heritage.isnull())]
    else:
        historic_buildings = historic_buildings[~historic_buildings.historic.
                                                isnull()]

    if epsg is None:
        historic_buildings = ox.projection.project_gdf(historic_buildings)
    else:
        crs = 'EPSG:' + str(epsg)
        historic_buildings = historic_buildings.to_crs(crs)

    historic_buildings["historic"] = 1
    historic_buildings["historic"][historic_buildings["historic"] != 0] = 1
    historic_buildings = historic_buildings[['geometry', 'historic']]
    historic_buildings['area'] = historic_buildings.geometry.area

    return historic_buildings
Пример #6
0
def get_buildings_fromOSM(place, download_method, epsg=None, distance=1000):
    """    
    The function downloads and cleans buildings footprint geometries and create a buildings GeoDataFrames for the area of interest.
    The function exploits OSMNx functions for downloading the data as well as for projecting it.
    The land use classification for each building is extracted. Only relevant columns are kept.   
            
    Parameters
    ----------
    place: string, tuple
        name of cities or areas in OSM: when using "from point" please provide a (lat, lon) tuple to create the bounding box around it; when using "distance_from_address"
        provide an existing OSM address; when using "OSMplace" provide an OSM place name
    download_method: string, {"from_point", "distance_from_address", "OSMplace"}
        it indicates the method that should be used for downloading the data.
    epsg: int
        epsg of the area considered; if None OSMNx is used for the projection
    distance: float
        Specify distance from address or point
    
    Returns
    -------
    buildings_gdf: Polygon GeoDataFrame
        the buildings GeoDataFrame
    """

    columns_to_keep = [
        'amenity', 'building', 'geometry', 'historic', 'land_use_raw'
    ]

    if download_method == "distance_from_address":
        buildings_gdf = ox.geometries_from_address(address=place,
                                                   dist=distance,
                                                   tags={"building": True})
    elif download_method == "OSMplace":
        buildings_gdf = ox.geometries_from_place(place,
                                                 tags={"building": True})
    elif download_method == "from_point":
        buildings_gdf = ox.geometries_from_point(center_point=place,
                                                 dist=distance,
                                                 tags={"building": True})
    elif download_method == "OSMpolygon":
        buildings_gdf = ox.geometries_from_polygon(place,
                                                   tags={"building": True})
    else:
        raise downloadError(
            'Provide a download method amongst {"from_point", "distance_from_address", "OSMplace", "OSMpolygon}'
        )

    if epsg is None:
        buildings_gdf = ox.projection.project_gdf(buildings_gdf)
    else:
        crs = 'EPSG:' + str(epsg)
        buildings_gdf = buildings_gdf.to_crs(crs)

    buildings_gdf['land_use_raw'] = None
    for column in buildings_gdf.columns:
        if column.startswith('building:use:'):
            buildings_gdf.loc[pd.notnull(buildings_gdf[column]),
                              'land_use_raw'] = column[13:]
        if column not in columns_to_keep:
            buildings_gdf.drop(column, axis=1, inplace=True)

    buildings_gdf = buildings_gdf[~buildings_gdf['geometry'].is_empty]
    buildings_gdf['building'].replace('yes', np.nan, inplace=True)
    buildings_gdf['building'][
        buildings_gdf['building'].isnull()] = buildings_gdf['amenity']
    buildings_gdf['land_use_raw'][
        buildings_gdf['land_use_raw'].isnull()] = buildings_gdf['building']
    buildings_gdf['land_use_raw'][
        buildings_gdf['land_use_raw'].isnull()] = 'residential'

    buildings_gdf = buildings_gdf[['geometry', 'historic', 'land_use_raw']]
    buildings_gdf['area'] = buildings_gdf.geometry.area
    buildings_gdf = buildings_gdf[buildings_gdf['area'] >= 50]

    # reset index
    buildings_gdf = buildings_gdf.reset_index(drop=True)
    buildings_gdf['buildingID'] = buildings_gdf.index.values.astype('int')

    return buildings_gdf
Пример #7
0

(PT_ROT, PT_IMG, PT_DTA, PT_PRE, PT_OUT, PT_MTR) = aux.selectPath('dsk', 'Onetahi', 'temp')
PTH  = '/'.join(PT_ROT.split('/')[:-2]) + '/GEO/'
point = (-17.0188, -149.5884)
(placeName, dist) = ('Onetahi', 1000)
(COLORS, DPI) = (plo.COLORS, 500)
###############################################################################
# Image config
###############################################################################
(img_folder, extension, size) = ('images', 'png', 240)
tags = {'building': True}
###############################################################################
# Get footprints
###############################################################################
gdf = ox.geometries_from_point(point, tags, dist=dist)
gdf_proj = ox.project_gdf(gdf)
fp = f'{PTH}/{placeName}.{extension}'
fig, ax = ox.plot_footprints(
    gdf_proj, filepath=fp, 
    dpi=DPI, save=False, show=False, close=True
)
###############################################################################
# Centroids
###############################################################################
bounds = list(gdf['geometry'])
centroids = [[list(i)[0] for i in j.centroid.xy] for j in bounds]
(lons, lats) = list(zip(*centroids))
df = pd.DataFrame({'lons': lons, 'lats': lats})
df.to_csv(f'{PTH}/{placeName}.csv', index=False)
###############################################################################