Tests for warping functionalityΒΆ

[1]:
%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'))
  • Pull a raster for the examples

[2]:
! 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
  • Test warp_img_transform

[3]:
src = rasterio.open('warp_tst.tif')
img = src.read()
#rioshow(img, transform=src.transform);
[4]:
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)
[4]:
<matplotlib.axes._subplots.AxesSubplot at 0x7f813f917128>
_images/warping_guide_6_1.png
  • Test warp_tiles

[5]:
# 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()
_images/warping_guide_8_0.png
[6]:
# 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()
_images/warping_guide_9_0.png
  • Test warp_tiles within add_basemap

[7]:
ax = db.plot(color='red', alpha=0.5)
ctx.add_basemap(ax, crs=db.crs)
[7]:
<matplotlib.axes._subplots.AxesSubplot at 0x7f813f8ce4e0>
_images/warping_guide_11_1.png
  • Test warping within add_basemap and local file

[8]:
db_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)
[8]:
<matplotlib.axes._subplots.AxesSubplot at 0x7f813f8f1358>
_images/warping_guide_13_1.png