@@ -0,0 +1,2682 @@
+# Copyright 2019 Luke Pinner%0A# %0A# Licensed under the Apache License, Version 2.0 (the %22License%22);%0A# you may not use this file except in compliance with the License.%0A# You may obtain a copy of the License at%0A# %0A#     http://www.apache.org/licenses/LICENSE-2.0%0A# %0A# Unless required by applicable law or agreed to in writing, software%0A# distributed under the License is distributed on an %22AS IS%22 BASIS,%0A# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.%0A# See the License for the specific language governing permissions and%0A# limitations under the License.%0A%0Afrom contextlib import contextmanager%0A%0Aimport rasterio%0Afrom rasterio import Affine, MemoryFile%0Afrom rasterio.enums import Resampling%0A%0A%0A@contextmanager%0Adef resample_raster(raster, out_path=None, scale=2):%0A    %22%22%22 Resample a raster%0A%0A        multiply the pixel size by the scale factor%0A        divide the dimensions by the scale factor%0A%0A        i.e%0A        given a pixel size of 250m, dimensions of (1024, 1024) and a scale of 2,%0A        the resampled raster would have an output pixel size of 500m and dimensions of (512, 512)%0A%0A        given a pixel size of 250m, dimensions of (1024, 1024) and a scale of 0.5,%0A        the resampled raster would have an output pixel size of 125m and dimensions of (2048, 2048)%0A%0A        returns a DatasetReader instance from either a filesystem raster or MemoryFile (if out_path is None)%0A    %22%22%22%0A    t = raster.transform%0A%0A    # rescale the metadata%0A    transform = Affine(t.a * scale, t.b, t.c, t.d, t.e * scale, t.f)%0A    height = int(raster.height / scale)%0A    width = int(raster.width / scale)%0A%0A    profile = src.profile%0A    profile.update(transform=transform, driver='GTiff', height=height, width=width)%0A%0A    data = raster.read(%0A            out_shape=(raster.count, height, width),%0A            resampling=Resampling.bilinear,%0A        )%0A%0A    if out_path is None:%0A        with write_mem_raster(data, **profile) as dataset:%0A            del data%0A            yield dataset%0A%0A    else:%0A        with write_raster(out_path, data, **profile) as dataset:%0A            del data%0A            yield dataset%0A%0A%0A@contextmanager%0Adef write_mem_raster(data, **profile):%0A    with MemoryFile() as memfile:%0A        with memfile.open(**profile) as dataset:  # Open as DatasetWriter%0A            dataset.write(data)%0A%0A        with memfile.open() as dataset:  # Reopen as DatasetReader%0A            yield dataset  # Note yield not return%0A%0A%0A@contextmanager%0Adef write_raster(path, data, **profile):%0A%0A    with rasterio.open(path, 'w', **profile) as dataset:  # Open as DatasetWriter%0A        dataset.write(data)%0A%0A    with rasterio.open(path) as dataset:  # Reopen as DatasetReader%0A        yield dataset%0A%0A

Create resample_raster.py