arcgis.raster module

The arcgis.raster module containing classes and raster analysis functions for working with raster data and imagery layers.

Raster data is made up of a grid of cells, where each cell or pixel can have a value. Raster data is useful for storing data that varies continuously, as in a satellite image, a surface of chemical concentrations, or an elevation surface.

Use arcgis.raster.analytics.is_supported(gis) to check if raster analysis is supported in your GIS.

ImageryLayer

class arcgis.raster.ImageryLayer(url, gis=None)
add_rasters(raster_type, item_ids=None, service_url=None, compute_statistics=False, build_pyramids=False, build_thumbnail=False, minimum_cell_size_factor=None, maximum_cell_size_factor=None, attributes=None, geodata_transforms=None, geodata_transform_apply_method='esriGeodataTransformApplyAppend')

This operation is supported at 10.1 and later. The Add Rasters operation is performed on an image service resource. The Add Rasters operation adds new rasters to an image service (POST only). The added rasters can either be uploaded items, using the item_ids parameter, or published services, using the service_url parameter. If item_ids is specified, uploaded rasters are copied to the image service’s dynamic image workspace location; if the service_url is specified, the image service adds the URL to the mosaic dataset no raster files are copied. The service_url is required input for the following raster types: Image Service, Map Service, WCS, and WMS.

Inputs:

item_ids - The upload items (raster files) to be added. Either
item_ids or service_url is needed to perform this operation.

Syntax: item_ids=<itemId1>,<itemId2> Example: item_ids=ib740c7bb-e5d0-4156-9cea-12fa7d3a472c,

ib740c7bb-e2d0-4106-9fea-12fa7d3a482c
service_url - The URL of the service to be added. The image service

will add this URL to the mosaic dataset. Either item_ids or service_url is needed to perform this operation. The service URL is required for the following raster types: Image Service, Map Service, WCS, and WMS.

Example: service_url=http://myserver/arcgis/services/Portland/ImageServer
raster_type - The type of raster files being added. Raster types

define the metadata and processing template for raster files to be added. Allowed values are listed in image service resource.

Example: Raster Dataset | CADRG/ECRG | CIB | DTED | Image Service | Map Service | NITF | WCS | WMS
compute_statistics - If true, statistics for the rasters will be
computed. The default is false.
Values: false | true
build_pyramids - If true, builds pyramids for the rasters. The
default is false.
Values: false | true
build_thumbnail - If true, generates a thumbnail for the rasters.
The default is false.
Values: false | true
minimum_cell_size_factor - The factor (times raster resolution) used

to populate the MinPS field (maximum cell size above which the raster is visible).

Syntax: minimum_cell_size_factor=<minimum_cell_size_factor> Example: minimum_cell_size_factor=0.1
maximum_cell_size_factor - The factor (times raster resolution) used

to populate MaxPS field (maximum cell size below which raster is visible).

Syntax: maximum_cell_size_factor=<maximum_cell_size_factor> Example: maximum_cell_size_factor=10
attributes - Any attribute for the added rasters.

Syntax: {

“<name1>” : <value1>, “<name2>” : <value2>

} Example: {

“MinPS”: 0, “MaxPS”: 20; “Year” : 2002, “State” : “Florida”

}

geodata_transforms - The geodata transformations applied on the

added rasters. A geodata transformation is a mathematical model that performs a geometric transformation on a raster; it defines how the pixels will be transformed when displayed or accessed. Polynomial, projective, identity, and other transformations are available. The geodata transformations are applied to the dataset that is added.

Syntax: [ {

“geodataTransform” : “<geodataTransformName1>”, “geodataTransformArguments” : {<geodataTransformArguments1>} }, { “geodataTransform” : “<geodataTransformName2>”, “geodataTransformArguments” : {<geodataTransformArguments2>} }

]

The syntax of the geodataTransformArguments property varies based on the specified geodataTransform name. See Geodata Transformations documentation for more details.

geodata_transform_apply_method - This parameter defines how to apply

the provided geodataTransform. The default is esriGeodataTransformApplyAppend.

Values: esriGeodataTransformApplyAppend | esriGeodataTransformApplyReplace | esriGeodataTransformApplyOverwrite
blend()

overlapping pixels at the same location are resolved by blending all overlapping pixels :return: this imagery layer with mosaic operation set to ‘blend’

colormap()

The colormap resource returns RGB color representation of pixel values. This resource is supported if the hasColormap property of the service is true.

compute_histograms(geometry, mosaic_rule=None, rendering_rule=None, pixel_size=None)

The compute_histograms operation is performed on an imagery layer resource. This operation is supported by any imagery layer published with mosaic datasets or a raster dataset. The result of this operation contains both statistics and histograms computed from the given extent. Inputs: geometry - A geometry that defines the geometry within which the histogram

is computed. The geometry can be an envelope or a polygon. The structure of the geometry is the same as the structure of the JSON geometry objects returned by the ArcGIS REST API, or an arcgis.geometry Geometry object
mosaic_rule - Specifies the mosaic rule when defining how individual
images should be mosaicked. When a mosaic rule is not specified, the default mosaic rule of the image service will be used (as advertised in the root resource: defaultMosaicMethod, mosaicOperator, sortField, sortValue).
rendering_rule - Specifies the rendering rule for how the requested
image should be rendered.
pixel_size - The pixel level being used (or the resolution being looked at).
If pixel size is not specified, then pixel_size will default to the base resolution of the dataset. The raster at the specified pixel size in the mosaic dataset will be used for histogram calculation. The structure of the pixel_size parameter is the same as the structure of the point object returned by the ArcGIS REST API. In addition to the JSON structure, you can specify the pixel size with a simple comma-separated syntax.
export_image(bbox=None, image_sr=None, bbox_sr=None, size=None, time=None, export_format='jpgpng', pixel_type=None, no_data=None, no_data_interpretation='esriNoDataMatchAny', interpolation=None, compression=None, compression_quality=None, band_ids=None, mosaic_rule=None, rendering_rule=None, f='json', save_folder=None, save_file=None, compression_tolerance=None, adjust_aspect_ratio=None)

The export_image operation is performed on an imagery layer. The result of this operation is an image resource. This resource provides information about the exported image, such as its URL, extent, width, and height. In addition to the usual response formats of HTML and JSON, you can also request the image format while performing this operation. When you perform an export with the image format , the server responds by directly streaming the image bytes to the client. With this approach, you don’t get any information associated with the exported image other than the image itself.

Inputs:
bbox - Optional. The extent (bounding box) of the exported image. Unless

the bbox_sr parameter has been specified, the bbox is assumed to be in the spatial reference of the imagery layer.

The bbox should be specified as an arcgis.geometry.Envelope object, it’s json representation or as a list or string with this format: ‘<xmin>, <ymin>, <xmax>, <ymax>’

If omitted, the extent of the imagery layer is used

image_sr - The spatial reference of the exported image.
The spatial reference can be specified as either a well-known ID, it’s json representation or as an arcgis.geometry.SpatialReference object. If the image_sr is not specified, the image will be exported in the spatial reference of the imagery layer.
bbox_sr - The spatial reference of the bbox.
The spatial reference can be specified as either a well-known ID, it’s json representation or as an arcgis.geometry.SpatialReference object. If the image_sr is not specified, bbox is assumed to be in the spatial reference of the imagery layer.
size - The size (width * height) of the exported image in
pixels. If size is not specified, an image with a default size of 400 * 400 will be exported. Format: list of [width, height]
time - The time instant or the time extent of the exported image.

Time instant specified as datetime.date, datetime.datetime or timestamp in milliseconds since epoch Syntax: time=<timeInstant>

Time extent specified as list of [<startTime>, <endTime>] For time extents one of <startTime> or <endTime> could be None. A None value specified for start time or end time will represent infinity for start or end time respectively. Syntax: time=[<startTime>, <endTime>] ; specified as datetime.date, datetime.datetime or timestamp

export_format - The format of the exported image. The default format is jpgpng.

The jpgpng format returns a JPG if there are no transparent pixels in the requested extent; otherwise, it returns a PNG (png32).

Values: jpgpng | png | png8 | png24 | jpg | bmp | gif | tiff | png32 | bip | bsq | lerc

pixel_type - The pixel type, also known as data type, pertains to
the type of values stored in the raster, such as signed integer, unsigned integer, or floating point. Integers are whole numbers, whereas floating points have decimals.

no_data - The pixel value representing no information.

no_data_interpretation - Interpretation of the no_data setting. The
default is esriNoDataMatchAny when no_data is a number, and esriNoDataMatchAll when no_data is a comma-delimited string: esriNoDataMatchAny | esriNoDataMatchAll.
interpolation - The resampling process of extrapolating the

pixel values while transforming the raster dataset when it undergoes warping or when it changes coordinate space. One of: RSP_BilinearInterpolation, RSP_CubicConvolution,

RSP_Majority, RSP_NearestNeighbor
compression - Controls how to compress the image when exporting
to TIFF format: None, JPEG, LZ77. It does not control compression on other formats.
compression_quality - Controls how much loss the image will be
subjected to by the compression algorithm. Valid value ranges of compression quality are from 0 to 100.
band_ids - If there are multiple bands, you can specify a single
band to export, or you can change the band combination (red, green, blue) by specifying the band number. Band number is 0 based. Specified as list of ints, eg [2,1,0]
mosaic_rule - Specifies the mosaic rule when defining how
individual images should be mosaicked. When a mosaic rule is not specified, the default mosaic rule of the image service will be used (as advertised in the root resource: defaultMosaicMethod, mosaicOperator, sortField, sortValue).
rendering_rule - Specifies the rendering rule for how the
requested image should be rendered.
f - The response format. default is json
Values: json | image | kmz If image format is chosen, the bytes of the exported image are returned unless save_folder and save_file parameters are also passed, in which case the image is written to the specified file

save_folder - the folder in which the exported image is saved when f=image

save_file - the file in which the exported image is saved when f=image

compression_tolerance - Controls the tolerance of the lerc compression algorithm. The tolerance defines the
maximum possible error of pixel values in the compressed image. It’s a double value. Example: compression_tolerance=0.5 is loseless for 8 and 16 bit images, but has an accuracy of +-0.5 for floating point data. The compression tolerance works for the LERC format only.

adjust_aspect_ratio - indicates whether to adjust the aspect ratio or not. By default adjust_aspect_ratio is true, that means the actual bbox will be adjusted to match the width/height ratio of size paramter, and the response image has square pixels. Values: True | False

extent

Area of interest. Used for displaying the imagery layer when queried

filter_by(where=None, geometry=None, time=None, lock_rasters=True)

Filters the layer by where clause, geometry and temporal filters

Parameters:
  • where – a where clause on this layer to filter the imagery layer by the selection sql statement. Any legal SQL where clause operating on the fields in the raster
  • geometry – spatial filter from arcgis.geometry.filters module to filter results by a spatial relationship with another geometry
  • time

    a temporal filter to this layer to filter the imagery layer by time using the specified time instant or the time extent. Time instant specified as datetime.date, datetime.datetime or timestamp in milliseconds since epoch Syntax: time_filter=<timeInstant>

    Time extent specified as list of [<startTime>, <endTime>] For time extents one of <startTime> or <endTime> could be None. A None value specified for start time or end time will represent infinity for start or end time respectively. Syntax: time_filter=[<startTime>, <endTime>] ; specified as datetime.date, datetime.datetime or timestamp in milliseconds

  • lock_rasters – bool If True, the LockRaster mosaic rule is applied to the layer, using the filtered objectids
Returns:

ImageryLayer with filtered images meeting the filter criteria

filtered_rasters()

The object ids of the filtered rasters in this imagery layer, by applying the where clause, spatial and temporal filters. If no rasters are filtered, returns None. If all rasters are filtered, returns empty list

first()

overlapping pixels at the same location are resolved by picking the first image :return: this imagery layer with mosaic operation set to ‘first’

classmethod fromitem(item)
get_samples(geometry, geometry_type=None, sample_distance=None, sample_count=None, mosaic_rule=None, pixel_size=None, return_first_value_only=None, interpolation=None, out_fields=None)

The get_samples operation is supported by both mosaic dataset and raster dataset imagery layers. The result of this operation includes sample point locations, pixel values, and corresponding spatial resolutions of the source data for a given geometry. When the input geometry is a polyline, envelope, or polygon, sampling is based on sample_count or sample_distance; when the input geometry is a point or multipoint, the point or points are used directly. The number of sample locations in the response is based on the sample_distance or sample_count parameter and cannot exceed the limit of the image service (the default is 1000, which is an approximate limit). Inputs: geometry - A geometry that defines the location(s) to be sampled. The

structure of the geometry is the same as the structure of the JSON geometry objects returned by the ArcGIS REST API. Applicable geometry types are point, multipoint, polyline, polygon, and envelope. When spatialReference is omitted in the input geometry, it will be assumed to be the spatial reference of the image service.
geometry_type - The type of geometry specified by the geometry parameter.
The geometry type can be point, multipoint, polyline, polygon, or envelope. Values: esriGeometryPoint | esriGeometryMultipoint | esriGeometryPolyline | esriGeometryPolygon | esriGeometryEnvelope
sample_distance - The distance interval used to sample points from the
provided path. The unit is the same as the input geometry. If neither sample_count nor sample_distance is provided, no densification can be done for paths (polylines), and a default sample_count (100) is used for areas (polygons or envelopes).
sample_count - The approximate number of sample locations from the provided
path. If neither sample_count nor sample_distance is provided, no densification can be done for paths (polylines), and a default sample_count (100) is used for areas (polygons or envelopes).
mosaic_rule - Specifies the mosaic rule defining the image sort order.
Additional filtering can be applied to the where clause and FIDs of a mosaic rule.
pixel_size - The raster that is visible at the specified pixel size in the
mosaic dataset will be used for sampling. If pixel_size is not specified, the service’s pixel size is used. The structure of the esri_codephpixelSize parameter is the same as the structure of the point object returned by the ArcGIS REST API. In addition to the JSON structure, you can specify the pixel size with a simple comma-separated syntax.
return_first_value_only - Indicates whether to return all values at a point,
or return the first non-NoData value based on the current mosaic rule. The default is true.
interpolation - The resampling method. Default is nearest neighbor.
Values: RSP_BilinearInterpolation | RSP_CubicConvolution | RSP_Majority | RSP_NearestNeighbor
out_fields - The list of fields to be
included in the response. This list is a comma-delimited list of field names. You can also specify the wildcard character (*) as the value of this parameter to include all the field values in the results.
histograms

Returns the histograms of each band in the imagery layer as a list of dictionaries corresponding to each band. If not histograms is found, returns None. In this case, call the compute_histograms() :return:

my_hist = imagery_layer.histograms()

Structure of the return value: [

{ #band 1
“size”:256, “min”:560, “max”:24568, counts: [10,99,56,42200,125,….] #length of this list corresponds ‘size’

} { #band 3

“size”:256, #number of bins “min”:8000, “max”:15668, counts: [45,9,690,86580,857,….] #length of this list corresponds ‘size’

]

key_properties(rendering_rule=None)

returns key properties of the imagery layer, such as band properties :param rendering_rule: Specifies the rendering rule for how the requested image should be processed. The response contains updated service information that reflects a custom processing as defined

by the rendering rule. For example, if renderingRule contains an attributeTable function, the response will indicate “hasRasterAttributeTable”: true; if the renderingRule contains

functions that alter the number of bands, the response will indicate correct bandCount.
Returns:key properties of the imagery layer
last()

overlapping pixels at the same location are resolved by picking the last image :return: this imagery layer with mosaic operation set to ‘last’

max()

overlapping pixels at the same location are resolved by picking the max pixel value :return: this imagery layer with mosaic operation set to ‘max’

mean()

overlapping pixels at the same location are resolved by choosing the mean of all overlapping pixels :return: this imagery layer with mosaic operation set to ‘mean’

min()

overlapping pixels at the same location are resolved by picking the min pixel value :return: this imagery layer with mosaic operation set to ‘min’

mosaic_by(method=None, sort_by=None, sort_val=None, lock_rasters=None, viewpt=None, asc=True, where=None, fids=None, muldidef=None, op='first')

Defines how individual images in this layer should be mosaicked. It specifies selection, mosaic method, sort order, overlapping pixel resolution, etc. Mosaic rules are for mosaicking rasters in the mosaic dataset. A mosaic rule is used to define:

  • The selection of rasters that will participate in the mosaic (using where clause).
  • The mosaic method, e.g. how the selected rasters are ordered.
  • The mosaic operation, e.g. how overlapping pixels at the same location are resolved.
Parameters:
  • method – determines how the selected rasters are ordered. str, can be none | center | nadir | northwest | seamline | viewpoint | attribute | lock-raster required if method is: center | nadir | northwest | seamline, optional otherwise. If no method is passed “none” method is used, which uses the order of records to sort If sort_by and optionally sort_val parameters are specified, “attribute” method is used If lock_rasters are specified, “lock-raster” method is used If a viewpt parameter is passed, “viewpoint” method is used.
  • sort_by – optional str, field name when sorting by attributes
  • sort_val – optional, a constant value defining a reference or base value for the sort field when sorting by attributes
  • lock_rasters – optional, an array of raster Ids. All the rasters with the given list of raster Ids are selected to participate in the mosaic. The rasters will be visible at all pixel sizes regardless of the minimum and maximum pixel size range of the locked rasters.
  • viewpt – optional point, used as view point for viewpoint mosaicking method
  • asc – optional bool, indicate whether to use ascending or descending order. Default is ascending order.
  • where – optional str, where clause to define a subset of rasters used in the mosaic, be aware that the rasters may not be visible at all scales
  • fids – optional list of objectids, use the raster id list to define a subset of rasters used in the mosaic, be aware that the rasters may not be visible at all scales.
  • muldidef – optional dict, multidemensional definition used for filtering by variable/dimensions. See http://resources.arcgis.com/en/help/arcgis-rest-api/index.html#//02r300000290000000
  • op – optional string, first | last | min | max | mean | blend | sum mosaic operation to resolve overlap pixel values: from first or last raster, use the min, max or mean of the pixel values, or blend them.
Returns:

a mosaic rule defined in the format at http://resources.arcgis.com/en/help/arcgis-rest-api/#/Mosaic_rule_objects/02r3000000s4000000/

Also see http://desktop.arcgis.com/en/arcmap/latest/manage-data/raster-and-images/understanding-the-mosaicking-rules-for-a-mosaic-dataset.htm#ESRI_SECTION1_ABDC9F3F6F724A4F8079051565DC59E

mosaic_rule

The mosaic rule used by the imagery layer to define: * The selection of rasters that will participate in the mosaic * The mosaic method, e.g. how the selected rasters are ordered. * The mosaic operation, e.g. how overlapping pixels at the same location are resolved.

Set by calling the mosaic_by or filter_by methods on the layer

properties

The properties of this object

query(where=None, out_fields='*', time_filter=None, geometry_filter=None, return_geometry=True, return_ids_only=False, return_count_only=False, pixel_size=None, order_by_fields=None, return_distinct_values=None, out_statistics=None, group_by_fields_for_statistics=None, out_sr=None, return_all_records=False, object_ids=None, multi_dimensional_def=None, result_offset=None, result_record_count=None, max_allowable_offset=None, true_curves=False)

queries an imagery layer by applying the filter specified by the user. The result of this operation is either a set of features or an array of raster IDs (if return_ids_only is set to True), count (if return_count_only is set to True), or a set of field statistics (if out_statistics is used).

Inputs:
where - the selection sql statement. Any legal SQL where clause operating on the fields in the raster
catalog is allowed.

out_fields - the attribute fields to return, comma-delimited list of field names. time_filter - The time instant or the time extent of the exported image.

Time instant specified as datetime.date, datetime.datetime or timestamp in milliseconds since epoch Syntax: time_filter=<timeInstant>

Time extent specified as list of [<startTime>, <endTime>] For time extents one of <startTime> or <endTime> could be None. A None value specified for start time or end time will represent infinity for start or end time respectively. Syntax: time_filter=[<startTime>, <endTime>] ; specified as datetime.date, datetime.datetime or timestamp in milliseconds

geometry_filter - spatial filter from arcgis.geometry.filters module to filter results by a
spatial relationship with another geometry
return_geometry - true means a geometry will be returned,
else just the attributes
return_ids_only - false is default. True means only OBJECTIDs
will be returned
return_count_only - if True, then an integer is returned only
based on the sql statement
pixel_size-Query visible rasters at a given pixel size. If
pixel_size is not specified, rasters at all resolutions can be queried.
order_by_fields-Order results by one or more field names. Use
ASC or DESC for ascending or descending order, respectively
return_distinct_values- If true, returns distinct values
based on the fields specified in outFields. This parameter applies only if the supportsAdvancedQueries property of the image service is true.
out_statistics- the definitions for one or more field-based
statistics to be calculated.
group_by_fields_for_statistics-One or more field names using the
values that need to be grouped for calculating the statistics.
out_sr - if the returning geometry needs to be in a different
spatial reference, provide the function with the desired WKID.
return_all_records - boolean, if True(default) all records
will be returned. False means only the limit of records will be returned.
object_ids - The object IDs of this raster catalog to be
queried.When this parameter is specified, any other filter parameters (including where) are ignored. When this parameter is specified, setting returnIdsOnly=true is invalid. Syntax: objectIds=<objectId1>, <objectId2> Example: objectIds=37, 462
multi_dimensional_def- The filters defined by multiple
dimensional definitions.

result_offset - This option fetches query results by skipping a specified number of records. The query results start from the next record (i.e., resultOffset + 1). The Default value is None. result_record_count - This option fetches query results up to the resultRecordCount specified. When resultOffset is specified and this parameter is not, image service defaults to maxRecordCount. The maximum value for this parameter is the value of the layer’s maxRecordCount property. max_allowable_offset - This option can be used to specify the max_allowable_offset to be used for generalizing geometries returned by the query operation. The max_allowable_offset is in the units of the outSR. If outSR is not specified, max_allowable_offset is assumed to be in the unit of the spatial reference of the service. true_curves - If true, returns true curves in output geometres, otherwise curves get converted to densified polylines or polygons.

Output:
A FeatureSet containing the footprints (features) matching the query when return_geometry is True, else a dictionary containing the expected return type
save(output_name=None, for_viz=False, gis=None)

Persists this imagery layer to the GIS as an Imagery Layer item. If for_viz is True, a new Item is created that uses the applied raster functions for visualization at display resolution using on-the-fly image processing. If for_viz is False, distributed raster analysis is used for generating a new raster information product by applying raster functions at source resolution across the extent of the output imagery layer.

Parameters:
  • output_name – Optional. If not provided, an Imagery Layer item is created by the method and used as the output. You can pass in the name of the output Imagery Layer that should be created by this method to be used as the output for the tool. Alternatively, if for_viz is False, you can pass in an existing Image Service Item from your GIS to use that instead A RuntimeError is raised if a service by that name already exists
  • for_viz – If True, a new Item is created that uses the applied raster functions for visualization at display resolution using on-the-fly image processing. If for_viz is False, distributed raster analysis is used for generating a new raster information product for use in analysis and visualization by applying raster functions at source resolution across the extent of the output imagery layer.
  • gis – The GIS to be used for saving the output

:return : output_raster - Image layer item

set_filter(where=None, geometry=None, time=None, lock_rasters=False, clear_filters=False)

Filters the rasters that will be used for applying raster functions.

If lock_rasters is set True, the LockRaster mosaic rule will be applied to the layer, unless overridden

Parameters:
  • where – a where clause on this layer to filter the imagery layer by the selection sql statement. Any legal SQL where clause operating on the fields in the raster
  • geometry – spatial filter from arcgis.geometry.filters module to filter results by a spatial relationship with another geometry
  • time

    a temporal filter to this layer to filter the imagery layer by time using the specified time instant or the time extent. Time instant specified as datetime.date, datetime.datetime or timestamp in milliseconds since epoch Syntax: time_filter=<timeInstant>

    Time extent specified as list of [<startTime>, <endTime>] For time extents one of <startTime> or <endTime> could be None. A None value specified for start time or end time will represent infinity for start or end time respectively. Syntax: time_filter=[<startTime>, <endTime>] ; specified as datetime.date, datetime.datetime or timestamp in milliseconds

  • lock_rasters – if True, the LockRaster mosaic rule will be applied to the layer, unless overridden
  • clear_filters – if True, the applied filters are cleared
Returns:

sum()

overlapping pixels at the same location are resolved by adding up all overlapping pixel values :return: this imagery layer with mosaic operation set to ‘sum’