How to use the rasterio.drivers function in rasterio

To help you get started, we’ve selected a few rasterio examples, based on popular ways it is used in public projects.

Secure your code as it's written. Use Snyk Code to scan source code in minutes - no build needed - and fix issues immediately.

github mapbox / rasterio / tests / test_features_shapes.py View on Github external
def test_shapes_dtype():
    """Test image data type handling"""

    rows = cols = 10
    with rasterio.drivers():
        supported_types = (
            ('int16', -32768),
            ('int32', -2147483648),
            ('uint8', 255),
            ('uint16', 65535),
            ('float32', 1.434532)
        )

        for dtype, test_value in supported_types:
            image = numpy.zeros((rows, cols), dtype=dtype)
            image[2:5, 2:5] = test_value

            shapes = ftrz.shapes(image)
            shape, value = next(shapes)
            if dtype == 'float32':
                assert round(value, 6) == round(test_value, 6)
github mapbox / rasterio / tests / test_features_sieve.py View on Github external
def test_sieve():
    """Test sieving a 10x10 feature from an ndarray."""

    image = numpy.zeros((20, 20), dtype=rasterio.ubyte)
    image[5:15, 5:15] = 1

    # An attempt to sieve out features smaller than 100 should not change the
    # image.
    with rasterio.drivers():
        sieved_image = ftrz.sieve(image, 100)
        assert numpy.array_equal(sieved_image, image)

    # Setting the size to 100 should leave us an empty, False image.
    with rasterio.drivers():
        sieved_image = ftrz.sieve(image, 101)
        assert not sieved_image.any()

    # Invalid size value should fail
    for invalid_size in (0, 45.1234, image.size + 1):
        with pytest.raises(ValueError):
            sieved_image = ftrz.sieve(image, invalid_size)
github sat-utils / sat-process / satio / utils.py View on Github external
""" returns a clipped TIF image """

    if os.path.isdir(dst_path):
        src_segments = os.path.split(src_path)
        src_filename = os.path.splitext(src_segments[1])

        dst_path = os.path.join(dst_path, src_filename[0] + '.tif')
    else:
        dst_segments = os.path.split(dst_path)
        dst_filename = os.path.splitext(dst_segments[1])
        dst_path = os.path.join(dst_segments[0], dst_filename[0] + '.tif')

    if not isinstance(bounds, list):
        raise Exception('Bounds must be a python list')

    with rasterio.drivers():
        with rasterio.open(src_path, 'r') as src:

            if not crs:
                crs = src.crs
            bounds = transform_bounds(
                crs,
                src.crs,
                *bounds
            )

            if disjoint_bounds(bounds, src.bounds):
                bounds = adjust_bounding_box(src.bounds, bounds)

            window = src.window(*bounds)

            out_kwargs = src.meta.copy()
github mapbox / satellite-change-detect / tiledelta / scripts / cli.py View on Github external
def comptiles(filedir, comparedir, sampling, filetype):

    # plotdir = '/Users/dnomadb/Documents/pcomp'

    files = os.listdir(filedir)
    cfiles = os.listdir(comparedir)

    if plotdir:
        import matplotlib.pyplot as plot

    for f in files:
        fileinfo = f.split('-')
        if len(fileinfo[-1].split('.')) != 0 and fileinfo[-1].split('.')[-1] == filetype:
            x, y, z = tiledelta.getXYZ(fileinfo)
            bbox = mercantile.bounds(x, y, z)
            with rio.drivers():
                with rio.open(os.path.join(filedir, f), 'r') as src:
                    greyimage_before = (src.read(1).astype(np.uint16) + src.read(2).astype(np.uint16) + src.read(3).astype(np.uint16))
                with rio.open(os.path.join(comparedir, f), 'r') as src:
                    greyimage_after = (src.read(1).astype(np.uint16) + src.read(2).astype(np.uint16) + src.read(3).astype(np.uint16))
                
                pcplo = tiledelta.compareGreys(greyimage_after, greyimage_before, 10, 20)
                pcplo = pcplo[::sampling,::sampling]
                
                if plotdir:
                    fig = plot.figure(figsize=(20,10))
                    before = fig.add_subplot(131)
                    before.imshow(greyimage_after,cmap='Greys_r')
                    after = fig.add_subplot(132)
                    after.imshow(greyimage_before, cmap='Greys_r')
                    pc2 = fig.add_subplot(133)
                    pc2.imshow(pcplo, cmap='YlGnBu')
github mapbox / grib-doctor / gribdoctor / scripts / cut_splice_globewrap.py View on Github external
def upwrap_raster(inputRaster, outputRaster, bidx, bandtags):
    import rasterio

    with rasterio.drivers():
        with rasterio.open(inputRaster, 'r') as src:
            if bidx == 'all':
                bandNos = np.arange(src.count) + 1
            else:
                bandNos = list(int(i.replace(' ', '')) for i in bidx.split(','))

            fixedArrays = list(gribdoctor.handleArrays(src.read_band(i)) for i in bandNos)

            fixAff = gribdoctor.updateBoundsAffine(src.affine)
            if bandtags:
                tags = list(src.tags(i + 1) for i in range(src.count))
                click.echo(json.dumps(tags, indent=2))

        with rasterio.open(outputRaster, 'w',
            driver='GTiff',
            count=len(bandNos),
github developmentseed / landsat-util / landsat / ndvi.py View on Github external
def write_band(self, output_band, output_file, image_data):
        # colormaps will overwrite our transparency masks so we will manually
        # create three RGB bands

        self.output("Applying ColorMap", normal=True, arrow=True)
        self.cmap[0] = (0, 0, 0, 255)

        v_manual_colormap = numpy.vectorize(self.manual_colormap, otypes=[numpy.uint8])
        rgb_bands = []
        for i in range(3):
            rgb_bands.append(v_manual_colormap(output_band, i))

        with rasterio.drivers(GDAL_TIFF_INTERNAL_MASK=True):
            with rasterio.open(output_file, 'w', driver='GTiff',
                               width=image_data['shape'][1],
                               height=image_data['shape'][0],
                               count=3,
                               dtype=numpy.uint8,
                               nodata=0,
                               photometric='RGB',
                               transform=image_data['dst_transform'],
                               crs=self.dst_crs) as output:

                for i in range(3):
                    output.write_band(i + 1, rgb_bands[i])

            self.output("Writing to file", normal=True, color='green', indent=1)
        return output_file
github mapbox / make-surface / makesurface / scripts / fill_facets.py View on Github external
def loadRaster(filePath, bands, bounds):
    """

    """
    with rasterio.drivers():
        with rasterio.open(filePath,'r') as src:
            oaff = src.affine
            upperLeft = src.index(bounds.left, bounds.top)
            lowerRight = src.index(bounds.right, bounds.bottom)
            filler = np.zeros((lowerRight[0] - upperLeft[0], lowerRight[1] - upperLeft[1])) - 999
            return np.dstack(list(
                src.read(i[1], boundless=True, out=filler, window=((upperLeft[0], lowerRight[0]),(upperLeft[1], lowerRight[1]))
                    ) for i in bands
                )), oaff
github erdc / quest / quest_filter_plugins / extract_elevations.py View on Github external
logger.error('no tiles found')

                return

            tiles = api.get_data(service, locs)
            tiles = [v['elevation'] for v in list(tiles.values())]

            if len(tiles)>1:
                raster_file = os.path.splitext(tiles[0])[0] + '.vrt'
                logger.info(subprocess.check_output(['gdalbuildvrt', '-overwrite', raster_file] + tiles))

            else:
                raster_file = tiles[0]

            logger.info('extracting elevations along feature')
            with rasterio.drivers():
                with rasterio.open(raster_file, 'r') as raster:
                    masks = []
                    if os.path.isfile(filename):
                        os.remove(filename) #fiona can't write to an existing file
                    with fiona.open(filename,'w',driver=vector.driver, crs=vector.crs, schema=vector.schema) as output:
                        for feature in vector:
                            points = feature['geometry']['coordinates']
                            masks.append((feature['geometry'], 0))
                            if method=='nearest':
                                elevations = list(raster.sample(points))
                                coordinates = [xy + tuple(z.tolist()) for xy, z in zip(points, elevations)]
                            elif method=='bilinear':
                                coordinates = []
                                for x,y in points:
                                    a, b, c, d, e, f, _, _, _ = raster.affine
                                    yf, r = math.modf(old_div((y-f),e))
github mapbox / rasterio / rasterio / rio / rio_warp.py View on Github external
verbosity = args.v - args.q
    logging.basicConfig(stream=sys.stderr, level=(30 - 10*verbosity))
    logger = logging.getLogger('rasterio')

    # TODO: quick check of filenames before we call main().

    # TODO: support other formats.
    options['driver'] = 'GTiff'

    source = args.source
    destination = args.destination
    dest_crs = args.destination_crs
    template=args.template_file
    log=logger

    with rasterio.drivers():

        try:

            with rasterio.open(source) as src:

                # First, copy the opts to the destination's kwargs.
                kwargs = src.meta.copy()
                kwargs.update(opts)

                # If there's a template file, overlay its georeferencing.
                if template is not None:
                    with rasterio.open(template) as tmpl:
                        kwargs['transform'] = tmpl.transform
                        kwargs['crs'] = tmpl.crs

                # Determine the output extent.
github mapbox / rasterio / rasterio / rio / rio.py View on Github external
[xs[1], ys[1]],
                            [xs[0], ys[1]],
                            [xs[0], ys[0]] ]]},
                    'properties': {
                        'id': str(i),
                        'title': path,
                        'filename': os.path.basename(path)} }

                self._xs.extend(bbox[::2])
                self._ys.extend(bbox[1::2])

    col = Collection()
    # Use the generator defined above as input to the generic output
    # writing function.
    try:
        with rasterio.drivers(CPL_DEBUG=verbosity>2):
            write_features(
                stdout, col, sequence=sequence,
                geojson_type=geojson_type, use_rs=use_rs,
                **dump_kwds)

    except Exception:
        logger.exception("Exception caught during processing")
        raise click.Abort()