Ejemplo n.º 1
0
def test_nodata(basic_image_file, basic_geometry):
    nodata_val = 0
    geometries = [basic_geometry]
    with rasterio.open(basic_image_file, "r") as src:
        masked, transform = mask_tool(src, geometries, crop=False,
                                      nodata=nodata_val, invert=True)
    assert(masked.data.all() == nodata_val)
Ejemplo n.º 2
0
def test_crop_all_touched(basic_image, basic_image_file, basic_geometry):
    geometries = [basic_geometry]
    with rasterio.open(basic_image_file, "r") as src:
        masked, transform = mask_tool(src, geometries, crop=True,
                                      all_touched=True)

    assert(masked.shape == (1, 4, 3))
    assert((masked[0] == basic_image[1:5, 2:5]).all())
Ejemplo n.º 3
0
def test_crop_and_invert(basic_image_file, basic_geometry):
    geometries = [basic_geometry]
    with rasterio.open(basic_image_file) as src:
        with pytest.raises(ValueError):
            masked, transform = mask_tool(src,
                                          geometries,
                                          crop=True,
                                          invert=True)
Ejemplo n.º 4
0
def test_crop(basic_image, basic_image_file, basic_geometry):
    geometries = [basic_geometry]
    with rasterio.open(basic_image_file, "r") as src:
        masked, transform = mask_tool(src, geometries, crop=True)

    image = basic_image
    image[4, :] = 0
    image[:, 4] = 0
    assert(masked.shape == (1, 4, 3))
    assert((masked[0] == image[1:5, 2:5]).all())
Ejemplo n.º 5
0
def test_nodata(basic_image_file, basic_geometry):
    nodata_val = 0
    geometries = [basic_geometry]
    with rasterio.open(basic_image_file, "r") as src:
        masked, transform = mask_tool(src,
                                      geometries,
                                      crop=False,
                                      nodata=nodata_val,
                                      invert=True)
    assert (masked.data.all() == nodata_val)
Ejemplo n.º 6
0
def test_crop_all_touched(basic_image, basic_image_file, basic_geometry):
    geometries = [basic_geometry]
    with rasterio.open(basic_image_file, "r") as src:
        masked, transform = mask_tool(src,
                                      geometries,
                                      crop=True,
                                      all_touched=True)

    assert (masked.shape == (1, 4, 3))
    assert ((masked[0] == basic_image[1:5, 2:5]).all())
Ejemplo n.º 7
0
def test_crop(basic_image, basic_image_file, basic_geometry):
    geometries = [basic_geometry]
    with rasterio.open(basic_image_file, "r") as src:
        masked, transform = mask_tool(src, geometries, crop=True)

    image = basic_image
    image[4, :] = 0
    image[:, 4] = 0
    assert (masked.shape == (1, 4, 3))
    assert ((masked[0] == image[1:5, 2:5]).all())
Ejemplo n.º 8
0
def test_crop_and_invert(basic_image_file, basic_geometry):
    geometries = [basic_geometry]
    with rasterio.open(basic_image_file) as src:
        with pytest.raises(ValueError):
            masked, transform = mask_tool(src, geometries,
                                          crop=True, invert=True)
Ejemplo n.º 9
0
def mask(
        ctx,
        files,
        output,
        geojson_mask,
        driver,
        all_touched,
        crop,
        invert,
        force_overwrite,
        creation_options):

    """Masks in raster using GeoJSON features (masks out all areas not covered
    by features), and optionally crops the output raster to the extent of the
    features.  Features are assumed to be in the same coordinate reference
    system as the input raster.

    GeoJSON must be the first input file or provided from stdin:

    > rio mask input.tif output.tif --geojson-mask features.json

    > rio mask input.tif output.tif --geojson-mask - < features.json

    If the output raster exists, it will be completely overwritten with the
    results of this operation.

    The result is always equal to or within the bounds of the input raster.

    --crop and --invert options are mutually exclusive.

    --crop option is not valid if features are completely outside extent of
    input raster.
    """

    from rasterio.tools.mask import mask as mask_tool
    from rasterio.features import bounds as calculate_bounds

    verbosity = (ctx.obj and ctx.obj.get('verbosity')) or 1
    logger = logging.getLogger('rio')

    output, files = resolve_inout(
        files=files, output=output, force_overwrite=force_overwrite)
    input = files[0]

    if geojson_mask is None:
        click.echo('No GeoJSON provided, INPUT will be copied to OUTPUT',
                   err=True)
        shutil.copy(input, output)
        return

    if crop and invert:
        click.echo('Invert option ignored when using --crop', err=True)
        invert = False

    with rasterio.drivers(CPL_DEBUG=verbosity > 2):
        try:
            with click.open_file(geojson_mask) as f:
                geojson = json.loads(f.read())
        except ValueError:
            raise click.BadParameter('GeoJSON could not be read from '
                                     '--geojson-mask or stdin',
                                     param_hint='--geojson-mask')

        if 'features' in geojson:
            geometries = [f['geometry'] for f in geojson['features']]
        elif 'geometry' in geojson:
            geometries = (geojson['geometry'], )
        else:
            raise click.BadParameter('Invalid GeoJSON', param=input,
                                     param_hint='input')
        bounds = geojson.get('bbox', calculate_bounds(geojson))

        with rasterio.open(input) as src:
            try:
                out_image, out_transform = mask_tool(src, geometries,
                                                     crop=crop, invert=invert,
                                                     all_touched=all_touched)
            except ValueError as e:
                if e.args[0] == 'Input shapes do not overlap raster.':
                    if crop:
                        raise click.BadParameter('not allowed for GeoJSON '
                                                 'outside the extent of the '
                                                 'input raster',                                                                 param=crop,
                                                 param_hint='--crop')

            meta = src.meta.copy()
            meta.update(**creation_options)
            meta.update({
                'driver': driver,
                'height': out_image.shape[1],
                'width': out_image.shape[2],
                'transform': out_transform
            })

            with rasterio.open(output, 'w', **meta) as out:
                out.write(out_image)
Ejemplo n.º 10
0
def mask(ctx, files, output, geojson_mask, driver, all_touched, crop, invert,
         force_overwrite, creation_options):
    """Masks in raster using GeoJSON features (masks out all areas not covered
    by features), and optionally crops the output raster to the extent of the
    features.  Features are assumed to be in the same coordinate reference
    system as the input raster.

    GeoJSON must be the first input file or provided from stdin:

    > rio mask input.tif output.tif --geojson-mask features.json

    > rio mask input.tif output.tif --geojson-mask - < features.json

    If the output raster exists, it will be completely overwritten with the
    results of this operation.

    The result is always equal to or within the bounds of the input raster.

    --crop and --invert options are mutually exclusive.

    --crop option is not valid if features are completely outside extent of
    input raster.
    """

    from rasterio.tools.mask import mask as mask_tool
    from rasterio.features import bounds as calculate_bounds

    verbosity = (ctx.obj and ctx.obj.get('verbosity')) or 1
    logger = logging.getLogger('rio')

    output, files = resolve_inout(files=files,
                                  output=output,
                                  force_overwrite=force_overwrite)
    input = files[0]

    if geojson_mask is None:
        click.echo('No GeoJSON provided, INPUT will be copied to OUTPUT',
                   err=True)
        shutil.copy(input, output)
        return

    if crop and invert:
        click.echo('Invert option ignored when using --crop', err=True)
        invert = False

    with rasterio.drivers(CPL_DEBUG=verbosity > 2):
        try:
            with click.open_file(geojson_mask) as f:
                geojson = json.loads(f.read())
        except ValueError:
            raise click.BadParameter(
                'GeoJSON could not be read from '
                '--geojson-mask or stdin',
                param_hint='--geojson-mask')

        if 'features' in geojson:
            geometries = [f['geometry'] for f in geojson['features']]
        elif 'geometry' in geojson:
            geometries = (geojson['geometry'], )
        else:
            raise click.BadParameter('Invalid GeoJSON',
                                     param=input,
                                     param_hint='input')
        bounds = geojson.get('bbox', calculate_bounds(geojson))

        with rasterio.open(input) as src:
            try:
                out_image, out_transform = mask_tool(src,
                                                     geometries,
                                                     crop=crop,
                                                     invert=invert,
                                                     all_touched=all_touched)
            except ValueError as e:
                if e.args[0] == 'Input shapes do not overlap raster.':
                    if crop:
                        raise click.BadParameter(
                            'not allowed for GeoJSON '
                            'outside the extent of the '
                            'input raster',
                            param=crop,
                            param_hint='--crop')

            meta = src.meta.copy()
            meta.update(**creation_options)
            meta.update({
                'driver': driver,
                'height': out_image.shape[1],
                'width': out_image.shape[2],
                'transform': out_transform
            })

            with rasterio.open(output, 'w', **meta) as out:
                out.write(out_image)