コード例 #1
0
def mask(geotiff, geojson, clean=False, filled=False, **kwargs):
    """Mask geotiff with geojson features.

    Arguments:
        geotiff: A GeoTiff
        geojson: Path to a GeoJSON Feature or Feature Collection
        clean: bool: To delete input file after processing
        filled: bool: To fill masked areas with nodata value, or if not,
            to return a masked image.
        **kwargs: Further options to pass to rasterio.mask.mask(), e.g.:
            nodata: Override nodata value. Defaults to value for geotiff, or 0.
            invert: bool: To mask the areas _inside_ the vector shapes.
    
    Returns: Path to the masked geotiff.
    """
    with rasterio.open(geotiff) as dataset:
        profile = dataset.profile.copy()
        epsg_code = profile['crs']['init'].split('epsg:')[-1]
        geoms = geojsonio.load_geometries(geojson)
        geoms = [projections.project_geojson_geom(g, epsg_code) for g in geoms]
        masked, _ = rasterio.mask.mask(dataset, geoms, filled=filled, **kwargs)

    outpath = geotiff.split('.tif')[0] + '-masked.tif'
    with rasterio.open(outpath, 'w', **profile) as of:
        of.write(masked)
        if not filled:
            gdalmask = (~masked.mask)[0]
            of.write_mask(gdalmask)
    if clean:
        os.remove(geotiff)
    return outpath
コード例 #2
0
def resolve(vrtfile, **kwargs):
    """Convert vrtfile to tif while resolving bands and geographic bounds.

    Arguments:
        vrtfile: A file output by gdalbuildvrt
        kwargs (optional):
            bandlist: Ordered list of output bands
            geojson: A geojson feature or feature collection expressing
                a crop region

    Outputs a geotiff; returns the filename.
    """
    tiffile = vrtfile.split('.vrt')[0] + '.tif'
    commands = ['gdal_translate', vrtfile, tiffile, '-co', 'COMPRESS=LZW']

    bandlist = kwargs.get('bandlist')
    if bandlist:
        dressed_bands = np.asarray([('-b', str(b)) for b in bandlist])
        commands += [*dressed_bands.flatten()]
        if len(bandlist) == 3:
            commands += ['-colorinterp', 'red,green,blue']

    geojson = kwargs.get('geojson')
    if geojson:
        bbox = geobox.bbox_from_geometries(geojsonio.load_geometries(geojson))
        gdal_bounds = [str(bbox.bounds[n]) for n in (0, 3, 2, 1)]
        commands += ['-projwin_srs', 'EPSG:4326', '-projwin', *gdal_bounds]

    subprocess.call(commands)
    os.remove(vrtfile)
    return tiffile
コード例 #3
0
def crop(geotiff, geojson, outpath):
    """Crop geotiff to bounding box of geojson and save to outpath."""

    bbox = geobox.bbox_from_geometries(geojsonio.load_geometries(geojson))
    gdal_bounds = [str(bbox.bounds[n]) for n in (0, 3, 2, 1)]

    commands = [
        'gdal_translate', geotiff, outpath, '-projwin_srs', 'EPSG:4326',
        '-projwin', *gdal_bounds
    ]
    subprocess.call(commands)
    return outpath
コード例 #4
0
def burn(geojson, geotiff):
    """Burn features in geojson into a container defined by existing geotiff."""
    with rasterio.open(geotiff) as f:
        profile = f.profile.copy()

    epsg_code = profile['crs']['init'].split('epsg:')[-1]
    shape = (profile['height'], profile['width'])
    pixel_max = pixel_limits.get_max(profile['dtype'])
    geoms = geojsonio.load_geometries(geojson)
    geoms = [projections.project_geojson_geom(g, epsg_code) for g in geoms]

    raster = rasterio.features.rasterize(((geom, pixel_max) for geom in geoms),
                                         out_shape=shape,
                                         transform=profile['transform'])
    
    raster = raster.reshape((1,) + shape)
    profile.update({'count': 1})
    rasterfile = '.'.join(geojson.split('.')[:-1]) + '-burned.tif'
    with rasterio.open(rasterfile, 'w', **profile) as f:
        f.write(raster)

    return rasterfile
コード例 #5
0
        '--indices',
        type=str,
        nargs='+',
        choices=INDICES,
        default=INDICES,
        help='Indices to compute, from {}. Defaults to all.'.format(INDICES))
    parser.add_argument(
        '-g',
        '--geojson',
        type=str,
        help='Geojson file expressing area of interest for optional crop.')
    parser.add_argument(
        '-d',
        '--image_dir',
        type=str,
        default='',
        help='Directory containing image band files. Defaults to pwd.')
    args = parser.parse_args()

    geoms = geojsonio.load_geometries(args.geojson) if args.geojson else []
    bounds = geobox.bbox_from_geometries(geoms).bounds if geoms else []

    base = os.path.join(args.image_dir, '*band?')
    paths = [glob.glob(base + ext) for ext in ['.tif', '.TIF']]
    paths = [p for sublist in paths for p in sublist]

    grouped = reduce_landsat.partition(paths, args.bandlist)
    for prefix, grouped_paths in grouped.items():
        for index in args.indices:
            build_index(prefix, grouped_paths, bounds, index)