Skip to content

Instantly share code, notes, and snippets.

@whlteXbread
Created January 2, 2018 16:29
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save whlteXbread/533aa1560ee0bec38aac5a5993512d0a to your computer and use it in GitHub Desktop.
Save whlteXbread/533aa1560ee0bec38aac5a5993512d0a to your computer and use it in GitHub Desktop.
Demonstrate `rasterio` windowing bug
import rasterio
from rasterio.mask import mask
import fiona
import numpy as np
test_filename = 'test_rasterio_mask.tif'
test_image = 128 * np.ones((1, 1000, 2000), dtype=np.uint8)
test_transform = rasterio.Affine(-0.05, 0.07, 15000,
0.07, 0.05, 3500000)
test_crs = {'init': 'epsg:32614'}
out_meta = {'driver': 'GTiff',
'height': test_image.shape[1],
'width': test_image.shape[2],
'transform': test_transform,
'crs': test_crs,
'count': 1,
'dtype': np.uint8,
'compress': 'lzw'}
with rasterio.open(test_filename, 'w', **out_meta) as dest:
dest.write(test_image)
test_shape = [{'geometry': {'coordinates': [[(15010, 3500110),
(14980, 3500130),
(14975, 3500100),
(15000, 3500095),
(15010, 3500110)]],
'type': 'Polygon'},
'id': '0',
'type': 'Feature'}]
# write the shape out
test_schema = {'geometry': 'Polygon', 'properties': {'id': 'int'}}
test_shapefile_name = 'test_rasterio_mask.shp'
with fiona.open(test_shapefile_name, 'w',
'ESRI Shapefile', test_schema,
crs=test_crs) as out_shape:
out_shape.write({'geometry': test_shape[0]['geometry'],
'properties': {'id': 3}})
with rasterio.open(test_filename) as src:
out_image, out_transform = mask(src, [test_shape[0]['geometry']], crop=True)
out_meta = src.meta.copy()
out_image[out_image > 0] += 100
out_meta.update({'height': out_image.shape[1],
'width': out_image.shape[2],
'transform': out_transform})
crop_filename = 'test_rasterio_cropped.tif'
with rasterio.open(crop_filename, 'w', **out_meta) as dest:
dest.write(out_image)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment