def create_image_url_v2(minlon, minlat, maxlon, maxlat, minzoom, maxzoom,
                        basetileurl, rootpath):
    for zoom in range(minzoom, maxzoom + 1):
        mintile = Tile.for_latitude_longitude(latitude=minlat,
                                              longitude=minlon,
                                              zoom=zoom)
        maxtile = Tile.for_latitude_longitude(latitude=maxlat,
                                              longitude=maxlon,
                                              zoom=zoom)

        print('mintile', 'X:', mintile.tms_x, 'Y:', mintile.tms_y, 'zoom:',
              mintile.zoom)
        print('maxtile', 'Y:', maxtile.tms_x, 'Y:', maxtile.tms_y, 'zoom:',
              maxtile.zoom)

        mintms_x, mintms_y = mintile.tms_x, mintile.tms_y
        maxtms_x, maxtms_y = maxtile.tms_x, maxtile.tms_y

        create_image_path(rootpath, zoom)

        imagelists = []
        for x in range(mintms_x, maxtms_x + 1):
            for y in range(maxtms_y, mintms_y + 1):
                savepath = './%s/%d/%d_%d.png' % (rootpath, zoom, x, y)
                tileurl = basetileurl + '&x=%d&y=%d&z=%d' % (x, y, zoom)
                imagelists.append((tileurl, savepath))

        return imagelists
Ejemplo n.º 2
0
def main():
    shp_df = gpd.GeoDataFrame.from_file(shp_file, encoding='utf-8')
    base_df = gpd.GeoDataFrame.from_file(base_file, encoding='utf-8')

    base_df['coords'] = base_df['geometry'].apply(
        lambda x: x.representative_point().coords[:])
    base_df['coords'] = [coords[0] for coords in base_df['coords']]
    shp_df['coords'] = shp_df['geometry'].apply(
        lambda x: x.representative_point().coords[:])
    shp_df['coords'] = [coords[0] for coords in shp_df['coords']]

    im_list = []
    for zoom in range(min_zoom, max_zoom + 1):
        print("----- genrate {} image -----".format(zoom))
        right_buttom_tile = Tile.for_latitude_longitude(latitude=-22.380080,
                                                        longitude=115.425220,
                                                        zoom=zoom)
        left_top_tile = Tile.for_latitude_longitude(latitude=-23.966600,
                                                    longitude=113.816970,
                                                    zoom=zoom)

        mintms_x, mintms_y = left_top_tile.tms_x, left_top_tile.tms_y
        maxtms_x, maxtms_y = right_buttom_tile.tms_x, right_buttom_tile.tms_y

        im = genrate_im(base_df,
                        shp_df,
                        mintms_x,
                        maxtms_x,
                        mintms_y,
                        maxtms_y,
                        zoom,
                        fontsize=18,
                        plt_dpi=plt_dpi)

        save_path = "./tile/tile_{}".format(zoom)
        im_list.append(
            (im, mintms_x, maxtms_x, mintms_y, maxtms_y, zoom, save_path))
        print("----- end {} -----".format(zoom))

    del base_df
    del shp_df
    gc.collect()

    start = time.perf_counter()
    loop = asyncio.get_event_loop()
    print("----- start -----")
    tasks = []
    for im, mintms_x, maxtms_x, mintms_y, maxtms_y, zoom, save_path in im_list:
        print("------------------------")
        #task = loop.create_task(genrate_tile(im, mintms_x, maxtms_x, mintms_y, maxtms_y, zoom, save_path))
        tasks.append(
            asyncio.ensure_future(
                genrate_tile(im, mintms_x, maxtms_x, mintms_y, maxtms_y, zoom,
                             save_path)))
        print("---- end ----")
    loop.run_until_complete(asyncio.wait(tasks))
    loop.close()
    # asyncio.run(handler(im_list)) # python 3.7 support
    print("Cost {} s".format(time.perf_counter() - start))
def _get_quadrant_tiles(tile):
    """Return indicies of tiles at one higher zoom (in TMS tiling scheme)"""
    ul = (tile.tms[0] * 2, tile.tms[1] * 2)

    return [Tile.from_tms(ul[0], ul[1], tile.zoom + 1),           # UL
            Tile.from_tms(ul[0], ul[1] + 1, tile.zoom + 1),       # LL
            Tile.from_tms(ul[0] + 1, ul[1], tile.zoom + 1),       # UR
            Tile.from_tms(ul[0] + 1, ul[1] + 1, tile.zoom + 1)]   # LR
Ejemplo n.º 4
0
def test_roundtrip():
    zoom_level = 18
    t = Tile.from_tms(139423, 171197, zoom_level)
    minx, maxy = t.bounds[0].pixels(zoom_level)
    maxx, miny = t.bounds[1].pixels(zoom_level)
    p = Point.from_pixel(maxx, maxy, zoom=zoom_level)
    mx, my = p.meters
    t2 = Tile.for_meters(mx, my, zoom_level)
    assert t.quad_tree == t2.quad_tree
Ejemplo n.º 5
0
 def test_get_quadrant_tiles(self):
     """Test ability to get tile children on level of increased zoom."""
     tile = Tile.from_google(0, 0, 0)
     child_tiles = _get_quadrant_tiles(tile)
     self.assertEqual(child_tiles, [
         Tile.from_google(0, 0, 1),
         Tile.from_google(0, 1, 1),
         Tile.from_google(1, 0, 1),
         Tile.from_google(1, 1, 1)
     ])
Ejemplo n.º 6
0
def get_quadrant_tiles(tile):
    """Return indicies of tiles at one higher zoom (in google tiling scheme)"""
    ul = (tile.google[0] * 2, tile.google[1] * 2)

    return [
        Tile.from_google(ul[0], ul[1], tile.zoom + 1),  # UL
        Tile.from_google(ul[0], ul[1] + 1, tile.zoom + 1),  # LL
        Tile.from_google(ul[0] + 1, ul[1], tile.zoom + 1),  # UR
        Tile.from_google(ul[0] + 1, ul[1] + 1, tile.zoom + 1)
    ]  # LR
Ejemplo n.º 7
0
    def test_finding_child_tiles(self):
        """Check if 4 correct child tiles can be found from a parent tile."""

        parent_tile = Tile.from_tms(1412, 3520, 17)
        ground_truth = [
            Tile.from_tms(x, y, z)
            for x, y, z in [(2825, 7041, 18), (2825, 7040,
                                               18), (2824, 7041,
                                                     18), (2824, 7040, 18)]
        ]
        children_tiles = _get_quadrant_tiles(parent_tile)
        self.assertCountEqual(ground_truth, children_tiles)
Ejemplo n.º 8
0
def get_tiles_bbox(tms_bbox: Tuple[int, int, int, int], zoom: int) -> Tuple[float, float, float, float]:
    # language=rst
    """
    Returns bbox of geo coordinates for tiles from tms_bbox area
    :param tms_bbox: area of the tms coordinates in the form of:
     `(min_x, min_y, max_x, max_y)`
    :param zoom:
    :return: bbox of geo coordinates in the form: `(min_lat, min_lon, max_lat, max_lon)`
    """
    points = Tile.from_tms(*tms_bbox[:2], zoom).bounds + Tile.from_tms(*tms_bbox[2:], zoom).bounds
    latitudes, longitudes = zip(*(p.latitude_longitude for p in points))
    return min(latitudes), min(longitudes), max(latitudes), max(longitudes)
Ejemplo n.º 9
0
    def georeference(self):
        """

        :return:
        """
        print('Georeferencing ...')

        # tile_start = Tile.for_latitude_longitude(self.lat_start, self.lon_start, self.zoom)
        # tile_stop = Tile.for_latitude_longitude(self.lat_stop, self.lon_stop, self.zoom)

        Xs, Ys = self.tiles_in_dir()

        start_x, start_y = min(Xs), min(Ys)
        stop_x, stop_y = max(Xs), max(Ys)

        tile_start = Tile.from_google(start_x, start_y, self.zoom)
        tile_stop = Tile.from_google(stop_x, stop_y, self.zoom)

        point_start = Point.from_latitude_longitude(
            max(tile_start.bounds[0][0], tile_start.bounds[1][0]),
            min(tile_start.bounds[0][1], tile_start.bounds[1][1]))
        point_stop = Point.from_latitude_longitude(
            min(tile_stop.bounds[0][0], tile_stop.bounds[1][0]),
            max(tile_stop.bounds[0][1], tile_stop.bounds[1][1]))

        # print(point_start.meters, point_stop.meters)

        if 'bing' in self.map or 'google' in self.map:
            a_srs = 'EPSG:3857'
        else:
            a_srs = 'EPSG:4326'

        # Georeferencing
        os.system(
            "gdal_translate -of GTiff -co BIGTIFF=YES -co NUM_THREADS=8 -a_ullr "
            + str(point_start.meters[0]) + " " + str(point_start.meters[1]) +
            " " + str(point_stop.meters[0]) + " " + str(point_stop.meters[1]) +
            " " + "-a_srs " + a_srs + " " + self.map + "_" + self.mode +
            "_stitched.tif result.tif")
        # warping with conversion to RGBA
        # --config GDAL_CACHEMAX 32000 - wm 1500
        os.system(
            "gdalwarp -dstalpha -srcnodata 0 -dstnodata 0 -overwrite -wo NUM_THREADS=8 "
            + "-co COMPRESS=PACKBITS -co BIGTIFF=YES " + "-s_srs " + a_srs +
            " -t_srs EPSG:4326 result.tif  " + self.map + "_" + self.mode +
            "_gcps.tif")

        os.remove('result.tif')

        print('Georeferencing Complete!')
Ejemplo n.º 10
0
def test_cross_check(tms, google, quad_tree, zoom):
    tile = Tile.from_quad_tree(quad_tree=quad_tree)

    assert tile.tms == tms
    assert tile.zoom == zoom
    assert tile.google == google
    assert tile.quad_tree == quad_tree
Ejemplo n.º 11
0
def get_bbox_in_tms(bbox: Tuple[float, float, float, float], zoom: int) -> Tuple[int, int, int, int]:
    # language=rst
    """
    Returns tms coordinates of the tiles bbox
    :param bbox: area of the geo coordinates in the form of:
     `(min_lat, min_lon, max_lat, max_lon)`
    :param zoom:
    :return: bbox of tms tile coordinates in the form: `(min_x, min_y, max_x, max_y)`
    """
    tile1 = Tile.for_latitude_longitude(*bbox[:2], zoom)
    tile2 = Tile.for_latitude_longitude(*bbox[2:], zoom)

    min_x, max_x = sorted([tile1.tms_x, tile2.tms_x])
    min_y, max_y = sorted([tile1.tms_y, tile2.tms_y])

    return min_x, min_y, max_x, max_y
Ejemplo n.º 12
0
def test_pixel_bounds_chicago(chicago_quad_tree, chicago_pixel_bounds):
    tile = Tile.from_quad_tree(chicago_quad_tree)

    point_min, point_max = tile.bounds

    assert chicago_pixel_bounds[0] == point_min.pixels(zoom=tile.zoom)
    assert chicago_pixel_bounds[1] == point_max.pixels(zoom=tile.zoom)
Ejemplo n.º 13
0
def _tile_at(point, zoom):
    """Return the map tile located at the given point in Spherical
    Mercator coordinates with the specified zoom level.
    """
    point = PyGeoPoint.from_meters(point[0], point[1])
    tile = PyGeoTile.for_point(point, zoom)
    return tile.google
Ejemplo n.º 14
0
def _merge_tiles(path: Union[Path, str], tiles_dir: Union[Path, str],
                 tms_bbox: Tuple[int, int, int, int], zoom: int,
                 tiles_format: ImageFormat) -> None:
    # language=rst
    """
    Merge tiles from `tms_bbox` area from `tiles_dir` with `zoom` zoomlevel and `tiles_format` image format
    in image file with `path` without georeference
    :param path:
    :param tiles_dir:
    :param tms_bbox: area of the tms coordinates in the form of:
     `(min_x, min_y, max_x, max_y)`
    :param zoom:
    :param tiles_format:
    :return:
    """
    min_x, min_y, max_x, max_y = tms_bbox

    rows = list()
    for y in range(max_y, min_y - 1, -1):
        row = list()
        for x in range(min_x, max_x + 1):
            tile_path = get_filename(Tile.from_tms(x, y, zoom), tiles_format,
                                     tiles_dir)
            row.append(cv2.imread(str(tile_path)))

        row_img = cv2.hconcat(row)
        rows.append(row_img)
    data = cv2.vconcat(rows)

    cv2.imwrite(path, data)
Ejemplo n.º 15
0
def test_assert_google_y(google_y, zoom):
    google_x = 0

    with pytest.raises(AssertionError) as assertion_info:
        _ = Tile.from_google(google_x=google_x, google_y=google_y, zoom=zoom)

    assert 'Google Y needs to be a value between 0 and (2^zoom) -1.' in str(
        assertion_info.value)
Ejemplo n.º 16
0
def test_for_latitude_longitude(chicago_latitude_longitude, chicago_zoom,
                                chicago_tms):
    latitude, longitude = chicago_latitude_longitude
    tile = Tile.for_latitude_longitude(latitude=latitude,
                                       longitude=longitude,
                                       zoom=chicago_zoom)

    assert tile.tms == chicago_tms
Ejemplo n.º 17
0
def test_for_point(chicago_latitude_longitude, chicago_zoom, chicago_tms):
    latitude, longitude = chicago_latitude_longitude
    point = Point.from_latitude_longitude(latitude=latitude,
                                          longitude=longitude)
    tile = Tile.for_point(point=point, zoom=chicago_zoom)

    assert tile.tms == chicago_tms
    assert tile.zoom == chicago_zoom
Ejemplo n.º 18
0
def test_assert_tms_y(tms_y, zoom):
    tms_x = 0

    with pytest.raises(AssertionError) as assertion_info:
        _ = Tile.from_tms(tms_x=tms_x, tms_y=tms_y, zoom=zoom)

    assert 'TMS Y needs to be a value between 0 and (2^zoom) -1.' in str(
        assertion_info.value)
Ejemplo n.º 19
0
def test_georeference():
    tile = Tile.from_tms(139423, 171197, 18)
    img_path = os.path.join(os.getcwd(), "test", "data", "18_139423_171197.tif")
    m = MarchingSquares.from_file(img_path)
    points = m.find_contour()
    geo_points = georeference(points, tile)
    p = geometry.Polygon(geo_points)
    print(p.wkt)
    assert p.wkt == "POLYGON ((11.46890044212341 48.1641425687818, 11.46890580654145 48.1641425687818, 11.46890580654145 48.16404238298088, 11.46879851818085 48.16404238298088, 11.46879851818085 48.16413899072083, 11.46890044212341 48.16413899072083, 11.46890044212341 48.1641425687818))"
Ejemplo n.º 20
0
def _build_tile_url(
    url_format: UrlFormat, url_template: str, z: int, x: int, y: int
) -> str:
    if url_format == UrlFormat.QUADKEY:
        return url_template.format(
            q=Tile.from_google(google_x=x, google_y=y, zoom=z).quad_tree
        )
    if url_format == UrlFormat.XYZ:
        return url_template.format(z=z, x=x, y=y)
Ejemplo n.º 21
0
def qt_convert(lat, lng, zoom=19):
    '''
    lat, lng, zoom=18(default)
    '''
    from pygeotile.tile import Tile
    try:
        return Tile.for_latitude_longitude(lat, lng, zoom=zoom).quad_tree
    except:
        pass
Ejemplo n.º 22
0
def test_for_meters_chicago(chicago_pixel, chicago_zoom, chicago_tms):
    pixel_x, pixel_y = chicago_pixel
    point = Point.from_pixel(pixel_x=pixel_x,
                             pixel_y=pixel_y,
                             zoom=chicago_zoom)
    meter_x, meter_y = point.meters

    tile = Tile.for_meters(meter_x=meter_x, meter_y=meter_y, zoom=chicago_zoom)

    assert tile.tms == chicago_tms
Ejemplo n.º 23
0
def tile_cover(geometry, z):
    import geopandas as gpd
    from supermercado import burntiles, super_utils
    from pygeotile.tile import Tile
    geo = gpd.GeoSeries([geometry]).__geo_interface__['features'][0]
    geo = [f for f in super_utils.filter_polygons([geo])]
    return [
        Tile.from_google(*geo).quad_tree
        for geo in [f for f in burntiles.burn(geo, z)]
    ]
Ejemplo n.º 24
0
def tile_to_geo_boundary(key):

    a = Tile.from_quad_tree(key)
    return ("Polygon ((" + f"{a.bounds[0].longitude}" + " " +
            f"{a.bounds[0].latitude}" + "," + f"{a.bounds[0].longitude}" +
            " " + f"{a.bounds[1].latitude}" + "," +
            f"{a.bounds[1].longitude}" + " " + f"{a.bounds[1].latitude}" +
            "," + f"{a.bounds[1].longitude}" + " " +
            f"{a.bounds[0].latitude}" + "," + f"{a.bounds[0].longitude}" +
            " " + f"{a.bounds[0].latitude}" + "))")
Ejemplo n.º 25
0
    def test_string_output(self):
        """Test that tile details are correctly printed."""

        tile = Tile.from_google(3, 1, 2)

        self.assertEqual(format_tile(tile, 'google'), '3 1 2')
        self.assertEqual(format_tile(tile, 'tms'), '3 2 2')
        self.assertEqual(format_tile(tile, 'quad_tree'), '13')

        self.assertEqual(format_tile(tile, 'google', '{z}-{x}-{y}'), '2-3-1')
        self.assertEqual(format_tile(tile, 'tms', '{z}-{x}-{y}'), '2-3-2')
Ejemplo n.º 26
0
def cvtLatlon2xyz(z, *bounds_):
    logging.info('calculating xyz...')
    cross_lat = (bounds_[0] + bounds_[2]) / 2
    cross_lon = (bounds_[1] + bounds_[3]) / 2
    t = Tile.for_latitude_longitude(longitude=cross_lon,
                                    latitude=cross_lat,
                                    zoom=z)
    x, y = t.google
    google_xyz = [x, y, z]
    #print x, y
    return google_xyz
def png2GeoTif(src_filename, dst_filename, google_x, google_y, zoom, pixels,
               epsg):
    """
    This function make image georeference adn convert to .tif format to be able to load it in qgis

    :param src_filename: '/path/to/source.tif'

    :param dst_filename: '/path/to/destination.tif'

    :param google_x:

    :param google_y:

    :param zoom: 15

    :param pixels:

    :param epsg: 4326 #Es el eps de los puntos del IDEAM y el que retorna pygeotile

    :return:
    """
    # Opens source dataset
    src_ds = gdal.Open(src_filename)
    format = "GTiff"
    driver = gdal.GetDriverByName(format)
    # Open destination dataset
    dst_ds = driver.CreateCopy(dst_filename, src_ds, 0)
    #Optener los puntos de referencia
    tile = Tile.from_google(google_x, google_y, zoom)
    bounds = tile.bounds  #Retorna el punto sur occidental y el punto nororiental del tile.
    p1 = bounds[
        0]  #Point(latitude=2.6357885741666065, longitude=-72.388916015625)
    p2 = bounds[1]
    uperleftx = min([p1[1], p2[1]])
    uperlefty = max([p1[0], p2[0]])
    scalex = abs(p1[1] - p2[1]) / pixels
    scaley = abs(p1[0] - p2[0]) / pixels
    # Specify raster location through geotransform array
    # (uperleftx, scalex, skewx, uperlefty, skewy, scaley)
    # Scale = size of one pixel in units of raster projection
    # this example below assumes 100x100
    gt = [uperleftx, scalex, 0, uperlefty, 0, -scaley]
    #print(gt)
    # Set location
    dst_ds.SetGeoTransform(gt)
    # Get raster projection
    srs = osr.SpatialReference()
    srs.ImportFromEPSG(epsg)
    dest_wkt = srs.ExportToWkt()
    # Set projection
    dst_ds.SetProjection(dest_wkt)
    # Close files
    dst_ds = None
    src_ds = None
Ejemplo n.º 28
0
def chipTiles(p, z):
    """
    find Planet Tile for a give point p at given zool level z
    :param p: (lat, long)
    :param z: 15
    :return: x,y,z tile google xyz tile grid
    """
    latitude, longitude, zoom = p[0], p[1], z
    tile = Tile.for_latitude_longitude(latitude, longitude, zoom)
    tile = tile.google
    return tile
Ejemplo n.º 29
0
def geoTiles_conveter(position):
    """
        converter geo coordenadas para quadTrees

    """
    lat, lon = position
 

    tile = Tile.for_latitude_longitude(latitude=lat, longitude=lon, zoom=18)

    return tile.quad_tree
Ejemplo n.º 30
0
def getTMSBBox(x, y, zoom):
    tile = Tile.from_tms(tms_x=x, tms_y=y, zoom=zoom)
    bounds = tile.bounds
    minLong = bounds[0].longitude
    minLat = bounds[0].latitude
    maxLong = bounds[1].longitude
    maxLat = bounds[1].latitude

    minLong, minLat = pointTo3857(minLong, minLat)
    maxLong, maxLat = pointTo3857(maxLong, maxLat)

    return np.array([minLong, maxLong, minLat, maxLat])
Ejemplo n.º 31
0
def open_tile(filename, outdir='./'):
    """ Open a tile image and assign projection and geotransform """
    img = gippy.GeoImage(filename)
    z, x, y = map(int, img.basename().split('-'))
    tile = Tile.from_tms(tms_x=x, tms_y=y, zoom=z)
    img[0] = (img[0] == 255)
    fout = os.path.join(outdir, img.basename() + '.tif')
    geoimg = img.save(fout, options={'COMPRESS': 'DEFLATE'})
    geoimg.set_srs('EPSG:3857')
    minpt = tile.bounds[0].meters
    maxpt = tile.bounds[1].meters
    affine = np.array(
        [
            minpt[0], (maxpt[0]-minpt[0])/geoimg.xsize(), 0.0,
            abs(minpt[1]), 0.0, -(maxpt[1]-minpt[1])/geoimg.ysize()
        ])
    geoimg.set_affine(affine)
    return geoimg