Exemplo n.º 1
0
def test_to_string():
    assert crs.to_string({'init': 'EPSG:4326'}) == "+init=EPSG:4326"
Exemplo n.º 2
0
def info(ctx, input, aspect, indent, namespace, meta_member, verbose, bidx,
         masked):
    """Print metadata about the dataset as JSON.

    Optionally print a single metadata item as a string.
    """
    with ctx.obj['env'], rasterio.open(input) as src:

        info = dict(src.profile)
        info['shape'] = (info['height'], info['width'])
        info['bounds'] = src.bounds

        if src.crs:
            proj4 = src.crs.to_string()
            if proj4.startswith('+init=epsg'):
                proj4 = proj4.split('=')[1].upper()
            info['crs'] = proj4
        else:
            info['crs'] = None
            proj4 = ''

        info['res'] = src.res
        info['colorinterp'] = [ci.name for ci in src.colorinterp]
        info['units'] = [units or None for units in src.units]
        info['descriptions'] = src.descriptions
        info['indexes'] = src.indexes
        info['mask_flags'] = [[flag.name for flag in flags]
                              for flags in src.mask_flag_enums]

        if proj4 != '':
            info['lnglat'] = src.lnglat()

        if verbose:
            stats = [{
                'min': float(b.min()),
                'max': float(b.max()),
                'mean': float(b.mean())
            } for b in src.read(masked=masked)]
            info['stats'] = stats

            info['checksum'] = [src.checksum(i) for i in src.indexes]

            gcps, crs = src.gcps
            proj4 = crs.to_string()
            if proj4.startswith('+init=epsg'):
                proj4 = proj4.split('=')[1].upper()
            if gcps:
                info['gcps'] = {
                    'crs': proj4,
                    'points': [p.asdict() for p in gcps]
                }

        if aspect == 'meta':
            if meta_member == 'subdatasets':
                for name in src.subdatasets:
                    click.echo(name)
            elif meta_member == 'stats':
                band = src.read(bidx, masked=masked)
                click.echo(
                    '%f %f %f' %
                    (float(band.min()), float(band.max()), float(band.mean())))
            elif meta_member == 'checksum':
                click.echo(str(src.checksum(bidx)))
            elif meta_member:
                if isinstance(info[meta_member], (list, tuple)):
                    click.echo(" ".join(map(str, info[meta_member])))
                else:
                    click.echo(info[meta_member])
            else:
                click.echo(json.dumps(info, sort_keys=True, indent=indent))

        elif aspect == 'tags':
            click.echo(json.dumps(src.tags(ns=namespace), indent=indent))
Exemplo n.º 3
0
def test_to_string():
    assert crs.to_string({'init': 'EPSG:4326'}) == "+init=EPSG:4326"
Exemplo n.º 4
0
def create_kea_image(fid, width, height, count, transform, crs, no_data,
                     dtype, chunksize, blocksize, compression, band_names):
    """
    Initialises the KEA format layout
    """


    # group names for each band
    band_group_names = ['BAND{}'.format(i+1) for i in range(count)]

    # resolutio, ul corner tie point co-ordinate, rotation
    res = (transform[0], transform[4])
    ul = (transform[2], transform[5])
    rot = (transform[1], transform[3])

    # gdal or numpy number dtype value
    kea_dtype = NUMPY2KEADTYPE[dtype]

    # convert the proj4 dict to wkt
    sr = osr.SpatialReference()
    sr.ImportFromProj4(to_string(crs))
    crs_wkt = sr.ExportToWkt()

    # create band level groups
    band_groups = {}
    for gname in band_group_names:
        fid.create_group(gname)
        fid[gname].create_group('METADATA')

        # TODO need example data in order to flesh the overviews section
        fid[gname].create_group('OVERVIEWS')

        # dataset for our data and associated attributes
        fid[gname].create_dataset('DATA', shape=shape, dtype=dtype,
                                  compression=compression, chunks=chunks,
                                  fillvalue=no_data)

        # CLASS 'IMAGE', is a HDF recognised attribute
        fid[gname]['DATA'].attrs['CLASS'] = 'IMAGE'
        fid[gname]['DATA'].attrs['IMAGE_VERSION'] = IMAGE_VERSION
        fid[gname]['DATA'].attrs['BLOCK_SIZE'] = blocksize

        # KEA has defined their own numerical datatype mapping
        fid[gname].create_dataset('DATATYPE', shape=(1,),
                                  data=kea_dtype, dtype='uint16')

        # descriptors of the dataset
        # TODO what info can be populated here???
        fid[gname].create_dataset('DESCRIPTION', shape=(1,),
                                          data='')

        # we'll use a default, but all the user to overide later
        fid[gname].create_dataset('LAYER_TYPE', shape=(1,), data=0)
        fid[gname].create_dataset('LAYER_USAGE', shape=(1,), data=0)

        # TODO unclear on this section
        fid[gname].create_group('ATT/DATA')

        # TODO need an example in order to flesh the neighbours section
        fid[gname].create_group('ATT/NEIGHBOURS')

        # TODO unclear on header chunksize and size
        fid[gname].create_dataset('ATT/HEADER/CHUNKSIZE', data=0,
                                          dtype='uint64')
        fid[gname].create_dataset('ATT/HEADER/SIZE', data=[0,0,0,0,0],
                                          dtype='uint64')

        # do we have no a data value
        if no_data is not None:
            fid[gname].create_dataset('NO_DATA_VAL', shape=(1,),
                                      data=no_data)

    # Some groups like GCPS will be empty depending on the type of image
    # being written to disk. As will some datasets.
    # TODO need an example in order to flesh out the GCP's section
    fid.create_group('GCPS')

    # TODO what else can we put in the metadata section
    met = fid.create_group('METADATA')

    # if we don't have an band names defined, create default values
    if band_names is None:
        band_names = ['Band {}'.format(bn + 1) for bn in range(count)]
    elif len(band_names) != count:
        # overwrite the user (probably should notify the user)
        bname_format = 'Band {}'
        band_names = ['Band {}'.format(bn + 1) for bn in range(count)]

    # write the band names to the METADATA group, as individually
    # named datasets of the form 'Band_n'; n=1..nbands
    dname_fmt = 'Band_{}'
    for i, bname in enumerate(band_names):
        dname = dname_fmt.format(i + 1)
        met.create_dataset(dname, shape=(1,), data=bname)

    # necessary image collection info
    hdr = fid.create_group('HEADER')

    # header datasets
    hdr.create_dataset('WKT', shape=(1,), data=crs_wkt)
    hdr.create_dataset('SIZE', data=(width, height), dtype='uint64')
    hdr.create_dataset('VERSION', shape=(1,), data=VERSION)
    hdr.create_dataset('RES', data=res, dtype='float64')
    hdr.create_dataset('TL', data=ul, dtype='float64')
    hdr.create_dataset('ROT', data=rot, dtype='float64')
    hdr.create_dataset('NUMBANDS', shape=(1,), data=count, dtype='uint16')
    hdr.create_dataset('FILETYPE', shape=(1,), data=FILETYPE)
    hdr.create_dataset('GENERATOR', shape=(1,), data=GENERATOR)

    # flush any cached items
    fid.flush()
Exemplo n.º 5
0
import json

import rasterio
from rasterio import crs, warp
import shapely

import tilezilla
from tilezilla import geoutils, products, stores, tilespec

# Get tilespec, find product, retrieve intersecting tiles
weld_conus = tilespec.TILESPECS['WELD_CONUS']
product = products.ESPALandsat('../tests/data/LT50120312002300-SC20151009172149/')

tile = list(weld_conus.bounds_to_tiles(product.bounding_box(weld_conus.crs)))[0]

crs.to_string(weld_conus.crs)
weld_conus.crs


geoutils.bounds_to_polygon(tile.bounds)

# TODO: geom_geojson looks a little off
warp.transform_geom('EPSG:4326', 'EPSG:5070', json.dumps(tile.geom_geojson))


# Init the data store
# TODO: switch on some storage format metadata configuration values
store = stores.GeoTIFFStore('tests/data/stores/GeoTIFF', tile, product)

# TODO: allow override driver metadata options (section "creation_options:")
store.meta_options
Exemplo n.º 6
0
def gcps(ctx, input, geojson_type, projection, precision, use_rs, indent,
         compact):
    """Print GeoJSON representations of a dataset's control points.

    Each ground control point is represented as a GeoJSON feature. The
    'properties' member of each feature contains a JSON representation
    of the control point with the following items:

    \b
        row, col:
            row (or line) and col (or pixel) coordinates.
        x, y, z:
            x, y, and z spatial coordinates.
        crs:
            The coordinate reference system for x, y, and z.
        id:
            A unique (within the dataset) identifier for the control
            point.
        info:
            A brief description of the control point.
    """

    # Handle the invalid combinations of args.
    if geojson_type == 'feature' and indent and not use_rs:
        raise click.BadParameter(
            "Pretty-printing a sequence of Features requires the --rs option")

    with ctx.obj['env'], rasterio.open(input) as src:

        gcps, crs = src.gcps
        proj = crs.to_string()
        proj = proj.split('=')[1].upper() if proj.startswith('+init=epsg') else proj

        def update_props(data, **kwds):
            data['properties'].update(**kwds)
            return data

        def transform(feat):
            dst_crs = 'epsg:4326' if projection == 'geographic' else crs
            geom = transform_geom(crs, dst_crs, feat['geometry'],
                                  precision=precision)
            feat['geometry'] = geom
            return feat

        # Specifying --collection overrides --sequence.
        if geojson_type == 'collection':

            if projection == 'geographic' or precision >= 0:
                features = [transform(update_props(p.__geo_interface__, crs=proj)) for p in gcps]
            else:
                features = [update_props(p.__geo_interface__, crs=proj) for p in gcps]

            click.echo(json.dumps(
                {'type': 'FeatureCollection', 'features': features},
                separators=(',', ':') if compact else None,
                indent=indent))

        else:
            for p in gcps:

                if use_rs:
                    click.echo(u'\x1e', nl=False)

                if projection == 'geographic' or precision >= 0:
                    feat = transform(update_props(p.__geo_interface__, crs=proj))
                else:
                    feat = update_props(p.__geo_interface__, crs=proj)

                click.echo(json.dumps(
                    feat,
                    separators=(',', ':') if compact else None,
                    indent=indent))
Exemplo n.º 7
0
def info(ctx, input, aspect, indent, namespace, meta_member, verbose, bidx,
         masked):
    """Print metadata about the dataset as JSON.

    Optionally print a single metadata item as a string.
    """
    with ctx.obj['env'], rasterio.open(input) as src:

        info = dict(src.profile)
        info['shape'] = (info['height'], info['width'])
        info['bounds'] = src.bounds

        if src.crs:
            proj4 = src.crs.to_string()
            if proj4.startswith('+init=epsg'):
                proj4 = proj4.split('=')[1].upper()
            info['crs'] = proj4
        else:
            info['crs'] = None
            proj4 = ''

        info['res'] = src.res
        info['colorinterp'] = [ci.name for ci in src.colorinterp]
        info['units'] = [units or None for units in src.units]
        info['descriptions'] = src.descriptions
        info['indexes'] = src.indexes
        info['mask_flags'] = [[
            flag.name for flag in flags] for flags in src.mask_flag_enums]

        if proj4 != '':
            info['lnglat'] = src.lnglat()

        if verbose:
            stats = [{'min': float(b.min()),
                      'max': float(b.max()),
                      'mean': float(b.mean())
                      } for b in src.read(masked=masked)]
            info['stats'] = stats

            info['checksum'] = [src.checksum(i) for i in src.indexes]

            gcps, crs = src.gcps
            proj4 = crs.to_string()
            if proj4.startswith('+init=epsg'):
                proj4 = proj4.split('=')[1].upper()
            if gcps:
                info['gcps'] = {
                    'crs': proj4, 'points': [p.asdict() for p in gcps]}

        if aspect == 'meta':
            if meta_member == 'subdatasets':
                for name in src.subdatasets:
                    click.echo(name)
            elif meta_member == 'stats':
                band = src.read(bidx, masked=masked)
                click.echo('%f %f %f' % (
                    float(band.min()),
                    float(band.max()),
                    float(band.mean())))
            elif meta_member == 'checksum':
                click.echo(str(src.checksum(bidx)))
            elif meta_member:
                if isinstance(info[meta_member], (list, tuple)):
                    click.echo(" ".join(map(str, info[meta_member])))
                else:
                    click.echo(info[meta_member])
            else:
                click.echo(json.dumps(info, sort_keys=True, indent=indent))

        elif aspect == 'tags':
            click.echo(
                json.dumps(src.tags(ns=namespace), indent=indent))