%matplotlib inline
from importlib import reload
import geopandas as gpd
import rasterio
from rasterio.plot import show as rioshow
import matplotlib.pyplot as plt
import contextily as ctx
from contextily.tile import warp_img_transform, warp_tiles, _warper
db = gpd.read_file(gpd.datasets.get_path('nybb'))
! rm warp_tst.tif
db_wm = db.to_crs(epsg=3857)
w, s, e, n = db_wm.total_bounds
img, ext = ctx.bounds2raster(w, s, e, n,
'warp_tst.tif',
zoom=10)
! du -hs warp_tst.tif
0 warp_tst.tif
warp_img_transform
src = rasterio.open('warp_tst.tif')
img = src.read()
#rioshow(img, transform=src.transform);
w_img, w_transform = warp_img_transform(img,
src.transform,
src.crs, db.crs)
f, ax = plt.subplots(1)
rioshow(w_img,
transform=w_transform, ax=ax);
db.plot(color='r', alpha=0.5, ax=ax)
<matplotlib.axes._subplots.AxesSubplot at 0x7f813f917128>
warp_tiles
# All in Web Mercator
db_wm = db.to_crs(epsg=3857)
w, s, e, n = db_wm.total_bounds
img, ext = ctx.bounds2img(w, s, e, n, zoom=10)
f, ax = plt.subplots(1, figsize=(3, 3))
ax.imshow(img, extent=ext)
db_wm.plot(ax=ax, color='r', alpha=0.5)
plt.show()
# Warp to original CRS
wimg, wext = ctx.tile.warp_tiles(img, ext, db.crs)
f, ax = plt.subplots(1, figsize=(9, 9))
ax.imshow(wimg, extent=wext)
db.plot(ax=ax, color='r', alpha=0.5)
plt.show()
warp_tiles
within add_basemap
ax = db.plot(color='red', alpha=0.5)
ctx.add_basemap(ax, crs=db.crs)
<matplotlib.axes._subplots.AxesSubplot at 0x7f813f8ce4e0>
add_basemap
and local filedb_wm = db.to_crs(epsg=4326)
ax = db_wm.plot(color='red', alpha=0.5)
ctx.add_basemap(ax, crs={'init': 'epsg:4326'},
url='warp_tst.tif',
attribution=None)
<matplotlib.axes._subplots.AxesSubplot at 0x7f813f8f1358>