API Reference

telluric.constants module

Useful constants.

telluric.constants.DEFAULT_CRS = CRS({'init': 'epsg:4326', 'no_defs': True})

Default CRS, set to WGS84_CRS.

telluric.constants.EQUAL_AREA_CRS = CRS({'proj': 'eck4'})

Eckert IV CRS.

telluric.constants.WEB_MERCATOR_CRS = CRS({'init': 'epsg:3857', 'no_defs': True})

Web Mercator CRS.

telluric.constants.WGS84_CRS = CRS({'init': 'epsg:4326', 'no_defs': True})

WGS84 CRS.

telluric.vectors module

class telluric.vectors.GeoVector(shape, crs=CRS({'init': 'epsg:4326', 'no_defs': True}), safe=True)

Geometric element with an associated CRS.

This class has also all the properties and methods of shapely.geometry.BaseGeometry.

__init__(shape, crs=CRS({'init': 'epsg:4326', 'no_defs': True}), safe=True)

Initialize GeoVector.

Parameters:
  • shape (shapely.geometry.BaseGeometry) – Geometry.
  • crs (CRS (optional)) – Coordinate Reference System, default to telluric.constants.DEFAULT_CRS.
  • safe (bool, optional) – Check method arguments validity (only CRS so far) if False, default to True
almost_equals(other, decimal=6)

invariant to crs.

equals_exact(other, tolerance)

invariant to crs.

classmethod from_bounds(xmin, ymin, xmax, ymax, crs=CRS({'init': 'epsg:4326', 'no_defs': True}))

Creates GeoVector object from bounds.

Parameters:

Examples

>>> from telluric import GeoVector
>>> GeoVector.from_bounds(xmin=0, ymin=0, xmax=1, ymax=1)
GeoVector(shape=POLYGON ((0 0, 0 1, 1 1, 1 0, 0 0)), crs=CRS({'init': 'epsg:4326'}))
>>> GeoVector.from_bounds(xmin=0, xmax=1, ymin=0, ymax=1)
GeoVector(shape=POLYGON ((0 0, 0 1, 1 1, 1 0, 0 0)), crs=CRS({'init': 'epsg:4326'}))
classmethod from_geojson(filename)

Load vector from geojson.

classmethod from_xyz(x, y, z)

Creates GeoVector from Mercator slippy map values.

get_shape(crs)

Gets the underlying Shapely shape in a specified CRS.

This method deliberately does not have a default crs=self.crs to force the user to specify it.

polygonize(width, cap_style_line=2, cap_style_point=1)

Turns line or point into a buffered polygon.

to_geojson(filename)

Save vector as geojson.

telluric.vectors.generate_tile_coordinates(roi, num_tiles)

Yields N x M rectangular tiles for a region of interest.

Parameters:
  • roi (GeoVector) – Region of interest
  • num_tiles (tuple) – Tuple (horizontal_tiles, vertical_tiles)
Yields:

~telluric.vectors.GeoVector

telluric.vectors.generate_tile_coordinates_from_pixels(roi, scale, size)

Yields N x M rectangular tiles for a region of interest.

Parameters:
  • roi (GeoVector) – Region of interest
  • scale (float) – Scale factor (think of it as pixel resolution)
  • size (tuple) – Pixel size in (width, height) to be multiplied by the scale factor
Yields:

~telluric.vectors.GeoVector

telluric.vectors.get_dimension(geometry)

Gets the dimension of a Fiona-like geometry element.

telluric.features module

class telluric.features.GeoFeature(geovector, properties)

GeoFeature object.

__init__(geovector, properties)

Initialize a GeoFeature object.

Parameters:
  • geovector (GeoVector) – Geometry.
  • properties (dict) – Properties.
classmethod from_raster(raster, properties)

Initialize a GeoFeature object with a GeoRaster

Parameters:
  • raster (GeoRaster) – the raster in the feature
  • properties (dict) – Properties.
get_shape(crs)

Gets the underlying Shapely shape in a specified CRS.

class telluric.features.GeoFeatureWithRaster(raster, properties)
__init__(raster, properties)
Initialize a GeoFeature object with a raster,

When a GeoFeature has a raster the default behviour is the same as GeoFeature where the geometry is the union of all rasters footprint.

we will override some methods to work differetnly like: 1. reproject (TBD) 2. rasterize (from feature collection, TBD) 3. to_record

Parameters:
  • raster[s] (array or single GeoRaster) –
  • properties (dict) – Properties.
telluric.features.raster_from_assets(assets)

create a raster from assets, assets is a dictonary of links like described in the stacs inteface https://github.com/radiantearth/stac-spec/tree/master/json-spec/examples

  • currently we support a single raster asset, in the feature we could support more
telluric.features.serialize_properties(properties)

Serialize properties.

Parameters:properties (dict) – Properties to serialize.
telluric.features.transform_properties(properties, schema)

Transform properties types according to a schema.

Parameters:
  • properties (dict) – Properties to transform.
  • schema (dict) – Fiona schema containing the types.

telluric.collections module

class telluric.collections.BaseCollection
dissolve(by=None, aggfunc=None)

Dissolve geometries and rasters within groupby.

filter(intersects)

Filter results that intersect a given GeoFeature or Vector.

get_values(key)

Get all values of a certain property.

groupby(by)

Groups collection using a value of a property.

Parameters:by (str or callable) – If string, name of the property by which to group. If callable, should receive a GeoFeature and return the category.
Returns:
Return type:_CollectionGroupBy
is_empty

True if all features are empty.

map(map_function)

Return a new FeatureCollection with the results of applying map_function to each element.

rasterize(dest_resolution, *, polygonize_width=0, crs=CRS({'init': 'epsg:3857', 'no_defs': True}), fill_value=None, bounds=None, dtype=None, **polygonize_kwargs)

Binarize a FeatureCollection and produce a raster with the target resolution.

Parameters:
  • dest_resolution (float) – Resolution in units of the CRS.
  • polygonize_width (int, optional) – Width for the polygonized features (lines and points) in pixels, default to 0 (they won’t appear).
  • crs (CRS, dict (optional)) – Coordinate system, default to telluric.constants.WEB_MERCATOR_CRS.
  • fill_value (float or function, optional) – Value that represents data, default to None (will default to telluric.rasterization.FILL_VALUE. If given a function, it must accept a single GeoFeature and return a numeric value.
  • nodata_value (float, optional) – Nodata value, default to None (will default to telluric.rasterization.NODATA_VALUE.
  • bounds (GeoVector, optional) – Optional bounds for the target image, default to None (will use the FeatureCollection convex hull).
  • dtype (numpy.dtype, optional) – dtype of the result, required only if fill_value is a function.
  • polygonize_kwargs (dict) – Extra parameters to the polygonize function.
save(filename, driver=None)

Saves collection to file.

sort(by, desc=False)

Sorts by given property or function, ascending or descending order.

Parameters:
  • by (str or callable) – If string, property by which to sort. If callable, it should receive a GeoFeature a return a value by which to sort.
  • desc (bool, optional) – Descending sort, default to False (ascending).
class telluric.collections.FeatureCollection(results)
__init__(results)

Initialize FeatureCollection object.

Parameters:results (iterable) – Iterable of GeoFeature objects.
classmethod from_geovectors(geovectors)

Builds new FeatureCollection from a sequence of GeoVector objects.

exception telluric.collections.FeatureCollectionIOError
class telluric.collections.FileCollection(filename, crs, schema, length)

FileCollection object.

__init__(filename, crs, schema, length)

Initialize a FileCollection object.

Use the open() method instead.

classmethod open(filename)

Creates a FileCollection from a file in disk.

Parameters:filename (str) – Path of the file to read.
telluric.collections.dissolve(collection, aggfunc=None)

Dissolves features contained in a FeatureCollection and applies an aggregation function to its properties.

telluric.georaster module

class telluric.georaster.GeoRaster2(image=None, affine=None, crs=None, filename=None, band_names=None, nodata=0, shape=None, footprint=None, temporary=False)

Represents multiband georeferenced image, supporting nodata pixels. The name “GeoRaster2” is temporary.

conventions:

  • .array is np.masked_array, mask=True on nodata pixels.
  • .array is [band, y, x]
  • .affine is affine.Affine
  • .crs is rasterio.crs.CRS
  • .band_names is list of strings, order corresponding to order in .array
__init__(image=None, affine=None, crs=None, filename=None, band_names=None, nodata=0, shape=None, footprint=None, temporary=False)

Create a GeoRaster object

Parameters:
  • filename – optional path/url to raster file for lazy loading
  • image – optional supported: np.ma.array, np.array, TODO: PIL image
  • affine – affine.Affine, or 9 numbers: [step_x, 0, origin_x, 0, step_y, origin_y, 0, 0, 1]
  • crs – wkt/epsg code, e.g. {‘init’: ‘epsg:32620’}
  • band_names – e.g. [‘red’, ‘blue’] or ‘red’
  • shape – raster image shape, optional
  • nodata – if provided image is array (not masked array), treat pixels with value=nodata as nodata
  • temporary – True means that file referenced by filename is temporary and will be removed by destructor, default False
add_raster(other, merge_strategy, resampling)

Return merge of 2 rasters, in geography of the first one.

merge_strategy - for pixels with values in both rasters.

affine

Raster affine.

apply_transform(transformation, resampling)

Apply affine transformation on image & georeferencing.

as specific cases, implement ‘resize’, ‘rotate’, ‘translate’

astype(dst_type, in_range='dtype', out_range='dtype', clip_negative=False)

Returns copy of the raster, converted to desired type Supported types: uint8, uint16, uint32, int8, int16, int32, float16, float32, float64

Parameters:
  • dst_type – desired type
  • in_range – str or 2-tuple, default ‘dtype’: ‘image’: use image min/max as the intensity range, ‘dtype’: use min/max of the image’s dtype as the intensity range, 2-tuple: use explicit min/max intensities, it is possible to use ‘min’ or ‘max’ as tuple values - in this case they will be replaced by min or max intensity of image respectively
  • out_range – str or 2-tuple, default ‘dtype’: ‘dtype’: use min/max of the image’s dtype as the intensity range, 2-tuple: use explicit min/max intensities
  • clip_negative – boolean, if True - clip the negative range, default False
Returns:

numpy array of values

attributes(url)

Without opening image, return size/bitness/bands/geography/….

band_names

Raster affine.

bounds()

Return image rectangle in pixels, as shapely.Polygon.

center()

Return footprint center in world coordinates, as GeoVector.

colorize(colormap, band_name=None, vmin=None, vmax=None)

Apply a colormap on a selected band.

colormap list: https://matplotlib.org/examples/color/colormaps_reference.html

Parameters:
  • colormap (str) –
  • name from this list https (Colormap) –
  • band_name (str, optional) –
  • of band to colorize, if none the first band will be used (Name) –
  • vmax (vmin,) –
  • and maximum range for normalizing array values, if None actual raster values will be used (minimum) –
Returns:

Return type:

GeoRaster2

copy_with(**kwargs)

Get a copy of this GeoRaster with some attributes changed. NOTE: image is shallow-copied!

corner(corner)

Return footprint origin in world coordinates, as GeoVector.

corners()

Return footprint corners, as {corner_type -> GeoVector}.

crop(vector, resolution=None, masked=True, bands=None)

crops raster outside vector (convex hull) :param vector: GeoVector :param resolution: output resolution, None for full resolution :return: GeoRaster

crs

Raster crs.

deepcopy_with(**kwargs)

Get a copy of this GeoRaster with some attributes changed. NOTE: image is shallow-copied!

footprint()

Return rectangle in world coordinates, as GeoVector.

classmethod from_bytes(image_bytes, affine, crs, band_names=None)

Create GeoRaster from image BytesIo object.

Parameters:
  • image_bytes – io.BytesIO object
  • affine – rasters affine
  • crs – rasters crs
  • band_names – e.g. [‘red’, ‘blue’] or ‘red’
classmethod from_tiles(tiles)

Compose raster from tiles. return GeoRaster.

get(point)

Get the pixel values at the requested point.

Parameters:point – A GeoVector(POINT) with the coordinates of the values to get
Returns:numpy array of values
get_tile(x_tile, y_tile, zoom, bands=None, masked=False, resampling=<Resampling.cubic: 2>)

Convert mercator tile to raster window.

Parameters:
  • x_tile – x coordinate of tile
  • y_tile – y coordinate of tile
  • zoom – zoom level
  • bands – list of indices of requested bands, default None which returns all bands
Returns:

GeoRaster2 of tile in WEB_MERCATOR_CRS

You can use TELLURIC_GET_TILE_BUFFER env variable to control the number of pixels surrounding the vector you should fetch when using this method on a raster that is not in WEB_MERCATOR_CRS default to 10

get_window(window, bands=None, xsize=None, ysize=None, resampling=<Resampling.cubic: 2>, masked=True, affine=None)

Get window from raster.

Parameters:
  • window – requested window
  • bands – list of indices of requested bads, default None which returns all bands
  • xsize – tile x size default None, for full resolution pass None
  • ysize – tile y size default None, for full resolution pass None
  • resampling – which Resampling to use on reading, default Resampling.cubic
  • masked – boolean, if True the return value will be a masked array. Default is True
Returns:

GeoRaster2 of tile

height

Raster height.

image

Raster bitmap in numpy array.

image_corner(corner)

Return image corner in pixels, as shapely.Point.

intersect(other)

Pixels outside either raster are set nodata

mask(vector, mask_shape_nodata=False)

Set pixels outside vector as nodata.

Parameters:
  • vector – GeoVector, GeoFeature, FeatureCollection
  • mask_shape_nodata – if True - pixels inside shape are set nodata, if False - outside shape is nodata
Returns:

GeoRaster2

num_bands

Raster number of bands.

classmethod open(filename, band_names=None, lazy_load=True, **kwargs)

Read a georaster from a file.

Parameters:
  • filename – url
  • band_names – list of strings, or string. if None - will try to read from image, otherwise - these will be [‘0’, ..]
  • lazy_load – if True - do not load anything
Returns:

GeoRaster2

origin()

Return footprint origin in world coordinates, as GeoVector.

pixel_crop(bounds, xsize=None, ysize=None, window=None, masked=True, bands=None)

Crop raster outside vector (convex hull).

Parameters:
  • bounds – bounds of requester portion of the image in image pixels
  • xsize – output raster width, None for full resolution
  • ysize – output raster height, None for full resolution
  • windows – the bounds representation window on image in image pixels, Optional
  • bands – list of indices of requested bands, default None which returns all bands
Returns:

GeoRaster

project(dst_crs, resampling)

Return reprojected raster.

rectify()

Rotate raster northwards.

reduce(op)

Reduce the raster to a score, using ‘op’ operation.

nodata pixels are ignored. op is currently limited to numpy.ma, e.g. ‘mean’, ‘std’ etc :returns list of per-band values

reproject(dst_crs=None, resolution=None, dimensions=None, src_bounds=None, dst_bounds=None, target_aligned_pixels=False, resampling=<Resampling.cubic: 2>, creation_options=None, **kwargs)

Return re-projected raster to new raster.

Parameters:
  • dst_crs (rasterio.crs.CRS, optional) – Target coordinate reference system.
  • resolution (tuple (x resolution, y resolution) or float, optional) – Target resolution, in units of target coordinate reference system.
  • dimensions (tuple (width, height), optional) – Output size in pixels and lines.
  • src_bounds (tuple (xmin, ymin, xmax, ymax), optional) – Georeferenced extent of output (in source georeferenced units).
  • dst_bounds (tuple (xmin, ymin, xmax, ymax), optional) – Georeferenced extent of output (in destination georeferenced units).
  • target_aligned_pixels (bool, optional) – Align the output bounds based on the resolution. Default is False.
  • resampling (rasterio.enums.Resampling) – Reprojection resampling method. Default is cubic.
  • creation_options (dict, optional) – Custom creation options.
  • kwargs (optional) – Additional arguments passed to transformation function.
Returns:

out

Return type:

GeoRaster2

res_xy()

Returns X and Y resolution.

resize(ratio=None, ratio_x=None, ratio_y=None, dest_width=None, dest_height=None, dest_resolution=None, resampling=<Resampling.cubic: 2>)

Provide either ratio, or ratio_x and ratio_y, or dest_width and/or dest_height.

Returns:GeoRaster2
resolution()

Return resolution. if different in different axis - return geometric mean.

save(filename, tags=None, **kwargs)

Save GeoRaster to a file.

Parameters:
  • filename – url
  • tags – tags to add to default namespace

optional parameters:

  • GDAL_TIFF_INTERNAL_MASK: specifies whether mask is within image file, or additional .msk
  • overviews: if True, will save with previews. default: True
  • factors: list of factors for the overview, default: calculated based on raster width and height
  • resampling: to build overviews. default: cubic
  • tiled: if True raster will be saved tiled, default: False
  • compress: any supported rasterio.enums.Compression value, default to LZW
  • blockxsize: int, tile x size, default:256
  • blockysize: int, tile y size, default:256
  • creation_options: dict, key value of additional creation options
  • nodata: if passed, will save with nodata value (e.g. useful for qgis)
save_cloud_optimized(dest_url, resampling=<Resampling.gauss: 7>)

Save as Cloud Optimized GeoTiff object to a new file.

Parameters:
  • dest_url – path to the new raster
  • resampling – which Resampling to use on reading, default Resampling.gauss
Returns:

new VirtualGeoRaster of the tiled object

shape

Raster shape.

classmethod tags(filename, namespace=None)

Extract tags from file.

to_bytes(transparent=True, thumbnail_size=None, resampling=None, in_range='dtype', out_range='dtype', format='png')

Convert to selected format (discarding geo).

Optionally also resizes. Note: for color images returns interlaced. :param transparent: if True - sets alpha channel for nodata pixels :param thumbnail_size: if not None - resize to thumbnail size, e.g. 512 :param in_range: input intensity range :param out_range: output intensity range :param format : str, image format, default “png” :param resampling: one of Resampling enums

:return bytes

to_pillow_image(return_mask=False)

Return Pillow. Image, and optionally also mask.

to_png(transparent=True, thumbnail_size=None, resampling=None, in_range='dtype', out_range='dtype')

Convert to png format (discarding geo).

Optionally also resizes. Note: for color images returns interlaced. :param transparent: if True - sets alpha channel for nodata pixels :param thumbnail_size: if not None - resize to thumbnail size, e.g. 512 :param in_range: input intensity range :param out_range: output intensity range :param resampling: one of Resampling enums

:return bytes

to_raster(vector)

Return the vector in pixel coordinates, as shapely.Geometry.

to_tiles()

Yield slippy-map tiles.

to_world(shape, dst_crs=None)

Return the shape (provided in pixel coordinates) in world coordinates, as GeoVector.

transform

Raster affine.

vectorize(condition=None)

Return GeoVector of raster, excluding nodata pixels, subject to ‘condition’.

Parameters:condition – e.g. 42 < value < 142.

e.g. if no nodata pixels, and without condition - this == footprint().

width

Raster width.

exception telluric.georaster.GeoRaster2Error

Base class for exceptions in the GeoRaster class.

exception telluric.georaster.GeoRaster2IOError

Base class for exceptions in GeoRaster read/write.

exception telluric.georaster.GeoRaster2NotImplementedError

Base class for NotImplementedError in the GeoRaster class.

exception telluric.georaster.GeoRaster2Warning

Base class for warnings in the GeoRaster class.

class telluric.georaster.MergeStrategy

An enumeration.

class telluric.georaster.PixelStrategy

An enumeration.

telluric.georaster.merge_all(rasters, roi=None, dest_resolution=None, merge_strategy=<MergeStrategy.UNION: 2>, shape=None, ul_corner=None, crs=None, pixel_strategy=<PixelStrategy.FIRST: 1>)

Merge a list of rasters, cropping by a region of interest. There are cases that the roi is not precise enough for this cases one can use, the upper left corner the shape and crs to precisely define the roi. When roi is provided the ul_corner, shape and crs are ignored

telluric.georaster.merge_two(one, other, merge_strategy=<MergeStrategy.UNION: 2>, silent=False, pixel_strategy=<PixelStrategy.FIRST: 1>)

Merge two rasters into one.

Parameters:
Returns:

Return type:

GeoRaster2

telluric.plotting module

Code for interactive vector plots.

telluric.plotting.layer_from_element(element, style_function=None)

Return Leaflet layer from shape.

Parameters:element (telluric.vectors.GeoVector, telluric.features.GeoFeature, telluric.collections.BaseCollection) – Data to plot.
telluric.plotting.plot(feature, mp=None, style_function=None, **map_kwargs)

Plots a GeoVector in an ipyleaflet map.

Parameters:
telluric.plotting.simple_plot(feature, *, mp=None, **map_kwargs)

Plots a GeoVector in a simple Folium map.

For more complex and customizable plots using Jupyter widgets, use the plot function instead.

Parameters:feature (telluric.vectors.GeoVector, telluric.features.GeoFeature, telluric.collections.BaseCollection) – Data to plot.
telluric.plotting.zoom_level_from_geometry(geometry, splits=4)

Generate optimum zoom level for geometry.

Notes

The obvious solution would be

>>> mercantile.bounding_tile(*geometry.get_shape(WGS84_CRS).bounds).z

However, if the geometry is split between two or four tiles, the resulting zoom level might be too big.