@AAmes It looks to me that your code is based on out of date examples or docs. Specifically, the rasterio module no longer exports a drivers()
function. Please see http://mapbox.github.io/rasterio/quickstart.html for Rasterio 1.0 usage examples.
I'm sorry about the difficulty of integrating Rasterio with QGIS. I haven't tried it myself, but being familiar with the problems of distributing Python C extensions, I'm surprised that you got it to work at all. Normally, Rasterio is installed using pip. I'm not sure what would be required to install it for QGIS's embedded Python.
It's a bit of a pain, but you need to write the resampled numpy array to a rasterio Dataset
(either on file or in memory) and adjust the transform to match the resampling..
Here's an example of both:
# Example licensed under cc by-sa 4.0 with attribution required
from contextlib import contextmanager
import rasterio
from rasterio import Affine, MemoryFile
from rasterio.enums import Resampling
@contextmanager
def resample_raster(raster, out_path=None, scale=2):
""" Resample a raster
multiply the pixel size by the scale factor
divide the dimensions by the scale factor
i.e
given a pixel size of 250m, dimensions of (1024, 1024) and a scale of 2,
the resampled raster would have an output pixel size of 500m and dimensions of (512, 512)
given a pixel size of 250m, dimensions of (1024, 1024) and a scale of 0.5,
the resampled raster would have an output pixel size of 125m and dimensions of (2048, 2048)
returns a DatasetReader instance from either a filesystem raster or MemoryFile (if out_path is None)
"""
t = raster.transform
# rescale the metadata
transform = Affine(t.a * scale, t.b, t.c, t.d, t.e * scale, t.f)
height = int(raster.height / scale)
width = int(raster.width / scale)
profile = src.profile
profile.update(transform=transform, driver='GTiff', height=height, width=width)
data = raster.read(
out_shape=(raster.count, height, width),
resampling=Resampling.bilinear,
)
if out_path is None:
with write_mem_raster(data, **profile) as dataset:
del data
yield dataset
else:
with write_raster(out_path, data, **profile) as dataset:
del data
yield dataset
@contextmanager
def write_mem_raster(data, **profile):
with MemoryFile() as memfile:
with memfile.open(**profile) as dataset: # Open as DatasetWriter
dataset.write(data)
with memfile.open() as dataset: # Reopen as DatasetReader
yield dataset # Note yield not return
@contextmanager
def write_raster(path, data, **profile):
with rasterio.open(path, 'w', **profile) as dataset: # Open as DatasetWriter
dataset.write(data)
with rasterio.open(path) as dataset: # Reopen as DatasetReader
yield dataset
Best Answer
The
mask
module was moved, after0.36
if I remember correctly, so you should instead import with: