Movatterモバイル変換


[0]ホーム

URL:


Skip to content
Esri Developer

ArcGIS API for PythonAPI Reference

arcgis.raster module

Thearcgis.raster module contains classes and analysis functions for working with raster data andimagery layers.

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

Useis_supported() to check if raster analysis is supported in your GIS.

ImageryLayer

classarcgis.raster.ImageryLayer(url:str,gis:GIS|None=None,parent_url=None)

TheImageryLayer class can be used to represent an image service resource as a layer.

AnImageryLayer object retrieves and displays data from image services.ImageryLayerallows you to apply server-defined or client-defined raster functions (e.g. remap, colormap), and mosaic rules.

ImageryLayer objects can also be created using raster datasets or raster products present in datastores registered with the server/active GIS(types:fileShares,cloudStores,rasterStores).To learn more about datastores, visit theWhat is ArcGIS Data Store?page in the ArcGIS Enterprise documentation.

Usage:arcgis.raster.ImageryLayer(url,gis=gis)

Parameter

Description

url

Required string. The input raster path

Example:

url = “https://myserver/arcgis/rest/services/ImageServiceName/ImageServer

url = “/fileShares/file_share_name/path/to/raster”

url = “/cloudStores/cloud_store_name/path/to/raster”

url = “https://sentinel-cogs.s3.us-west-2.amazonaws.com/sentinel-s2-l2a-cogs/43/M/BP/2021/6/S2A_43MBP_20210622_0_L2A/B08.tif

Note

When working with datastore rasters or non image service urls,RasterRendering serviceshould be enabled in the active GIS connection

gis

Optional GIS.GIS of the ImageryLayer object.

# Example Usage# Imagery layer items are available as content in the GIS. Items can be searched using gis.content.search()# This snippet creates an imagery layer using the 'layers' property of the searched Imagery Layer Itemimg_lyr=gis.content.search("my_image_service",item_type="Imagery Layer")[0].layers[0]# Create an imagery layer from an image service urlimg_lyr=ImageryLayer("https://myserver/arcgis/rest/services/ImageServiceName/ImageServer",gis=gis)# Create an imagery layer from a .tif file present in user's registered fileShare datastore# (Requires RasterRendering service to be enabled in the active GIS)img_lyr=ImageryLayer("/fileShares/data/Amberg.tif",gis=gis)# Create an imagery layer from a publicly accesible Cloud-Optimized GeoTIFF# (Requires RasterRendering service to be enabled in the active GIS)img_lyr=ImageryLayer("https://sentinel-cogs.s3.us-west-2.amazonaws.com/sentinel-s2-l2a-cogs/43/M/BP/2021/6/S2A_43MBP_20210622_0_L2A/B08.tif",gis=gis)# Overlay an imagery layer on the 'Map' widgetmap=gis.map()map.content.add(img_lyr)
attribute_table(rendering_rule:str|None=None,as_df:bool=False)

Theattribute_table method returns categorical mapping of pixelvalues (for example, aclass,group,category, ormembership).

Parameter

Description

rendering_rule

Specifies the rendering rule for how the requested image should beprocessed.

Note

The response is updated Layer info that reflects acustom processing as defined by the rendering rule. For example, ifrenderingRule contains an attributeTable function, the responsewill indicate “hasRasterAttributeTable”: true; if the renderingRulecontains functions that alter the number of bands, the response willindicate a correct bandCount value.

Returns:

A dictionary

propertyband_count

Get the band count of theImageryLayer.

Returns:

An Integer

blend()

Theblend method returns thisImageryLayer with mosaic operation set toblend (overlappingpixels at the same location are resolved by blending all overlapping pixels)

Returns:

AnImageryLayer object

propertycache_manager

Thecache_manager property provides access to the tools to update, add, and remove cache on theImageryLayer object.

Returns:

ImageryLayerCacheManager or None

calculate_volume(geometries:list[Polygon]|list[Envelope],base_type:int|None=None,mosaic_rule:dict[str,Any]|None=None,constant_z:int|None=None,pixel_size:str|dict[str,float]|None=None)

Thecalculate_volume method performs volumetric calculation on an elevation service.

Note

  • If a service does not have vertical spatial reference and z unit is not in meters, user needs to apply a conversion factor when interpreting results. The results are always in square meters (area) and cubic meters (volume).

  • Thecalculate_volume method is only available in 10.7+.

Parameter

Description

geometries

A required list ofPolygon geometry objects or alist ofEnvelope geometry objects.A geometry that defines the geometrywithin which the volume is computed.

base_type

Optional integer.0 - constant z;1 - best fitting plane;2 - lowest elevation on the perimeter;3 - highest elevation on the perimeter;4 - average elevation on the perimeter

mosaic_rule

Optional dictionary. Used to select different DEMs in a mosaic dataset

constant_z

Optional integer. parameter to specify constant z value

pixel_size

Optional string or dictionary. Defines the spatial resolution at which volume calculation is performedSyntax:

  • dictionary structure: pixel_size={point}

  • Point simple syntax: pixel_size=’<x>,<y>’

Examples:
  • pixel_size={“x”: 0.18, “y”: 0.18}

  • pixel_size=’0.18,0.18’

Returns:

A dictionary showing volume values for each geometry in the input geometries array

catalog_item(id:int)

Thecatalog_item method returns a single raster catalog item associated with the specified ID

Parameter

Description

id

Required integer. The ‘raster ID’.

Returns:

RasterCatalogItem associated with the ID

colormap(rendering_rule:dict[str,Any]|None=None,variable:str|None=None)

Thecolormap method returns RGB color representation of pixelvalues.

Note

This method is supported if thehasColormap property of the layer isTrue.

Parameter

Description

rendering_rule

Optional dictionary. Specifies the rendering rule for how therequested image should be rendered.See theRaster function objectspage in the ArcGIS REST API documentation for JSON syntax and examples.

variable

Optional string. This parameter can be used to request acolormap for each variable for an image service that hasmultidimensional information. It will return a colormapfor the whole image service if not specified. Eligible variable namescan be queried frommultidimensional_info property of theImageryLayer object.

Note

This parameter is available from 10.8.1 onwards.

Returns:

A dictionary

propertycolumns

Get the number of columns in theImageryLayer.

Returns:

An Integer

compute_angles(raster_id:int,point:dict|Point|None=None,angle_name:str|None=None,spatial_reference:dict|None=None)

Thecompute_angles method computes the rotation angle of a raster for a user-specifiedangle direction, and optionally, a user-specified rotation point and user-specifiedspatial reference.

Parameter

Description

raster_id

Required integer. Specifies the object ID of the raster catalog whichwill determine the raster and image coordinate system to use in amosaic dataset.

point

Optional dictionary orPoint object.The point geometry that defines the reference point of rotation tocompute the angle direction. By default, takes the centroid of imageas point of rotation.

angle_name

Optional string. Specifies the name (or names) of the rotationangle to be computed.

Possible options are:

  • “up”: The computed angle after rotating the map so the top of the image is always oriented to the direction of the sensor when it acquired the image.

  • “north”: The computed angle after rotating so the top of the image is always toward north.

You can specify multiple angle names by separating the names with acomma. By default, angles are computed for all directions.

spatial_reference

Optional dictionary. Specifies the spatial reference to be used bythe image. By default, the spatial reference of the image is used.

Returns:

A dictionary with the computed rotation angle of a raster.

# Example Usage: Compute angles for a given point and rotation angle.my_point={"x":7952916.33,"y":3869525.96,"spatialReference":{"wkid":3857}}my_point_object=Point(my_point)compute_angles_op=img_lyr.compute_angles(raster_id=1,point=my_point_object,angle_name="north",spatial_reference={"wkid":54004})
compute_cache_info(out_sr:int|None=None)

Thecompute_cache_info method computes and generates new image service tile cacheschemes for image services.If the corresponding image tile cache scheme is missing, it will also create a new set ofcached image tiles in the cache directory of the image service. This operation onlygenerates image tile cache schemes based on raster tiles (LERC2D format).

Note

This applies to image services that have dynamic service caching capability enabled.

Parameter

Description

out_sr

Optional integer. The spatial reference of the boundary’s geometry.The spatial reference can be specified as a well-known ID.If theout_sr is not specified, it will use the spatialreference of the image service.

Returns:

A dictionary with the image tile cache scheme information.

# Example Usage: Compute the cache info for a given spatial reference.cache_info_op=img_lyr.compute_cache_info(out_sr=3857)
compute_class_stats(descriptions:dict[str,Any],mosaic_rule:str='defaultMosaicMethod',rendering_rule:dict[str,str]|None=None,pixel_size:str|dict[str,float]|None=None)

Thecompute_class_stats method computes the class statistics signatures (used by the maximum likelihoodclassifier)

Parameter

Description

descriptions

Required dict. Class descriptions are training site polygons andtheir class descriptions. The structure of the geometry is the sameas the structure of the JSON geometry objects returned by theArcGIS REST API.

Syntax:

{
“classes”: [ // A list of classes
{
“id” : <id>,
“name” : “<name>”,
“geometry” : <geometry> //polygon
},
{
“id” : <id>,
“name” : “<name>”,
“geometry” : <geometry> //polygon
}
]
}

mosaic_rule

Optional string. Specifies the mosaic rule when defining howindividual images should be mosaicked. When a mosaic rule is notspecified, the default mosaic rule of the image layer will be used(as advertised in the root resource:defaultMosaicMethod,mosaicOperator,sortField,sortValue).See theMosaic rule objectshelp for more information.

rendering_rule

Optional dictionary. Specifies the rendering rule for how therequested image should be rendered.See theraster function objectspage in the ArcGIS REST API documentation for JSON syntax and examples.

pixel_size

Optional string or dictionary. The pixel level being used (or theresolution being looked at). If pixel size is not specified, thenpixel_size will default to the base resolution of the dataset.The structure of the pixel_size parameter is the same as thestructure of the point object returned by the ArcGIS REST API.In addition to the dictionary structure, you can specify the pixel sizewith a comma-separated syntax.

Syntax:
  • dictionary structure: pixel_size={point}

  • Point simple syntax: pixel_size=’<x>,<y>’

Examples:
  • pixel_size={“x”: 0.18, “y”: 0.18}

  • pixel_size=’0.18,0.18’

Returns:

A dictionary

# Example Usageimg_lyr=gis.content.search("my_image_service",item_type="Imagery Layer")[0].layers[0]stats=img_lyr.compute_class_stats(descriptions={"classes":[{"id":<id1>,"name":"<name1>","geometry":<polygon1>},{"id":<id2>,"name":"<name2>","geometry":<polygon2>}]},pixel_size={"x":0.18,"y":0.18})
compute_histograms(geometry:Geometry|Polygon|Envelope,mosaic_rule:str|None=None,rendering_rule:dict[str,Any]|None=None,pixel_size:str|dict[str,float]|None=None,time:str|list[int]|date|datetime|None=None,process_as_multidimensional:bool=False)

Thecompute_histograms method returns a list of histograms for all raster bands computed for theImageryLayer from the given extent.

Parameter

Description

geometry

RequiredGeometry (PolygonorEnvelope).A geometry that defines the geometry within which the histogram is computed.

mosaic_rule

Optional string. Specifies the mosaic rule when defining howindividual images should be mosaicked. When a mosaic rule is notspecified, the default mosaic rule of the image layer will be used(as advertised in the root resource: defaultMosaicMethod,mosaicOperator, sortField, sortValue).See theMosaic rule objectshelp for more information.

rendering_rule

Optional rule. Specifies the rendering rule for how the requested imageshould be processed. The response is updated Layer info that reflects acustom processing as defined by the rendering rule. For example, ifrenderingRule contains an attributeTable function, the responsewill indicate “hasRasterAttributeTable”: true; if the renderingRulecontains functions that alter the number of bands, the response willindicate a correct bandCount value.

pixel_size

Optional string or dictionary. The pixel level being used (or theresolution being looked at). If pixel size is not specified, thenpixel_size will default to the base resolution of the dataset.The structure of the pixel_size parameter is the same as thestructure of the point object returned by the ArcGIS REST API.In addition to the dictionary structure, you can specify the pixel sizewith a comma-separated string.

Syntax:
  • dictionary structure: pixel_size={point}

  • Point simple syntax: pixel_size=’<x>,<y>’

Examples:
  • pixel_size={“x”: 0.18, “y”: 0.18}

  • pixel_size=’0.18,0.18’

time

Optional datetime.date, datetime.datetime or timestamp string. Thetime instant or the time extent to compute the histogram.Time instant specified as datetime.date, datetime.datetime ortimestamp in milliseconds since epochSyntax: time=<timeInstant>

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

Note

This parameter was added at 10.8.

process_as_multidimensional

Optional boolean. Specifies whether to process the image service as amultidimensional image service.

  • False - The histogram of pixel values from only the first slice is computed. This is the default.

  • True - The image service is treated as a multidimensional raster, and histograms of pixel values from all selected slices are computed.

Note

Added at 10.9 for image services which useArcObjects11 orArcObjectsRasterRenderingas the service provider.

Returns:

A dictionary

# Usage Example 1: Compute the histograms in the specified area of interest for a time instant.aoi={"spatialReference":{"wkid":32610},"xmax":725000,"xmin":720000,"ymax":4300000,"ymin":4250000}aoi_geometry=Geometry(aoi)comp_hist_01=img_lyr.compute_histograms(geometry=aoi,rendering_rule={"rasterFunction":None},time="1326650400000")
# Usage Example 2: Compute the histograms in the specified area of interest for a time extent.aoi={"spatialReference":{"wkid":32610},"xmax":725000,"xmin":720000,"ymax":4300000,"ymin":4250000}aoi_geometry=Geometry(aoi)# If the datetime object is not in the UTC timezone, the API will internally convert it to the UTC timezone.start=datetime.datetime(2012,1,15,18,0,0,tzinfo=datetime.timezone.utc)end=datetime.datetime(2012,1,15,21,0,0,tzinfo=datetime.timezone.utc)comp_hist_02=img_lyr.compute_histograms(geometry=aoi,rendering_rule={"rasterFunction":None},time=[start,end])
compute_pixel_location(raster_id:int,geometries:list[Geometry],spatial_reference:str|dict[str,Any]|SpatialReference)

Thecompute_pixel_location method calculates pixel locationin column and row on specific raster catalog item based on given input geometry.

Note

A prerequisite is that the raster catalog item has validicsToPixel resource.

Parameter

Description

raster_id

Required integer. Specifies the objectId of image service’s rastercatalog. This integer rasterId number will determine which raster’simage coordinate system will be used during the calculation andwhich raster does the column and row of results represent.

geometries

Required list of geometries for computing pixel locations.All geometries in this list should be of the type defined bygeometryType.

spatial_reference

Required string, dictionary,This specifies the spatial reference of the Geometries parameter above.It can accept a multitudes of values. These can be a WKID,image coordinate system (ICSID), or image coordinate system in json/dict format.Additionally theSpatialReference object is also avalid entry.

Note

An image coordinate system ID can be specifiedusing 0:icsid; for example, 0:64. The extra 0: is used to avoidconflicts with wkid

Returns:

A dictionary. The result of this operation includes x and y values for the columnand row of each input geometry. It also includes a z value for the height at givenlocation based on elevation info that the catalog raster item has.

compute_stats_and_histograms(geometry:Geometry|Polygon|Envelope,mosaic_rule:dict[str,str]|None=None,rendering_rule:dict[str,str]|None=None,pixel_size:str|dict[str,float]|None=None,time:str|list[int]|date|datetime|None=None,process_as_multidimensional:bool=False)

Thecompute_stats_and_histograms method computes both statistics and histograms for theImageryLayer object from the given extent.

Parameter

Description

geometry

RequiredGeometry (PolygonorEnvelope).A geometry that defines the geometry within which the statistics and histograms are computed.

mosaic_rule

Optional dictionary. Specifies the mosaic rule when defining howindividual images should be mosaicked. When a mosaic rule is notspecified, the default mosaic rule of the image layer will be used(as advertised in the root resource: defaultMosaicMethod,mosaicOperator, sortField, sortValue).

rendering_rule

Optional dictionary. Specifies the rendering rule for how therequested image should be rendered.

pixel_size

Optional string or dict. The pixel level being used (or theresolution being looked at). If pixel size is not specified, thenpixel_size will default to the base resolution of the dataset. Theraster at the specified pixel size in the mosaic dataset will beused for histogram calculation.

Syntax:
  • dictionary structure: pixel_size={point}

  • Point simple syntax: pixel_size=’<x>,<y>’

Examples:
  • pixel_size={“x”: 0.18, “y”: 0.18}

  • pixel_size=’0.18,0.18’

time

Optional datetime.date, datetime.datetime or timestamp string. Thetime instant or the time extent to compute statistics and histograms.Time instant specified as datetime.date, datetime.datetime ortimestamp in milliseconds since epochSyntax: time=<timeInstant>

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

Note

The parameter was added at 10.8.

process_as_multidimensional

Optional boolean. Specifies whether to process the image service asa multidimensional image service.

  • False - Statistics and histograms of pixel values from only the first slice is computed. This is the default.

  • True - The image service is treated as a multidimensional raster, and statistics and histograms of pixel values from all selected slices are computed.

Note

Added at 10.9 for image services which useArcObjects11 orArcObjectsRasterRenderingas the service provider.

Returns:

dictionary

# Usage Example 1: Compute the stats and histograms in the specified area of interest for a time instant.aoi={"spatialReference":{"wkid":32610},"xmax":725000,"xmin":720000,"ymax":4300000,"ymin":4250000}aoi_geometry=Geometry(aoi)comp_stats_hist_01=img_lyr.compute_stats_and_histograms(geometry=aoi,rendering_rule={"rasterFunction":None},time="1326650400000")
# Usage Example 2: Compute the stats and histograms in the specified area of interest for a time extent.aoi={"spatialReference":{"wkid":32610},"xmax":725000,"xmin":720000,"ymax":4300000,"ymin":4250000}aoi_geometry=Geometry(aoi)# If the datetime object is not in the UTC timezone, the API will internally convert it to the UTC timezone.start=datetime.datetime(2012,1,15,18,0,0,tzinfo=datetime.timezone.utc)end=datetime.datetime(2012,1,15,21,0,0,tzinfo=datetime.timezone.utc)comp_stats_hist_02=img_lyr.compute_stats_and_histograms(geometry=aoi,rendering_rule={"rasterFunction":None},time=[start,end])
compute_tie_points(raster_id:int,geodata_transforms:dict[str,Any])

Thecompute_tie_points method retrieves tie points that can be usedto match the source image to the reference image. The referenceimage is configured by the image layer publisher.

Note

For more information, seeFundamentals for georeferencing a raster dataset.

Parameter

Description

raster_id

Required integer. Source raster ID.

geodata_transforms

Required dictionary. The geodata transformation that provides arough fit of the source image to the reference image.For example, afirst order polynomial transformation that fits the source image tothe expected location.

Returns:

dictionary

dimension_profile(points:list[Point],dimension:str,time:datetime,variables:list[str]=[],show_values:bool=False,show_trend_line:bool=False,plot_properties:dict[str,Any]={})

Dimension profile chart visualizes change along a vertical dimension, such as depth or height,using a multidimensional raster dataset with a z-dimension.Dimension Profile is only available for multidimensional datasets that contain a z-dimension.

Change is plotted in the form of a line graph for a given location and date or time. This allowstrends in two variables to be displayed and compared simultaneously, while taking into accountdifferent unit scales.

The x-axis of the dimension profile displays the values of the variable. Default minimum andmaximum x-axis bounds are set based on the range of data values represented on the axis.

The y-axis of the dimension profile displays the vertical dimension value.

Parameter

Description

points

Required list ofPoint objects.

dimension

Required string. The dimension name that will be used for plotting dimension profile. Use this parameter to set the field thatrepresents the dimension field in the image service.

time

Required datetime object or timestamp in milliseconds. The time slice that will be used for plotting dimension profile.

variables

Required list of strings. The variables that will be used for plotting dimension profile.The dimension profile chart allows a maximum of two variables to be displayed.

show_values

Optional boolean. Default value is False.Set this parameter to True to display the values at each point in the line graph.

show_trend_line

Optional boolean. Default value is False.Set this parameter to True to add a linear trend line to the dimension profile chart.One trend line will be drawn for each location when charting multiple locations,or each variable when charting multiple variables.

plot_properties

Optional dictionary. This parameter can be used to set the figureproperties. These are thematplotlib.pyplot.figure()parameters and values specified in dictionary format.

eg: {“figsize”:(15,15)}

Returns:

None

draw_graph(show_attributes:bool=False,graph_size:str='14.25,15.25')

Thedraw_graph method displays a structural representation of the function chain and it’sraster input values. Ifshow_attributes is set toTrue, then thedraw_graph method alsodisplays the attributesof all the functions in the function chain, representing the rasters in a blue rectangularbox, attributes in green rectangular box and the raster function names in yellow.

Parameter

Description

show_attributes

Optional boolean. IfTrue, the graph displayed includes all theattributes of the function and not only it’s function name and rasterinputsSet to False by default, to display only the raster function name andthe raster inputs to it.

graph_size

Optional string. Maximum width and height of drawing, in inches,seperated by a comma. If only a single number is given, this is usedfor both the width and the height. If defined and the drawing islarger than the given size, the drawing is uniformly scaled down sothat it fits within the given size.

Returns:

A Graph

# Usage Example: Draws the function chain applied on the ImageryLayer object created from an Image service.imagery_layer=ImageryLayer("https://myserver/arcgis/rest/services/ImageServiceName/ImageServer",gis=gis)grayscale_layer=grayscale(raster=imagery_layer)invert_layer=boolean_not(rasters=[grayscale_layer])invert_layer.draw_graph(show_attributes=True)
export_image(bbox:str|dict[str,float]|None=None,image_sr:int|dict[str,Any]|SpatialReference|None=None,bbox_sr:int|dict[str,Any]|SpatialReference|None=None,size:list[int]|None=None,time:str|list[int]|date|datetime|None=None,export_format:str='jpgpng',pixel_type:str|None=None,no_data:float|None=None,no_data_interpretation:str='esriNoDataMatchAny',interpolation:str|None=None,compression:str|None=None,compression_quality:int|None=None,band_ids:list[int]|None=None,mosaic_rule:dict[str,Any]|None=None,rendering_rule:dict[str,Any]|None=None,f:str='json',save_folder:str|None=None,save_file:str|None=None,compression_tolerance:float|None=None,adjust_aspect_ratio:bool|None=None,lerc_version:int|None=None,slice_id:int|None=None)

Theexport_image operation is performed on anImageryLayer object.The result of this operation is an image method. This methodprovides information about the exported image, such as its URL,extent, width, and height.

Note

In addition to the usual response formats of HTML and JSON, you canalso request the image format while performing this operation. Whenyou perform an export with the image format , the server respondsby directly streaming the image bytes to the client. With thisapproach, you don’t get any information associated with theexported image other than the image itself.

Parameter

Description

bbox

Optional dict or string. The extent (bounding box) of the exportedimage. Unless the bbox_sr parameter has been specified, the bbox isassumed 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 thisformat: ‘<xmin>, <ymin>, <xmax>, <ymax>’If omitted, the extent of the imagery layer is used

image_sr

Optional string,SpatialReference.The spatial reference of theexported image. The spatial reference can be specified as either awell-known ID, it’s json representation or as anSpatialReference object.If theimage_sr is not specified, the image will be exported in thespatial reference of the imagery layer.

bbox_sr

Optional string, SpatialReference. The spatial reference of thebbox.The spatial reference can be specified as either a well-known ID,it’s json representation or as an arcgis.geometry.SpatialReferenceobject.If the image_sr is not specified, bbox is assumed to be in thespatial reference of the imagery layer.

size

Optional list. The size (width * height) of the exported image inpixels. If size is not specified, an image with a default size of1200*450 will be exported.Syntax: list of [width, height]

time

Optional datetime.date, datetime.datetime or timestamp string. Thetime instant or the time extent of the exported image.Time instant specified as datetime.date, datetime.datetime ortimestamp in milliseconds since epochSyntax: time=<timeInstant>

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

export_format

Optional string. The format of the exported image. The defaultformat is jpgpng. The jpgpng format returns a JPG if there are notransparent pixels in the requested extent; otherwise, it returns aPNG (png32).

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

pixel_type

Optional string. The pixel type, also known as data type, pertainsto 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

Optional float. The pixel value representing no information.

no_data_interpretation

Optional string. Interpretation of the no_data setting. The defaultis NoDataMatchAny when no_data is a number, and NoDataMatchAll whenno_data is a comma-delimited string: NoDataMatchAny,NoDataMatchAll.

interpolation

Optional string. The resampling process of extrapolating the pixelvalues while transforming the raster dataset when it undergoeswarping or when it changes coordinate space.One of: RSP_BilinearInterpolation, RSP_CubicConvolution,RSP_Majority, RSP_NearestNeighbor

compression

Optional string. Controls how to compress the image when exportingto TIFF format: None, JPEG, LZ77. It does not control compression onother formats.

compression_quality

Optional integer. Controls how much loss the image will be subjectedto by the compression algorithm. Valid value ranges of compressionquality are from 0 to 100.

band_ids

Optional list. If there are multiple bands, you can specify a singleband 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

Optional dict. Specifies the mosaic rule when defining howindividual images should be mosaicked. When a mosaic rule is notspecified, the default mosaic rule of the image layer will be used(as advertised in the root resource: defaultMosaicMethod,mosaicOperator, sortField, sortValue).

rendering_rule

Optional dict. Specifies the rendering rule for how the requestedimage should be rendered.

f

Optional string. The response format. default is jsonValues: json,image,kmz,numpy_array

Note: If f=”numpy_array” and if the raster is a single or multiband raster,the dimensions of the array will be rows, columns, and number of bands.If the raster is a multidimensional raster, the dimensions of the arraywill be number of slices, rows, columns, and number of bands.LERC needs to be installed to export image service as numpy array.

If f=”image”, the bytes of the exported image arereturned unless save_folder and save_file parameters are alsopassed, in which case the image is written to the specified file

save_folder

Optional string. The folder in which the exported image is savedwhen f=image

save_file

Optional string. The file in which the exported image is saved whenf=image

compression_tolerance

Optional float. Controls the tolerance of the lerc compressionalgorithm. The tolerance defines the maximum possible error of pixelvalues in the compressed image.Example: compression_tolerance=0.5 is loseless for 8 and 16 bitimages, but has an accuracy of +-0.5 for floating point data. Thecompression tolerance works for the LERC format only.

adjust_aspect_ratio

Optional boolean. Indicates whether to adjust the aspect ratio ornot. By default adjust_aspect_ratio is true, that means the actualbbox will be adjusted to match the width/height ratio of sizeparamter, and the response image has square pixels.

lerc_version

Optional integer. The version of the Lerc format if the user setsthe format as lerc.Values: 1 or 2If a version is specified, the server returns the matching version,or otherwise the highest version available.

slice_id

Optional integer. Exports the given slice of a multidimensional raster.To get the slice index use slices method on the ImageryLayer object.

Returns:

Dictionary of the data that is exported or a string indicating the file path.

# Usage Example: Exports an ImageryLayer object (created using Image Service) to a local location in tiff formatimagery_layer=ImageryLayer("https://myserver/arcgis/rest/services/ImageServiceName/ImageServer",gis=gis)imagery_layer.export_image(size=[1400,600],export_format="tiff",f="image",save_folder=r"/path/to/save_folder",save_file="my_raster.tif")
propertyextent

Get/Set the area of interest.Used for displaying theImageryLayer when queried.

Returns:

A dictionary

filter_by(where:str|None=None,geometry:dict|None=None,time:str|list[int]|date|datetime|None=None,lock_rasters:bool=True)

Thefilter_by method filters the layer by where clause, geometry and temporal filters.

Parameter

Description

where

Optional string. A where clause on this layer to filter the imagerylayer by the selection sql statement. Any legal SQL where clauseoperating on the fields in the raster

geometry

Optional arcgis.geometry.filters. To filter results by a spatialrelationship with another geometry

time

Optional datetime, date, or timestamp. A temporal filter to thislayer to filter the imagery layer by time using the specified timeinstant or the time extent.

Syntax: time_filter=<timeInstant>

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

lock_rasters

Optional boolean. If True, the LockRaster mosaic rule will beapplied to the layer, unless overridden

Returns:

ImageryLayer with filtered images meeting the filter criteria

# Example Usageimg_lyr=gis.content.search("my_image_service",item_type="Imagery Layer")[0].layers[0]filtered_img_lyr=img_lyr.filter_by(time=[1627417239146],lock_rasters=True)
filtered_rasters()

Thefiltered_rasters method retrieves object ids of the filtered rasters in thisImageryLayer, by applying the where clause, spatial andtemporal filters.

Returns:

A list of object ids. If no rasters are filtered, returns None.If all rasters are filtered, returns empty list.

find_images(from_geometry:dict[str,Any]|Point=None,to_geometry:dict[str,Any]|Point=None,in_sr:dict|None=None,object_ids:list|None=None,where:str|None=None,max_count:int|None=None)

The function locates all images that contain to_geometry and sort themaccordingly. For example, in the image inspection workflow, in most cases,from_geometry is the viewing camera position, andto_geometry is the targetpoint (where user clicked on the map). The images found are sorted inascending order based on the angle between the vector from viewing cameraposition to target point, and that from the image camera GPS location tothe target point, plus distance between the image center and the targetpoint.

Note

Thefind_images operation is supported at 11.2 and later.

Parameter

Description

from_geometry

Required dictionary orPoint object.A point geometry that defines the from location.

to_geometry

Required dictionary orPoint object.A point geometry that defines the to location.

in_sr

Optional integer, string, dictionary,SpatialReference.If in_sr is not specified, the geometry is assumed to be in the spatial reference of the service.

object_ids

Optional list or string. The object IDs of this raster catalog to bequeried. When this parameter is specified, any other filterparameters (including where) are ignored.

Syntax: object_ids=”<objectId1>, <objectId2>” or [<objectId1>, <objectId2>]Example: object_ids=”37, 462” or object_ids = [37, 462]

where

Optional string. A where clause on this layer to filter the imagerylayer by the selection sql statement.Any legal SQL where clause operating on the fields in theraster catalog is allowed.

Example: where=”OBJECTID>2”

max_count

Optional integer. The maximum number of results to be returned bythis operation.

Example: max_count=10

Returns:

A dictionary containing the information of all images that can see the view point andare ordered based on the distance from the view point to the center of each image.

first()

Thefirst method returns thisImageryLayer with mosaic operation set tofirst (overlappingpixels at the same location are resolved by picking the first image)

Returns:

AnImageryLayer object

classmethodfromitem(item:Item)

Thefromitem method creates an Image Layer from a GISItem.

Returns:

AnImageryLayer object

get_download_info(raster_ids:str,polygon:Polygon|None=None,extent:str|None=None,out_format:str|None=None)

Theget_download_info method returns information (the file ID)that can be used to download the raw raster files that areassociated with a specified set of rasters in the raster catalog.

Parameter

Description

raster_ids

Required string. A comma-separated list of raster IDs whose filesare to be downloaded.

polygon

OptionalPolygon object. The geometry to apply for clipping

extent

Optional string. The geometry to apply for clippingexample: “-104,35.6,-94.32,41”

out_format

Optional string. The format of the rasters returned. If notspecified, the rasters will be in their native format.The format applies when the clip geometry is also specified, and theformat will be honored only when the raster is clipped.

To force the Download Rasters operation to convert source images toa different format, append :Conversion after format string.Valid formats include: TIFF, Imagine Image, JPEG, BIL, BSQ, BIP,ENVI, JP2, GIF, BMP, and PNG.Example: out_format=’TIFF’

Returns:

A dictionary

get_histograms(variable:str|None=None,rendering_rule:dict|None=None)

Theget_histograms method retrieves the histograms of each band in theImageryLayeras a list of dictionaries corresponding to each band.

Note

  • get_histograms can return a histogram for each variable if used with multidimensional ImageryLayer object by specifying value for variable parameter.

  • If histogram is not found, returns None. In this case, call thecompute_histograms method.

  • get_histograms is an enhanced version of thehistograms property on theImageryLayer class with additional variable parameter.

Parameter

Description

variable

Optional string. For an image service that has multidimensionalinformation, this parameter can be used to request histograms foreach variable. It will return histograms for the whole ImageryLayerif not specified.This parameter is available from 10.8.1

rendering_rule

Optional dictionary. Specifies the rendering rule for how the requested image should be rendered.

In the context of accessing image service histograms resource,this parameter is used to retrieve histograms info in attachedpredefined raster function templates (inside a StatisticsHistogram function).

This parameter is available from 10.9.1

Returns:

A list

Example Structure of the return value:

[{“size”:256,
“min”:560,
“max”:24568,
“counts”: [10,99,56,42200,125,….]}] # length of this list corresponds “size”
# Example Usagemy_hist=imagery_layer.get_histograms(variable="water_temp")
get_image_url(image_uri:str,raster_id:int)

Returns an accessible url to the image.

Note

Theget_image_url operation is supported at 11.2 and later.

Parameter

Description

image_uri

Required string. URI of the image to be accessed. The find_images operation returns the image_uri.

raster_id

Required integer. Specifies the objectId of the image service’s raster catalog.The url will be returned only if it belongs to theraster_id specified.

Returns:

A string representing the accessible url to the image.

# Example Usageimg_layer=gis.content.search("my_image_service",item_type="Imagery Layer")[0].layers[0]op=img_layer.get_image_url(image_uri="/vsis3/t-agu/Hosted_om20230601105400/data/YUN_0040.JPG",raster_id=1)
get_raster_file(download_info:dict[str,Any],out_folder:str|None=None)

Theget_raster_file method returns a list of raw raster files. Thedownload_info is obtained by using theget_download_info operation.

Parameter

Description

download_info

Required dictionary. This is derived from theget_download_info method.

out_folder

Optional string. Path to the file save location. If the value isNone, the OS temporary directory is used.

Returns:

A list of the files downloaded

get_samples(geometry:Geometry|Point|MultiPoint|Polyline|Polygon|Envelope,geometry_type:str|None=None,sample_distance:float|None=None,sample_count:int|None=None,mosaic_rule:dict[str,str]|None=None,pixel_size:str|dict[str,float]|None=None,return_first_value_only:bool|None=None,interpolation:str|None=None,out_fields:str|None=None,slice_id:int|None=None,time:str|list[date]|list[datetime]|date|datetime|None=None)

Theget_samples operation is supported by both mosaic dataset and rasterdataset imagery layers.The result of this operation includes sample point locations, pixelvalues, and corresponding spatial resolutions of the source data for agiven geometry.

Note

  • When the input geometry is aPolyline,Envelope, orPolygon, sampling is based onsample_count orsample_distance; when the input geometry is aPoint orMultiPoint, the point or points are used directly.

  • The number of sample locations in the response is based on thesample_distance orsample_count parameter and cannot exceed the limit of the image layer (the default is 1000, which is an approximate limit).

Parameter

Description

geometry

RequiredGeometry object that defines the location(s)to be sampled. The structure of the geometry is the same as the structure ofthe JSON geometry objects returned by the ArcGIS REST API. Applicable geometrytypes arepoint,multipoint,polyline,polygon, andenvelope. Whenspatial reference is omitted in the input geometry, it will be assumedto be the spatial reference of the image layer.

geometry_type

Optional string. The type of geometry specified by the geometryparameter.Applicable geometrytypes arepoint,multipoint,polyline,polygon, andenvelope.

sample_distance

Optional float. The distance interval used to sample points fromthe provided path. The unit is the same as the input geometry. Ifneither sample_count nor sample_distance is provided, nodensification can be done for paths (polylines), and a defaultsample_count (100) is used for areas (polygons or envelopes).

sample_count

Optional integer. The approximate number of sample locations fromthe provided path. If neither sample_count nor sample_distance isprovided, no densification can be done for paths (polylines), and adefault sample_count (100) is used for areas (polygons or envelopes).

mosaic_rule

Optional dictionary. Specifies the mosaic rule when defining howindividual images should be mosaicked. When a mosaic rule is notspecified, the default mosaic rule of the image layer will be used(as advertised in the root resource: defaultMosaicMethod,mosaicOperator, sortField, sortValue).

pixel_size

Optional string or dict. The pixel level being used (or theresolution being looked at). If pixel size is not specified, thenpixel_size will default to the base resolution of the dataset. Theraster at the specified pixel size in the mosaic dataset will beused for histogram calculation.

Syntax:
  • dictionary structure: pixel_size={point}

  • Point simple syntax: pixel_size=’<x>,<y>’

Examples:
  • pixel_size={“x”: 0.18, “y”: 0.18}

  • pixel_size=’0.18,0.18’

return_first_value_only

Optional boolean. Indicates whether to return all values at apoint, or return the first non-NoData value based on the currentmosaic rule.The default is true.

interpolation

Optional string. The resampling method. Default is nearest neighbor.Values: RSP_BilinearInterpolation, RSP_CubicConvolution, RSP_Majority,RSP_NearestNeighbor

out_fields

Optional string. The list of fields to be included in the response.This list is a comma-delimited list of field names. You can alsospecify the wildcard character (*) as the value of this parameter toinclude all the field values in the results.

slice_id

Optional integer. The slice ID of a multidimensional raster. The operationwill be performed for the specified slice.This parameter is available from 10.9 onwards.

time

Optional datetime.date, datetime.datetime or timestamp string.The time instant or time extent of the raster to be sampled.Time instant specified as datetime.date, datetime.datetime ortimestamp in milliseconds since epochSyntax: time=<timeInstant>

Time extent specified as list of [<startTime>, <endTime>]For time extents one of <startTime> or <endTime> could be None. ANone value specified for start time or end time will representinfinity for start or end time respectively.Syntax: time=[<startTime>, <endTime>] ; specified asdatetime.date, datetime.datetime or timestampThis parameter is available from 10.9 onwards.

Returns:

A list of samples

propertyheight

Get the height of theImageryLayer object.

Returns:

A float

propertyhistograms

Get the histograms of each band in theImageryLayeras a list of dictionaries corresponding to each band.

Note

If histograms is not found, returns None. In this case, call thecompute_histograms method.

Syntax:

my_hist = imagery_layer.histograms

Returns:

#Structure of the return value for a two band imagery layer
[
{#band 1
”size”:256,
”min”:560,
”max”:24568,
”counts”: [10,99,56,42200,125,….] #length of this list corresponds ‘size’
},
{#band 2
”size”:256,
”min”:8000,
”max”:15668,
”counts”: [45,9,690,86580,857,….] #length of this list corresponds ‘size’
}
]

identify(geometry:dict[str,Any]|Polygon|Point|MultiPoint|Envelope,mosaic_rule:str|dict|None=None,rendering_rules:list[str]|dict[str,Any]|None=None,pixel_size:str|dict[str,int]|None=None,time_extent:list[datetime]|datetime|None=None,return_geometry:bool=False,return_catalog_items:bool=True,return_pixel_values:bool=True,max_item_count:int|None=None,slice_id:int|None=None,process_as_multidimensional:bool=False)

Theidentify method identifies the content of an image layer for a given locationand a given mosaic rule. The location can be aPoint or aPolygon or aEnvelope or aMultiPoint

Note

Theidentify operation is supported by both mosaic dataset andraster dataset image services.

The result of this operation includes the pixel value of the mosaicfor a given mosaic rule, a resolution (pixel size), and a set ofcatalog items that overlap the given geometry. The single pixelvalue is that of the mosaic at the centroid of the specifiedlocation. If there are multiple rasters overlapping the location,the visibility of a raster is determined by the order of therasters defined in the mosaic rule. It also contains a set ofcatalog items that overlap the given geometry. The catalog itemsare ordered based on the mosaic rule. A list of catalog itemvisibilities gives the percentage contribution of the item tooverall mosaic.

Parameter

Description

geometry

Required dictionary/Point/Polygon/MultiPoint/Envelope. AGeometry thatdefines the location to be identified.

Note

The location can be a point or polygon or envelope or multipoint.
  • Support for envelope was added at 10.9.1.

  • Support for multipoint was added at 11.0.

mosaic_rule

Optional string or dict. Specifies the mosaic rule when defining howindividual images should be mosaicked. When a mosaic rule is notspecified, the default mosaic rule of the image layer will be used(as advertised in the root resource: defaultMosaicMethod,mosaicOperator, sortField, sortValue).

rendering_rules

Optional dictionary/list. Specifies the rendering rule for how therequested image should be rendered.

pixel_size

Optional string or dict. The pixel level being identified (or theresolution being looked at).Syntax:

  • dictionary structure: pixel_size={point}

  • Point simple syntax: pixel_size=’<x>,<y>’

Examples:
  • pixel_size={“x”: 0.18, “y”: 0.18}

  • pixel_size=’0.18,0.18’

time_extent

Optional list of datetime objects or datetime object. The timeinstant or time extent of the raster to be identified. Thisparameter is only valid if the image layer supports time.

return_geometry

Optional boolean. Default is False. Indicates whether or not toreturn the raster catalog item’s footprint. Set it to false when thecatalog item’s footprint is not needed to improve the identifyoperation’s response time.

return_catalog_items

Optional boolean. Indicates whether or not to return raster catalogitems. Set it to false when catalog items are not needed to improvethe identify operation’s performance significantly. When set tofalse, neither the geometry nor attributes of catalog items will bereturned.

return_pixel_values

Optional boolean. Indicates whether to return the pixel values ofall mosaicked raster catalog items under the requested geometry.

Set it to false when only the pixel value of mosaicked output isneeded at requested geometry.

The default value of this parameter isTrue.

Note

This parameter was added at 10.6.1.

max_item_count

Optional int. If the return_catalog_items parameter is set to true,this parameter will take effect. The default behavior is to returnall raster catalog items within the requested geometry.Otherwise, the number of items returned will be the value specified in themax_item_count or all eligible items, whichever is smaller.

Example:max_item_count = 5

Note

The parameter was added at 10.6.1.

slice_id

Optional int. The slice ID of multidimensional raster. The identifyoperation will be performed for the specified slice. To get the sliceID use slices method on theImageryLayer object.

Note

The parameter was added at 10.9 for image services which useArcObjects11 orArcObjectsRasterRenderingas the service provider.

process_as_multidimensional

Optional boolean. Specifies whether to process the image service as amultidimensional image service.

  • False - Pixel values of the specified rendering rules and mosaic rule at the specified geometry will be returned. This is the default.

  • True - The image service is treated as a multidimensional raster, and pixel values from all slices, along with additional properties describing the slices, will be returned.

Note

The parameter was added at 10.9 for image services which useArcObjects11 orArcObjectsRasterRenderingas the service provider.

Returns:

A dictionary

# Example Usageimg_layer=gis.content.search("my_image_service",item_type="Imagery Layer")[0].layers[0]identified=img_layer.identify(geometry=polygon_obj,pixel_size="0.18,0.18",return_geometry=True,return_pixel_values=False,max_item_count=5,slice_id=1,)
image_to_map(raster_id:int,geometry:dict[str,Any]|Polygon|Point|MultiPoint|Polyline,out_sr:dict|None=None,options:dict|None=None)

Theimage_to_map method converts a point on an image location to a map location.

Note

Theimage_to_map operation is supported at 11.2 and later.

Parameter

Description

raster_id

Required integer. Specifies the objectId of the image service’s raster catalog.Theraster_id value identifies which raster of the mosaic datasetwill be used.

geometry

Required dictionary/Point/Polygon/MultiPoint/Polyline. AGeometry thatneeds to be converted from image space to map space.

out_sr

Optional integer, string, dictionary,SpatialReference.The spatial reference of the returned geometry.

options

Optional dict. Supports DOff and Adjust keys.

  • DOff - The DOff key is the depth offset value, and has a numeric value.DOff is introduced to resolve Z-fighting, setting the depth offset tothat the geometries the user sketched can draw on top of mesh insteadof burying inside of it.

  • Adjust is a boolean value. If Adjust is set to True, the “background” vertices will be adjusted to the foreground.

Syntax: {“DOff”:<depth offset value>, “Adjust”: True/False}

Returns:

A dictionary

# Example Usageimg_layer=gis.content.search("my_image_service",item_type="Imagery Layer")[0].layers[0]output_info=img_layer.image_to_map(raster_id=1,geometry={"x":852039.3825317159,"y":5776166.453139959,"z":4107.771753068082},out_sr=3857)
image_to_map_multiray(geometries:list,raster_ids:list,out_sr:dict|None=None)

Theimage_to_map_multiray computes a geometry in map space from multiple views of the geometry in image space on multiple images.The function operation computes a 3D geometry in a map from multiple image space geometries on multiple corresponding raster items ofone same object. For example, a house shows up in several raster items. Users may specify the house location on each image using thegeometries parameter. In the rasterIds parameter, specify the rasterIds of the images in the same order. Then the operation will find the houselocation in the map space.

Note

Theimage_to_map_multiray operation is supported at 11.2 and later.

Parameter

Description

geometries

Required dictionary with the value being the list of geometries and key being “geometries”.All geometries in this list should be of the type defined bygeometryType

raster_ids

Required list. The object IDs of a raster catalog items.

out_sr

Optional integer string, dictionary,SpatialReference.

Returns:

A dictionary

# Example Usageimg_layer=gis.content.search("my_image_service",item_type="Imagery Layer")[0].layers[0]op=img_layer.image_to_map(raster_ids="1,2",geometries={"geometries":[{"x":-45.56,"y":-31.75,"z":634.18},{"x":-55.56,"y":31.75,"z":234.18}]],"geometryType":"esriGeometryPoint"}out_sr=3857)
propertyitem_info

Get the Image Service’s item’s infomation

key_properties(rendering_rule:dict[str,Any]|None=None)

Thekey_properties method retrieves the key properties of theImageryLayer,such as band properties.

Parameter

Description

rendering_rule

Optional dictionary. Specifies the rendering rule for how therequested image should be rendered.

Returns:

A dictionary representing the key properties of theImageryLayer

last()

Thelast method returns thisImageryLayer with mosaic operation set tolast (overlappingpixels at the same location are resolved by picking the last image)

Returns:

AnImageryLayer object

legend(band_ids:str|None=None,rendering_rule:dict[str,Any]|None=None,as_html:bool=False)

Thelegend method retrieves the legend information. The information includes the symbol images and labels foreach symbol.

Note

Each symbol is generally an image of size 20 x 20pixels at 96 DPI. Symbol sizes may vary slightly for some renderertypes (e.g., Vector Field Renderer). Additional information in thelegend response will include the layer name, layer type, label,and content type.

The legend symbols include the base64 encodedimageData. Thesymbols returned in response to an image layer legend requestreflect the default renderer of the image layer or the rendererdefined by the rendering rule and band Ids.

Parameter

Description

band_ids

Optional string. If there are multiple bands, you can specify asingle band, or you can change the band combination (red, green,blue) by specifying the band ID. Band ID is 0 based.Example: bandIds=2,1,0

rendering_rule

Optional dictionary. Specifies the rendering rule for how therequested image should be rendered.

as_html

Optional bool. Returns an HTML table if True

Returns:

A legend as a dictionary by default, or as an HTML table if as_html is True

map_to_image(raster_id:int,geometry:dict[str,Any]|Polygon|Point|MultiPoint|Polyline,in_sr:dict|None=None,options:dict|None=None)

Themap_to_image method converts a point on a map location to an image location.

Note

Themap_to_image operation is supported at 11.2 and later.

Parameter

Description

raster_id

Required integer. Specifies the objectId of the image service’s raster catalog.Theraster_id value identifies which raster of the mosaic datasetwill be used as part of the calculation.

geometry

Required dictionary/Point/Polygon/MultiPoint/Polyline. AGeometry thatdefines the location to be identified.

in_sr

Optional integer, string, dictionary,SpatialReference.

options

Optional dict. It has VisibleOnly key.
  • VisibleOnly is a boolean value. If it’s true, method will return an empty geometry if vertices are behind the depths

Syntax: {“VisibleOnly”: True/False}

Returns:

A dictionary

# Example Usageimg_layer=gis.content.search("my_image_service",item_type="Imagery Layer")[0].layers[0]op=img_layer.map_to_image(raster_id=1,geometry={"x":-116.95577740063976,"y":34.8830387385285,"z":635.8976440429688},in_sr=4326)
max()

Themax method returns thisImageryLayer with mosaic operation set tomax (overlappingpixels at the same location are resolved by picking the max pixel value)

Returns:

AnImageryLayer object

mean()

Themean method returns thisImageryLayer with mosaic operation set tomean (overlappingpixels at the same location are resolved by choosing the mean of all overlapping pixels)

Returns:

AnImageryLayer object

measure(from_geometry:Geometry|dict[str,Any],to_geometry:Geometry|dict[str,Any]|None=None,measure_operation:str|dict[str,str]|None=None,pixel_size:str|dict[str,float]|None=None,mosaic_rule:str|dict[str,str]|None=None,linear_unit:str|None=None,angular_unit:str|None=None,area_unit:str|None=None)

Themeasure method lets a user measure distance, direction, area,perimeter, and height from an image layer. The result of thisoperation includes the name of the raster dataset being used,sensor name, and measured values.

Note

The measure operation can be supported by image services fromraster datasets and mosaic datasets. Spatial reference is requiredto perform basic measurement (distance, area, and so on). Sensormetadata (geodata transformation) needs to be present in the datasource used by an image layer to enable height measurement (forexample, imagery with RPCs). The mosaic dataset or Layer needs toinclude DEM to perform 3D measure.

Parameter

Description

from_geometry

RequiredGeometry or dictionary.A geometry that defines thefrom location of the measurement.

to_geometry

OptionalGeometry or dictionary. A geometry that definesthetolocation of the measurement. The type of geometry must be the sameasfrom_geometry.

measure_operation

Optional string or dict. Specifies the type of measure beingperformed.

Values:Point, DistanceAndAngle, AreaAndPerimeter, HeightFromBaseAndTop,HeightFromBaseAndTopShadow,HeightFromTopAndTopShadow, Centroid,Point3D, DistanceAndAngle3D,AreaAndPerimeter3D, Centroid3D

Different measureOperation types require different from and togeometries:

  • Point and Point3D-Require only from_geometry, type: {Point}

  • DistanceAndAngle, DistanceAndAngle3D, HeightFromBaseAndTop, HeightFromBaseAndTopShadow, and HeightFromTopAndTopShadow - Require both from_geometry and to_geometry, type: {Point}

  • AreaAndPerimeter, AreaAndPerimeter3D, Centroid, and Centroid3D - Require only from_geometry, type: {Polygon}, {Envelope}

Supported measure operations can be derived from themensurationCapabilities in the image layer root resource.Basic capability supports Point,DistanceAndAngle, AreaAndPerimeter,and Centroid.Basic and 3Dcapabilities support Point3D,DistanceAndAngle3D,AreaAndPerimeter3D,and Centroid3D.Base-Top Height capability supportsHeightFromBaseAndTop.Top-Top Shadow Height capability supportsHeightFromTopAndTopShadow.Base-Top Shadow Height capability supportsHeightFromBaseAndTopShadow.

pixel_size

Optional string or dict. The pixel level (resolution) beingmeasured. If pixel size is not specified, pixel_size will default tothe base resolution of the image layer. The raster at the specified pixelsize in the mosaic dataset will be used for measurement.Syntax:

  • dictionary structure: pixel_size={point}

  • Point simple syntax: pixel_size=’<x>,<y>’

Examples:
  • pixel_size={“x”: 0.18, “y”: 0.18}

  • pixel_size=’0.18,0.18’

mosaic_rule

Optional string or dict. Specifies the mosaic rule when defining howindividual images should be mosaicked. When a mosaic rule is notspecified, the default mosaic rule of the image layer will be used(as advertised in the root resource: defaultMosaicMethod,mosaicOperator, sortField, sortValue). The first visible image isused by measure.

linear_unit

Optional string. The linear unit in which height, length, orperimeters will be calculated. It can be any of the followingU constant. If the unit is not specified, the default isMeters. The list of valid Units constants include:Inches,Feet,Yards,Miles,NauticalMiles,Millimeters,Centimeters,Decimeters,Meters,Kilometers

angular_unit

Optional string. The angular unit in which directions of linesegments will be calculated. It can be one of the followingDirectionUnits constants:DURadians, DUDecimalDegrees

Note

If the unit is not specified, the default isDUDecimalDegrees.

area_unit

Optional string. The area unit in which areas of polygons will becalculated. It can be any AreaUnits constant. If the unit is notspecified, the default is SquareMeters. The list of validAreaUnits constants include:SquareInches,SquareFeet,SquareYards,Acres,SquareMiles,SquareMillimeters,SquareCentimeters,SquareDecimeters,SquareMeters,Ares,Hectares,SquareKilometers

Returns:

A dictionary

# Example Usageimg_layer=gis.content.search("my_image_service",item_type="Imagery Layer")[0].layers[0]measured=img_layer.measure(from_geometry=point1,to_geometry=point2,measure_operation="HeightFromTopAndTopShadow")
measure_from_image(from_geometry:Geometry|dict[str,Any],to_geometry:Geometry|dict[str,Any]|None=None,raster_id:int|None=None)

Themeasure_from_image operation provides mensuration capabilities within one image space andreturns the measurement result in a map space unit. When to_geometry is specified, this operationreturns distance between the two geometries. When to_geometry is not specified, this operation returnslength for a polyline geometry and area for a polygon geometry.

Parameter

Description

from_geometry

RequiredGeometry or dictionary.A geometry defines the from location of the measurement.If the spatial reference is missing, the coordinate is assumed to bein image space set throughraster_id parameter. If the spatial referenceexists, it will be used for the geometry’s coordinates.

Possible geometry types are: Point, Polyline, Polygon

to_geometry

OptionalGeometry or dictionary.A geometry that defines the to location of the measurement.If spatialReference is missing, the coordinate is assumed to be inimage space set through rasterId parameter. If spatialReference exists,it will be used for the geometry’s coordinates.

Possible geometry types are: Point, Polyline, Polygon

raster_id

Optional integer. Specifies the objectId of the raster item.Thefrom_geometry andto_geometry in this operation use the image coordinate system of the specified raster item.

Returns:

A dictionary

# Example Usageimg_layer=gis.content.search("my_image_service",item_type="Imagery Layer")[0].layers[0]measured=img_layer.measure_from_image(from_geometry=point1,to_geometry=point2,raster_id=2)
propertymetadata

Get the Image Service’s XML metadata file

min()

Themin method returns thisImageryLayer with mosaic operation set tomin (overlappingpixels at the same location are resolved by picking the min pixel value)

Returns:

AnImageryLayer object

mosaic_by(method:str|None=None,sort_by:str|None=None,sort_val:str|None=None,lock_rasters:list[int]|None=None,viewpt:Point|None=None,asc:bool=True,where:str|None=None,fids:list[int]|None=None,muldidef:list|None=None,op:str='first',item_rendering_rule:str|None=None)

Themosaic_by method defines how individual images in this layer should be mosaicked.

Note

It specifies selection, mosaic method, sort order, overlapping pixel resolution, etc.Mosaic rules are for mosaicking rasters inthe 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.

Note

See theUnderstanding the mosaicking rules for a mosaic datasetpage for more inforamation on mosaic datasets. See themosaic rule page formore information on mosaic rules.

Parameter

Description

method

Optional string. Determines how the selected rasters are ordered.str, can be none,center,nadir,northwest,seamline,viewpoint,attribute,lock-rasterrequired if method is: center,nadir,northwest,seamline, optionalotherwise. If no method is passed “none” method is used, which usesthe order of records to sortIf sort_by and optionally sort_val parameters are specified,attribute method is used

Note

If lock_rasters are specified, “lock-raster” method is used.If a viewpt parameter is passed, “viewpoint” method is used.

sort_by

Optional string. field name when sorting by attributes

sort_val

Optional string. A constant value defining a reference or base valuefor the sort field when sorting by attributes

lock_rasters

Optional list, an array of raster Ids. All the rasters with the givenlist of raster Ids are selected to participate in the mosaic. Therasters will be visible at all pixel sizes regardless of the minimumand 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 descendingorder. Default is ascending order.

where

Optional string. where clause to define a subset of rasters used inthe mosaic, be aware that the rasters may not be visible at allscales

fids

Optional list of objectids, use the raster id list to define asubset of rasters used in the mosaic, be aware that the rasters maynot be visible at all scales.

muldidef

Optional array. multidemensional definition used for filtering byvariable/dimensions.See theMultidimensional definitionpage in the ArcGIS REST API documentation for more information.

op

Optional string, first,last,min,max,mean,blend,sum mosaic operationto resolve overlap pixel values: from first or last raster, use themin, max or mean of the pixel values, or blend them.

item_rendering_rule

Optional item rendering rule, applied on items before mosaicking.

Returns:

A mosaic rule.

propertymosaic_rule

Themosaic_rule property is used by theImageryLayer 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 themosaic_by orfilter_by methods on the layer.

Returns:

A mosaic rule

propertymultidimensional_info

Get the multidimensionalinformation of the Image Layer. This property is supported if thehasMultidimensions property of the Layer is True.

Note

Common data sources for multidimensional image services are mosaicdatasets created from netCDF, GRIB, and HDF data.

propertypixel_type

Get the pixel type of theImageryLayer

Returns:

The pixel type

plot_histograms(geometry:Geometry|Polygon|Envelope|None=None,pixel_size:dict[str,Any]|str|None=None,time:str|list[int]|date|datetime|None=None,bands:list[int]=[],display_stats:bool=True,plot_properties:dict[str,Any]|None=None,subplot_properties:list[dict[str,Any],dict[str,Any]]|None=None)

Theplot_histograms method is used to plot the histograms for theImageryLayer.

Image histograms visually summarize the distribution of a continuous numeric variable by measuringthe frequency at which certain values appear in the image. The x-axis in the image histogram is a number line that displays the range of image pixel values that has been split into number ranges, or bins. A bar is drawn for each bin, and the width of the bar represents the density number range of the bin; the height of the bar represents the number of pixels that fall into that range. Understanding the distribution of your data is an important step in the data exploration process.

This method can be used for plotting the band-wise image histogram charts of anyImageryLayer published with mosaic datasets or a raster dataset.

Parameter

Description

geometry

OptionalGeometry (PolygonorEnvelope).A geometry that defines the geometry within which the histogram is computed.

Note

If not provided, then the full extent of theraster will be used for the computation.

pixel_size

Optional string or dictionary. The pixel level being used (or theresolution being looked at). If pixel size is not specified, thenpixel_size will default to the base resolution of the dataset.The structure of the pixel_size parameter is the same as thestructure of the point object returned by the ArcGIS REST API.In addition to the dictionary structure, you can specify the pixel sizewith a comma-separated string.

Syntax:
  • dictionary structure: pixel_size={point}

  • Point simple syntax: pixel_size=’<x>,<y>’

Examples:
  • pixel_size={“x”: 0.18, “y”: 0.18}

  • pixel_size=’0.18,0.18’

time

Optional datetime.date, datetime.datetime or timestamp string. Thetime instant or the time extent to compute statistics and histograms.Time instant specified as datetime.date, datetime.datetime ortimestamp in milliseconds since epochSyntax: time=<timeInstant>

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

Available in 10.8+

bands

Optional list of band indices. By default takes the first band (band index - 0).Image histogram charts are plotted for these specific bands.

Example:
  • [0,2,3]

display_stats

Optional boolean. Specifies whether to plot the band-wise statisticsalong with the histograms.

Some basic descriptive statistics are calculated and displayed onhistograms. The mean and median are displayed with one line each, andone standard deviation above and below the mean is displayed using two lines.

  • False - The statistics will not be displayed along with the histograms.

  • True - The statistics will be displayed along with the histograms. This is the default.

plot_properties

Optional dictionary. This parameter can be used to set the figureproperties. These are thematplotlib.pyplot.figure()parameters and values specified in dictionary format.

Example:

{“figsize”:(15,15)}

subplot_properties

Optional list or dictionary. This parameter can be used to set band-wisehistogram (subplot) display properties. These are thematplotlib.axes.Axes.bar()parameters and values specified in dictionary format.

Note

matplotlib.axes.Axes.bar()parameters: ‘’x’, ‘height’ or ‘align’ cannot be passed intosubplot_properties.

Example:

subplot_properties = [

{“color”:”r”},{“color”:”g”},{“color”:”b”,”edgecolor”:”w”}

]

Tip

When working with multidimensional imagery layers, you can use themultidimensional_filter()raster function on the layer for slicing the data along defined variables and dimensions.plot_histograms can then be used on the output layer returned upon applying the filter.

Returns:

None

# Usage Example: Plots histograms of the raster with specified resolution and bandsraster1.plot_histograms(pixel_size="0.18, 0.18",bands=[1,2,3],plot_properties={"figsize":(15,15)},subplot_properties=[{"color":"r"},{"color":"g"},{"color":"b","edgecolor":"w"}],)
project(geometries:list,in_sr:str|dict[str,Any]|SpatialReference,out_sr:str|dict[str,Any]|SpatialReference)

Theproject method is performed on anImageryLayer object.This operation projects a list of input geometries from the inputspatial reference to the output spatial reference. The responseorder of geometries is in the same order as they were requested.

Parameter

Description

geometries

Required list. The list of geometries to be projected.

in_sr

Required string, dictionary,SpatialReference. Thein_srcan accept amultitudes of values. These can be a WKID, image coordinate system(ICSID), or image coordinate system in json/dict format.Additionally the arcgis.geometry.SpatialReference object is also avalid entry.

Note

An image coordinate system ID can be specifiedusing 0:icsid; for example, 0:64. The extra 0: is used to avoidconflicts with wkid

out_sr

Required string, dictionary,SpatialReference. Theout_srcan accept amultitudes of values. These can be a WKID, image coordinate system(ICSID), or image coordinate system in json/dict format.Additionally the arcgis.geometry.SpatialReference object is also avalid entry.

Note

An image coordinate system ID can be specifiedusing 0:icsid; for example, 0:64. The extra 0: is used to avoidconflicts with wkid

Returns:

A dictionary

propertyproperties

Theproperties property retrieves and set properties of this object.

query(where:str|None=None,out_fields:str|list[str]='*',time_filter:str|list[int]|date|datetime|None=None,geometry_filter:dict|None=None,return_geometry:bool=True,return_ids_only:bool=False,return_count_only:bool=False,pixel_size:float|None=None,order_by_fields:str|None=None,return_distinct_values:bool|None=None,out_statistics:dict[str,Any]|str|None=None,group_by_fields_for_statistics:dict[str,Any]|str|None=None,out_sr:int|dict[str,Any]|SpatialReference|None=None,return_all_records:bool=False,object_ids:str|None=None,multi_dimensional_def:dict[str,Any]|None=None,result_offset:int|None=None,result_record_count:int|None=None,max_allowable_offset:int|None=None,true_curves:bool=False,as_df:bool=False,raster_query:str|None=None,return_extent_only:bool=False)

Thequery method queries anImageryLayer by applying the filter specified bythe user. The result of this operation iseither 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).

Parameter

Description

where

Optional string. A where clause on this layer to filter the imagerylayer by the selection sql statement. Any legal SQL where clauseoperating on the fields in the raster

out_fields

Optional string. The attribute fields to return, comma-delimitedlist of field names.

time_filter

Optional datetime.date, datetime.datetime or timestamp inmilliseconds. The time instant or the time extent to query.

Syntax: time_filter=<timeInstant>

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

geometry_filter

Optional arcgis.geometry.filters. Spatial filter fromarcgis.geometry.filters module to filter results by a spatialrelationship with another geometry.

return_geometry

Optional boolean. True means a geometry will be returned, else justthe attributes

return_ids_only

Optional boolean. False is default. True means only OBJECTIDs willbe returned

return_count_only

Optional boolean. If True, then an integer is returned only based onthe sql statement

return_extent_only

optional boolean. If True, then only the extent is returned.This parameter is available from 10.8.1 onwards.

pixel_size

optional dict or string. Query visible rasters at a given pixel size.If pixel_size is not specified, rasters at all resolutions can bequeried.Syntax:

  • dictionary structure: pixel_size={point}

  • Point simple syntax: pixel_size=’<x>,<y>’

Examples:
  • pixel_size={“x”: 0.18, “y”: 0.18}

  • pixel_size=’0.18,0.18’

order_by_fields

Optional string. Order results by one or more field names. Use ASCor DESC for ascending or descending order, respectively.

return_distinct_values

Optional boolean. If true, returns distinct values based on thefields specified in out_fields. This parameter applies only if thesupportsAdvancedQueries property of the image layer is true.

out_statistics

Optional dict or string. The definitions for one or more field-basedstatistics to be calculated.

group_by_fields_for_statistics

Optional dict/string. One or more field names using thevalues that need to be grouped for calculating thestatistics.

out_sr

Optional dict, SpatialReference. If the returning geometry needs tobe in a different spatial reference, provide the function with thedesired WKID.

return_all_records

Optional boolean. If True(default) all records will be returned.False means only the limit of records will be returned.

object_ids

Optional string. The object IDs of this raster catalog to bequeried. When this parameter is specified, any other filterparameters (including where) are ignored.When this parameter is specified, setting return_ids_only=true isinvalid.Syntax: objectIds=<objectId1>, <objectId2>Example: objectIds=37, 462

multi_dimensional_def

Optional dict. The filters defined by multiple dimensionaldefinitions.

result_offset

Optional integer. This option fetches query results by skipping aspecified number of records. The query results start from the nextrecord (i.e., resultOffset + 1). The Default value is None.

result_record_count

Optional integer. This option fetches query results up to theresultRecordCount specified. When resultOffset is specified and thisparameter is not, image layer defaults to maxRecordCount. Themaximum value for this parameter is the value of the layer’smaxRecordCount property.max_allowable_offset - This option can be used to specify themax_allowable_offset to be used for generalizing geometries returnedby the query operation. The max_allowable_offset is in the units ofthe out_sr. If outSR is not specified, max_allowable_offset isassumed to be in the unit of the spatial reference of the Layer.

true_curves

Optional boolean. If true, returns true curves in output geometries,otherwise curves get converted to densified polylines or polygons.

as_df

Optional boolean. Returns the query result as a dataframe object

raster_query

Optional string. Make query based on key properties of eachraster catalog item. Any legal SQL where clause operating on thekey properties of raster catalog items is allowed.

Example: LANDSAT_WRS_PATH >= 150 AND LANDSAT_WRS_PATH<= 165

This option was added at 10.8.1.

Returns:

AFeatureSet containing the footprints (features) matching the query whenreturn_geometry isTrue, else a dictionary containing the expected returntype.

# Usage Exampleimg_lyr=gis.content.search("my_image_service",item_type="Imagery Layer")[0].layers[0]search_res=img_lyr.query(where="OBJECTID=1")
query_boundary(out_sr:int|dict[str,Any]|SpatialReference|None=None)

Thequery_boundary operation is supported by image services based on mosaic datasetsor raster datasets.

For an image service based on a mosaic dataset, the result of this operationincludes the geometry shape of the mosaicked items’ boundary and area ofcoverage in square meters.

For an image service based on a raster dataset, the result of this operationincludes the geometry shape of the dataset’s envelope boundary and area ofcoverage in square meters.

Note

Thequery_boundary method was added at 10.6.

Parameter

Description

out_sr

The spatial reference of the boundary’s geometry.

The spatial reference can be specified as either a well-known ID oras a spatial reference JSON object.

If theout_SR is not specified, the boundary will be reported in thespatial reference of the image service.

Example:

4326

Returns:

A dictionary representing the boundary geometry shape.

query_gps_info(where:str|None=None,object_ids:list[int]|None=None,time_filter:str|list[int]|date|datetime|None=None,geometry_filter:dict|None=None)

Thequery_gps_info method queries anImageryLayer by applying the filter specified bythe user. The result of this operation is the gps and orientation information for image collections created byOrthoMapping REST/Python API or Ortho Maker.

Note

Thequery_gps_info operation is supported at 11.2 and later.

Parameter

Description

where

Optional string. A where clause on this layer to filter the imagerylayer by the selection sql statement. Any legal SQL where clauseoperating on the fields in the raster

object_ids

Optional list of objectids, use the raster id list to define asubset of rasters.

time_filter

Optional datetime.date, datetime.datetime or timestamp inmilliseconds. The time instant or the time extent to query.

Syntax: time_filter=<timeInstant>

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

geometry_filter

Optional arcgis.geometry.filters. Spatial filter fromarcgis.geometry.filters module to filter results by a spatialrelationship with another geometry.

Returns:

A dict containing the gps and camera information for the image collection.

# Usage Exampleimg_lyr=gis.content.search("my_image_service",item_type="Imagery Layer")[0].layers[0]gps_info=img_lyr.query_gps_info(where="OBJECTID=1")# Usage Example 2img_lyr=gis.content.search("my_image_service",item_type="Imagery Layer")[0].layers[0]aoi_intersects=arcgis.geometry.filters.intersects(geometry=geometry_obj)gps_info=img_lyr.query_gps_info(geometry_filter=aoi_intersects)
propertyraster_info

Get the information about theImageryLayer such asbandCount,extent,pixelSizeX,pixelSizeY, andpixelType.

Returns:

A dictionary of the raster information

propertyrasters

Therasters property creates a Raster Manager for this layer.Used to create an instance of the manager and help perform edit methods on theImageryLayer.

Returns:

An instance ofRasterManager for the ImageryLayer

refresh_service(options:str=None,future:bool=True)str

Refresh Service is a task in the existing out-of-the-boxPublishing Tools geoprocessing service used by the service publisherto refresh a GIS service to reflect back-end data changes.

render_tilesonly_layer(level:int|None=None,slice_id:int|None=None)

Therender_tilesonly_layer method renders a tiles-onlyImageryLayer at a givenlevel.

Parameter

Description

level

Optional integer. Level to be used for rendering.Default value is 0.

slice_id

Optional integer. Renders the given slice of a multidimensional raster.To get the slice index use slices method on the ImageryLayer object.

Returns:

None

propertyrows

Get the number of rows in theImageryLayer.

Returns:

An Integer

save(output_name:str|None=None,for_viz:bool=False,process_as_multidimensional:bool|None=None,build_transpose:bool|None=None,context:dict|None=None,*,gis:GIS|None=None,future:bool=False,estimate:bool|None=False,**kwargs)

Thesave method saves this imagery layer to the GIS as anImageryLayer item.Iffor_viz isTrue, a newItem is created thatuses the applied raster functions for visualization at display resolution using on-the-fly image processing.Iffor_viz isFalse, distributed raster analysis is used for generating a new raster information product byapplying raster functions at source resolution across the extent of the output imagery layer.

Parameter

Description

output_name

Optional string. If not provided, an Imagery Layer item is createdby the method and used as the output.You can pass in the name of the output Imagery Layer that should becreated by this method to be used as the output for the tool.Alternatively, if for_viz is False, you can pass in an existingImage Layer Item from your GIS to use that instead.A RuntimeError is raised if a layer by that name already exists

for_viz

Optional boolean. If True, a new Item is created that uses theapplied raster functions for visualization at display resolutionusing on-the-fly image processing.If for_viz is False, distributed raster analysis is used forgenerating a new raster information product for use in analysis andvisualization by applying raster functions at source resolutionacross the extent of the output imagery layer.

process_as_multidimensional

Optional bool. If the input is multidimensional raster, the outputwill be processed as multidimensional if set to True

build_transpose

Optional bool, if set to true, transforms the outputmultidimensional raster. Valid only if process_as_multidimensionalis set to True

context

context contains additional settings that affect task execution.

context parameter overwrites values set through arcgis.env parameter

This function has the following settings:

  • Extent (extent): A bounding box that defines the analysis area.

    Example:

    {“extent”: {“xmin”: -122.68,“ymin”: 45.53,“xmax”: -122.45,“ymax”: 45.6,“spatialReference”: {“wkid”: 4326}}}

  • Output Spatial Reference (outSR): The output raster will beprojected into the output spatial reference.

    Example:

    {“outSR”: {spatial reference}}

  • Snap Raster (snapRaster): The output raster will have itscells aligned with the specified snap raster.

    Example:

    {‘snapRaster’: {‘url’: ‘<image_service_url>’}}

  • Mask (mask): Only cells that fall within the analysismask will be considered in the operation.

    Example:

    {“mask”: {“url”: “<image_service_url>”}}

  • Cell Size (cellSize): The output raster will have the resolutionspecified by cell size.

    Example:

    {‘cellSize’: 11} or {‘cellSize’: {‘url’: <image_service_url>}} or {‘cellSize’: ‘MaxOfIn’}

  • Parallel Processing Factor (parallelProcessingFactor): controlsRaster Processing (CPU) service instances.

    Example:

    Syntax example with a specified number of processing instances:

    {“parallelProcessingFactor”: “2”}

    Syntax example with a specified percentage of totalprocessing instances:

    {“parallelProcessingFactor”: “60%”}

  • Resampling Method (resamplingMethod): The output raster will beresampled to method specified.The supported values are: BILINEAR, NEAREST, CUBIC.

    Example:

    {‘resamplingMethod’: “NEAREST”}

gis

OptionalGIS object.The GIS to be used for saving theoutput. Keyword only parameter.

future

Optional boolean. If True, a future object will be returned and the processwill not wait for the task to complete. The default is False, which means wait for results.

estimate

Keyword only parameter. Optional Boolean. If True, the number of credits needed to run the operation will be returned as a float.Available only on ArcGIS Online.

folder

Optional string or dictionary. Creates a folder in the portal, if it doesnot exist, with the given folder name and persists the output in this folder.The properties property on the Folder object returned by thecreate() can also be passed in as input.

Example:

{‘username’: ‘user1’, ‘id’: ‘6a3b77c187514ef7873ba73338cf1af8’, ‘title’: ‘trial’}

tiles_only

In ArcGIS Online, the default output image service for this functionwould be a Tiled Imagery Layer.

To create Dynamic Imagery Layer as output on ArcGIS Online, settiles_only parameter toFalse.

Function will not honor tiles_only parameter in ArcGIS Enterprise andwill generate Dynamic Imagery Layer by default.

Returns:

output_raster -ImageryLayer item

# Usage Exampleimg_lyr.save(output_name="saved_imagery_layer",process_as_multidimensional=True,build_transpose=True,folder="my_imagery_layers",gis=gis)
propertyservice

Theservice property represents the service backing this imagery layer (if user can administer the service).

set_filter(where:str|None=None,geometry:dict|None=None,time:str|list[int]|date|datetime|None=None,lock_rasters:bool=False,clear_filters:bool=False)

Theset_filters method filters the rasters that will be used for applying raster functions.

Iflock_rasters is set toTrue, the LockRaster mosaic rule will be applied to the layer,unless overridden.

Parameter

Description

where

Optional string. A where clause on this layer to filter the imagerylayer by the selection sql statement. Any legal SQL where clauseoperating on the fields in the raster

geometry

Optional arcgis.geometry.filters. To filter results by a spatialrelationship with another geometry

time

Optional datetime, date, or timestamp. A temporal filter to thislayer to filter the imagery layer by time using the specified timeinstant or the time extent.

Syntax: time_filter=<timeInstant>

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

lock_rasters

Optional boolean. If True, the LockRaster mosaic rule will beapplied to the layer, unless overridden

clear_filters

Optional boolean. If True, the applied filters are cleared

slices(muldidef:list[str]|None=None)

Theslices method is used to query slice ID and multidimensional information of a multidimensional imageservice.

Note

Theslices operation is available in ArcGIS Image Server 10.8.1 and higher.

Parameter

Description

muldidef

Optional list. Multidimensional definition used for queryingdimensional slices of the input image service.

See theMultidimensional definitionpage in the ArcGIS REST API documentation for more information.

Returns:

A dictionary containing the list of slice definitions.

# Usage Example: This example returns the slice ID and multidimensional information of slices with# "salinity" variable at "StdZ" dimension with a value of "-5000".multidimensional_definition=[{"variableName":"salinity","dimensionName":"StdZ","values":[-5000]}]multidimensional_lyr_input.slices(multidimensional_definition)
spectral_profile(points:list[Point]=[],show_values:bool=False,plot_properties:dict[str,Any]={})

Thespectral_profile method can be used to create spectral profile charts.

Spectral profile charts allow you to select areas of interest or ground features on the image and review the spectral information of all bands in a chart format.

The x-axis of the spectral profile displays the band names

The y-axis of the spectral profile displays the spectral values.

Parameter

Description

points

Required list ofPoint objects.

show_values

Optional boolean. Default is False.Set this parameter to True to display the values at each point in the line graph.

plot_properties

Optional dictionary. This parameter can be used to set the figureproperties. These are thematplotlib.pyplot.figure()parameters and values specified in dictionary format.

eg: {“figsize”:(15,15)}

Returns:

None

statistics(variable:str|None=None,rendering_rule:dict|None=None)

Thestatistics method retrieves the statistics of the raster.

Note

Thestatistics method is available in ArcGIS Image Server 10.8.1 and higher.

Parameter

Description

variable

Optional string. For an image service that has multidimensionalinformation, this parameter can be used to request statistics foreach variable. If not specified, it will return statistics for thewhole image service. Eligible variable names can be queried frommultidimensional_info property of the Imagery Layer object.

rendering_rule

Optional dictionary. Specifies the rendering rule for how the requested image should be rendered.

In the context of accessing image service statistics resource,this parameter is used to retrieve statistics info in attachedpredefined raster function templates (inside a StatisticsHistogram function).

This parameter is available from 10.9.1

Returns:

A dictionary containing the statistics.

# Usage Example: This example returns the statistics of an Imagery Layer object.lyr_input.statistics()
sum()

Thesum method returns thisImageryLayer with mosaic operation set tosum (overlappingpixels at the same location are resolved by adding up all overlapping pixel values)

Returns:

AnImageryLayer object

temporal_profile(points:list[Point]=[],time_field:str|None=None,variables:list[str]=[],bands:list[int]=[0],time_extent:list[datetime]|None=None,dimension:list[str]|None=None,dimension_values:list[float]|None=[],show_values:bool=False,trend_type:str|None=None,trend_order:int|None=None,plot_properties:dict={})

Thetemporal_profile method creates a temporal profile.A temporal profile serves as a basic analysis tool for imagery data in a time series.Visualizing change over time with the temporal profile allows trends to be displayedand compared with variables, bands, or values from other dimensions simultaneously.

Using the functionality in temporal profile charts, you can perform trend analysis, gain insight intomultidimensional raster data at given locations, and plot values that are changing over timein the form of a line graph.

Temporal profile charts can be used in various scientific applications involving time seriesanalysis of raster data, and the graphical output of results can be used directly asinput for strategy management and decision making.

The x-axis of the temporal profile displays the time in continuous time intervals. The time field isobtained from the timeInfo of the image service.

The y-axis of the temporal profile displays the variable value.

Parameter

Description

points

Required list ofPoint objects.

time_field

Required string. The time field that will be used for plottingtemporal profile.

If not specified the time field is obtained from the timeInfo ofthe image service.

variables

Required list of strings. The variables that will be used for plotting temporal profile.For non multidimensional data, the variable would be name of the Sensor.To plot the graph against all sensors specify - “ALL_SENSORS”

bands

Optional list of integers. Band indices to be used for plotting temporal profile.By default takes the first band (band index - 0).For a multiband data, you can compare the time change of differentbands over different locations.

time_extent

Optional list of datetime objects. This represents the time extent.

dimension

Optional list of strings. The dimension names that will be used for plotting temporal profile.This option works specifically on multidimensional data containing a time dimension and other dimensions.

The temporal profile is created based on the specific values in otherdimensions, such as depth at the corresponding time value. For example,soil moisture data usually includes both a time dimension and verticaldimension below the earth’s surface, resulting in a temporal profileat 0.1, 0.2, and 0.3 meters below the ground.

dimension_values

Optional list of floats. This parameter can be used to specifythe values of dimension parameter other than the time dimension (dimensionname specified using dimension parameter)

show_values

Optional boolean. Default False.Set this parameter to True to display the values at each point in the line graph.

trend_type

Optional string. Default None.Set the trend_type parameter to either linear or harmonic to draw the trend line.linear : Fits the pixel values for a variable along a linear trend line.harmonic : Fits the pixel values for a variable along a harmonic trend line.

trend_order

Optional integer. The frequency number to use in the trend fitting.This parameter specifies the frequency of cycles in a year.The default value is 1, or one harmonic cycle per year.

This parameter is only included in the trend analysis for a harmonic regression.

plot_properties

Optional dictionary. This parameter can be used to set the figureproperties. These are thematplotlib.pyplot.figure()parameters and values specified in dictionary format.

eg: {“figsize”:(15,15)}

Returns:

None

thumbnail(out_path:str|None=None)

Thethumbnail method downloads the image service’s thumbnail image to local disk.

Parameter

Description

out_path

Optional string. Represents the path to which the image needs to be downloaded.

# Usage Example: This example returns the thumbnail of an Imagery Layer object.lyr_input.thumbnail()
Returns:

string representing path to the downloaded thumbnail.

propertytiles

Thetiles property creates an ImageryTileManager for this layer.This manager helps perform edits on the tiles of the Image Layer.

Returns:

AnImageryTileManager for this Image Layer

propertytiles_only

Thetiles_only property returnsTrue if the layer is a Tiled Imagery Layer.

Returns:

A boolean indicating a Tiled Imagery Layer (True), or not (False).

to_features(field:str='Value',output_type:str='Polygon',simplify:bool=True,output_name:str|None=None,create_multipart_features:bool=False,max_vertices_per_feature:int|None=None,context:dict|None=None,*,gis:GIS|None=None,future:bool=False,estimate:bool=False,**kwargs)

Theto_features method converts this raster to a persistedFeatureLayerof the specified type using Raster Analytics.

Note

Distributed raster analysis is used for generating a new feature layer byapplying raster functions at source resolution across the extent of the rasterand performing a raster to features conversion.

Parameter

Description

field

Optional string - field that specifies which value will be used for the conversion.It can be any integer or a string field.

A field containing floating-point values can only be used if the output is to a point dataset.

Default is “Value”

output_type

Optional string.

One of the following: [‘Point’, ‘Line’, ‘Polygon’]

simplify

Optional bool, This option that specifies how the features should be smoothed. It isonly available for line and polygon output.

True, then the features will be smoothed out. This is the default.

if False, then The features will follow exactly the cell boundaries of the raster dataset.

output_name

Optional. If not provided, an Feature layer is created by the method and used as the output

You can pass in an existing Feature Service Item from your GIS to use that instead.

Alternatively, you can pass in the name of the output Feature Service that should be created by this methodto be used as the output for the tool.

A RuntimeError is raised if a service by that name already exists

create_multipart_features

Optional boolean. Specifies whether the output polygons will consist ofsingle-part or multipart features.

True: Specifies that multipart features will be created based on polygons that have the same value.

False: Specifies that individual features will be created for each polygon. This is the default.

max_vertices_per_feature

Optional int. The vertex limit used to subdivide a polygon into smaller polygons.

context

context contains additional settings that affect task execution.

context parameter overwrites values set through arcgis.env parameter

This function has the following settings:

  • Extent (extent): A bounding box that defines the analysis area.

    Example:

    {“extent”: {“xmin”: -122.68,“ymin”: 45.53,“xmax”: -122.45,“ymax”: 45.6,“spatialReference”: {“wkid”: 4326}}}

  • Output Spatial Reference (outSR): The output raster will beprojected into the output spatial reference.

    Example:

    {“outSR”: {spatial reference}}

gis

Optional GIS object. If not speficied, the currently active connectionis used.

future

Optional boolean. If True, a future object will be returned and the processwill not wait for the task to complete. The default is False, which means wait for results.

estimate

Keyword only parameter. Optional Boolean. If True, the number of credits needed to run the operation will be returned as a float.Available only on ArcGIS Online.

Returns:

AFeatureLayer item.

# Usage Examplefeature_layer=img_lyr.to_features(output_type="Polygon",simplify=False,output_name="new_feature_layer",create_multipart_features=True,)
validate(rendering_rule:dict[str,Any]|None=None,mosaic_rule:dict[str,Any]|None=None)

Thevalidate method validates rendering rule and/or mosaic rule of an image service.

Parameter

Description

rendering_rule

Optional dictionary. Specifies the rendering rule to be validated

mosaic_rule

Optional dictionary. Specifies the mosaic rule to be validated

Returns:

A dictionary showing whether the specified rendering rule and/or mosaic rule is valid

propertywidth

Get the width of theImageryLayer object.

Returns:

A float

ImageryLayerCacheManager

classarcgis.raster.ImageryLayerCacheManager(url,gis=None,img_lyr=None)

TheImageryLayerCacheManager class allows for administration of ArcGIS Online hosted image layers.

cancel_job(job_id:str)

Thecancel_job operation supports cancelling a job while updatetiles is running from a hosted feature service. The result of thisoperation is a response indicating success or failure with errorcode and description.

Parameter

Description

job_id

Required string, the job id to cancel.

Returns:

A boolean indicating cancellation (True), or not (False)

delete_tiles(levels:str,extent:dict[str,Any]|None=None)

Thedelete_tiles method deletes tiles for the current cache.

Parameter

Description

levels

Required string, The level to delete.Example, 0-5,10,11-20 or 1,2,3 or 0-5

extent

Optional dictionary, If specified, the tiles withinthis extent will be deleted or will be deleted basedon the service’s full extent.

Example:
6224324.092137296,487347.5253569535,
11473407.698535524,4239488.369818687
the minx, miny, maxx, maxy values or,
{“xmin”:6224324.092137296,”ymin”:487347.5253569535,“xmax”:11473407.698535524,”ymax”:4239488.369818687}
“spatialReference”:{“wkid”:102100}} the JSON
representation of the Extent object.
Returns:

A dictionary

fromarcgis.layersimportImageryLayerfromarcgis.gisimportGIS# Example Usagegis=GIS(url,username,password)img_lyr=ImageryLayer("<url>",gis)img_lyr_cache_manager=img_lyr.cache_managerdeleted_tiles=img_lyr_cache_manager.delete_tiles(levels="11-20",extent={"xmin":6224324.092137296,"ymin":487347.5253569535,"xmax":11473407.698535524,"ymax":4239488.369818687})
edit_tile_service(service_definition:str|None=None,min_scale:int|None=None,max_scale:int|None=None,source_item_id:str|None=None,export_tiles_allowed:bool=False,max_export_tile_count:int=100000)

Theedit_tile_service operation updates a Tile Service’s properties.

Parameter

Description

service_definition

Optional String.Updates a service definition

min_scale

Optional integerSets the services minimum scale for caching

max_scale

Optional integer.Sets the service’s maximum scale for caching

source_item_id

Optional String.The Source Item ID is the GeoWarehouse Item ID of the map service

export_tiles_allowed

Optional bool. Sets the value to let users export tiles

max_export_tile_count

Optional integer.Sets the maximum amount of tiles to be exported from a single call.Deletes tiles for the current cache

Returns:

A boolean indicating success (True), or failure (False)

classmethodfromitem(item:Item)

Thefromitem method is used to create aFeatureLayerCollection from aItem class.

Parameter

Description

item

A requiredItem object. The item needed to convert toaFeatureLayerCollection object.

Returns:

AFeatureLayerCollection object.

import_tiles(item:str|Item,levels:str|list[int]|None=None,extent:str|dict[str,int]|None=None,merge:bool=False,replace:bool=False)

Theimport_tiles method imports cache from a newImageLayerTilePackage.

Parameter

Description

item

Required ItemId orItem. The TPK file’s item id.This TPK file contains to-be-extracted bundle fileswhich are then merged into an existing cache service.

levels

Optional String / List of integers, The level of detailsto update. Example: “1,2,10,20” or [1,2,10,20]

extent

Optional String / Dict. The area to update as Xmin, YMin, XMax, YMaxexample: “-100,-50,200,500” or{‘xmin’:100, ‘ymin’:200, ‘xmax’:105, ‘ymax’:205}

merge

Optional Boolean. Default is false and applicable tocompact cache storage format. It controls whetherthe bundle files from the TPK file are merged withthe one in the existing cached service. Otherwise,the bundle files are overwritten.

replace

Optional Boolean. Default is false, applicable tocompact cache storage format and used whenmerge=true. It controls whether the new tiles willreplace the existing ones when merging bundles.

Returns:

A dictionary

fromarcgis.layersimportImageryLayerfromarcgis.gisimportGIS# Example Usagegis=GIS(url,username,password)img_lyr=ImageryLayer("<url>",gis)img_lyr_cache_manager=img_lyr.cache_managerimported_tiles=img_lyr_cache_manager.import_tiles(item=item1,levels="11-20",extent={"xmin":6224324.092137296,"ymin":487347.5253569535,"xmax":11473407.698535524,"ymax":4239488.369818687},merge=True)
job_statistics(job_id:str)

Thejob_statistics method retrieves the job statistics for the givenjob_id.

Parameter

Description

job_id

required String. The unique identifier of the job in question.

Returns:

A dictionary

job_status(job_id:str)

Thejob_status method retrieves the current Job Status.

Parameter

Description

job_id

required String. The unique identifier of the job in question.

Returns:

A dictionary

propertyjobs

Get a list of all the jobs on the tile server

Returns:

A list

propertyproperties

Theproperties property retrieves and set properties of this object.

refresh()

Therefresh operation refreshes a service, which clears the webserver cache for the service.

rerun_job(job_id:str,code:str)

Thererun_job operation supports re-running a canceled job from ahosted map service. The result of this operation is a responseindicating success or failure with error code and description.

Parameter

Description

code

Required string, parameter used to re-run a givenjobs with a specific errorcode:ALL |ERROR |CANCELED

job_id

Required string, job to reprocess

Returns:

JSON dictionary indicating ‘success’ or ‘error’

swap(target_service_name:str)

The swap operation replaces the current service cache with an existing one.

Note

Theswap operation is for ArcGIS Online only.

Parameter

Description

target_service_name

Required string. Name of service you want to swap with.

Returns:

dictionary indicating success or error

update_tiles(levels:str|list[int]|None=None,extent:str|dict[str,int]|None=None,merge:bool=False,replace:bool=False)

Theupdate_tiles method starts tile generation for ArcGIS Online. The levels of detailand the extent are needed to determine the area where tiles needto be rebuilt.

Note

Theupdate_tiles operation is for ArcGIS Online only.

Parameter

Description

levels

Optional String / List of integers, The level of detailsto update. Example: “1,2,10,20” or [1,2,10,20]

extent

Optional String / Dict. The area to update as Xmin, YMin, XMax, YMaxexample: “-100,-50,200,500” or{‘xmin’:100, ‘ymin’:200, ‘xmax’:105, ‘ymax’:205}

merge

Optional Boolean. Default isFalse. When true the updatedcache is merged with the existing cache.

replace

Optional Boolean. The default is False. The updatedtiles will remove the existing tiles.

Returns:

JSON dictionary that indicates ‘success’ or ‘error’. If the product is not ArcGIS Online tile service, theresult will be None.

fromarcgis.layersimportImageryLayerfromarcgis.gisimportGIS# Example Usagegis=GIS(url,username,password)img_lyr=ImageryLayer("<url>",gis)img_lyr_cache_manager=img_lyr.cache_managerupdated_tiles=img_lyr_cache_manager.update_tiles(levels="11-20",extent={"xmin":6224324.092137296,"ymin":487347.5253569535,"xmax":11473407.698535524,"ymax":4239488.369818687},merge=True)

ImageryTileManager

classarcgis.raster.ImageryTileManager(imglyr)

Manages the tiles for Cached Imagery Layers.

Note

This class is not created by users directly. An instance of this class, calledtiles , is available as a property of an ImageryLayer object. Users call methods on thistiles object to create and access tiles from an ImageryLayer.

Parameter

Description

imglyr

required ImageLayer. The imagery layer object that is cached.

estimate_size(tile_package:bool=False,extent:str|None=None,optimize_for_size:bool=True,compression:int=75,export_by:str='LevelID',levels:str|None=None,aoi:Polygon|None=None)

Theestimate_size operation is an asynchronous task thatallows estimation of the size of the tile package or the cache dataset that you download using the Export Tiles operation. Thisoperation can also be used to estimate the tile count in a tilepackage and determine if it will exceced the maxExportTileCountlimit set by the administrator of the layer. The result of thisoperation is the response size. This job response containsreference to the Image LayerResult method that returns the totalsize of the cache to be exported (in bytes) and the number of tilesthat will be exported.

Parameter

Description

tile_package

Optional boolean. If the value is true output will be in tilepackage format and if the value is false Cache Raster data set isreturned. The default value is false

extent

Optional string. The extent (bounding box) of the tile package orthe cache dataset to be exported. If extent does not include aspatial reference, the extent values are assumed to be in thespatial reference of the map. The default value is full extent ofthe tiled map service.

Syntax: <xmin>, <ymin>, <xmax>, <ymax>Example: -104,35.6,-94.32,41

optimize_for_size

Optional boolean. Use this parameter to enable compression of JPEGtiles and reduce the size of the downloaded tile package or thecache raster data set. Compressing tiles slightly compromises on thequality of tiles but helps reduce the size of the download. Try outsample compressions to determine the optimal compression beforeusing this feature.

compression

Optional integer. When optimizeTilesForSize=true you can specify acompression factor. The value must be between 0 and 100. Default is75.

export_by

Optional string. The criteria that will be used to select the tileservice levels to export. The values can be Level IDs, cache scalesor the Resolution (in the case of image services).Values: LevelID,Resolution,ScaleDefault: LevelID

levels

Optional string. Specify the tiled service levels to export. Thevalues should correspond to Level IDs, cache scales or theResolution as specified in exportBy parameter. The values can becomma separated values or a range.

Example 1: 1,2,3,4,5,6,7,8,9Example 2: 1-4,7-9

aoi

OptionalPolygon. TheareaOfInterest Polygon allowsexporting tiles within the specified polygon areas.

Note

This parameter supersedesextent parameter.

Returns:

A dictionary

# Example Usagesize_estimate=img_tile_manager.estimate_size(tile_package=True,levels="11-20",extent={"xmin":6224324.092137296,"ymin":487347.5253569535,"xmax":11473407.698535524,"ymax":4239488.369818687},merge=True,optimize_for_size=True,export_by="Scale")
export(tile_package:bool=False,extent:str|None=None,optimize_for_size:bool=True,compression:int=75,export_by:str='LevelID',levels:str|None=None,aoi:Polygon|None=None)

Theexport method allows client applications to download map tilesfrom server for offline use.

Note

This operation is performed on aImageryLayer that allows clients to export cache tiles. The resultof this operation is anImageLayerJob.

export can be enabled in a layer by using ArcGIS Desktop or theArcGIS Server Administrative Site Directory. In ArcGIS Desktop,make an admin or publisher connection to the server, go to layerproperties and enable “Allow Clients to Export Cache Tiles” inadvanced caching page of the layer Editor. You can also specifythe maximum tiles clients will be allowed to download.

Note

The default maximum allowed tile count is 100,000. To enable this capabilityusing the ArcGIS Servers Administrative Site Directory, edit thelayer and set the propertiesexportTilesAllowed=True andmaxExportTilesCount=100000.

Parameter

Description

tile_package

Optional boolean. Allows exporting either a tile package or acache raster data set. If the value is true output will be in tilepackage format and if the value is false Cache Raster data set isreturned. The default value is false

extent

Optional string. The extent (bounding box) of the tile package orthe cache dataset to be exported. If extent does not include aspatial reference, the extent values are assumed to be in thespatial reference of the map. The default value is full extent ofthe tiled map service.

Syntax: <xmin>, <ymin>, <xmax>, <ymax>Example: -104,35.6,-94.32,41

optimize_for_size

Optional boolean. Use this parameter to enable compression of JPEGtiles and reduce the size of the downloaded tile package or thecache raster data set. Compressing tiles slightly compromises on thequality of tiles but helps reduce the size of the download. Try outsample compressions to determine the optimal compression beforeusing this feature.

compression

Optional integer. When optimizeTilesForSize=true you can specify acompression factor. The value must be between 0 and 100. Default is75.

export_by

Optional string. The criteria that will be used to select the tileservice levels to export. The values can be Level IDs, cache scalesor the Resolution (in the case of image services).Values: LevelID,Resolution,ScaleDefault: LevelID

levels

Optional string. Specify the tiled service levels to export. Thevalues should correspond to Level IDs, cache scales or theResolution as specified in exportBy parameter. The values can becomma separated values or a range.

Example 1: 1,2,3,4,5,6,7,8,9Example 2: 1-4,7-9

aoi

OptionalPolygon. TheareaOfInterest Polygon allowsexporting tiles within the specified polygon areas.

Note

This parameter supersedesextent parameter.

Returns:

AnImageLayerJob

# Example Usageexported=img_tile_manager.export(tile_package=True,levels="11-20",extent={"xmin":6224324.092137296,"ymin":487347.5253569535,"xmax":11473407.698535524,"ymax":4239488.369818687},merge=True,optimize_for_size=True,export_by="Scale")
image_tile(level:int,row:int,column:int,blank_tile:bool=False)

For cached image services, theimage_tile method represents a single cachedtile for the image. The image bytes for the tile at the specifiedlevel, row, and column are directly streamed to the client.

Note

If the tile is not found, an HTTP status code of 404 is thrown.

Parameter

Description

level

Required integer. The level of detail ID.

row

Required integer. The row of the cache to pull from.

column

Required integer. The column of the cache to pull from.

blank_tile

Optional boolean. Default is False. This parameter applies only tocached image services that are configured with the ability to returnblank or missing tiles for areas where cache is not available. WhenFalse, the server will return a resource not found (HTTP 404)response instead of a blank or missing tile. When this parameter isnot set, the response will contain the header blank-tile : truefor a blank/missing tile.

Returns:

None or file path (string)

Raster

classarcgis.raster.Raster(path:str,is_multidimensional:bool=False,extent:dict|None=None,cmap:str|None=None,opacity:float|None=None,engine:str|None=None,gis:GIS|None=None)

ARaster object is a variable that references a raster.It can be used to query the properties of the raster dataset.

Usage:arcgis.raster.Raster(path,is_multidimensional=False, engine=None,gis=None)

TheRaster class can work with arcpy engine or image server engine. By default,if the path is a local path, then the Raster class uses the arcpy engineelse it will useimage_server engine.

Parameter

Description

path

Required string. The input raster.

Example:

path = r”/path/to/raster”

path = “https://myserver/arcgis/rest/services/ImageServiceName/ImageServer

path = “/fileShares/file_share_name/path/to/raster”

path = “/cloudStores/cloud_store_name/path/to/raster”

path = “https://sentinel-cogs.s3.us-west-2.amazonaws.com/sentinel-s2-l2a-cogs/43/M/BP/2021/6/S2A_43MBP_20210622_0_L2A/B08.tif

When working with datastore rasters or non image service urls, RasterRendering serviceshould be enabled in the active GIS connection

is_multidimensional

Optional boolean. Determines whether the input raster will betreated as multidimensional.

Specify True if the input is multidimensional and should beprocessed as multidimensional, where processing occurs for everyslice in the dataset. Specify False if the input is notmultidimensional, or if it is multidimensional and should not beprocessed as multidimensional.

Default is False

extent

Optional dict. If the input raster’s extent cannot be automaticallyinferred, pass in a dictionary representing the raster’s extentfor when viewing on aMap widget.

Example:
{ “xmin” : -74.22655,
“ymin” : 40.712216,
“xmax” : -74.12544,
“ymax” : 40.773941,
“spatialReference” :
{ “wkid” : 4326 }
}

cmap

Optional str. When displaying a 1 band raster in aMap widget, what matplotlib colormapto apply to the raster. Seearcgis.layers.symbol.display_colormaps()for a list of compatible values.

Deprecated

Please use arcgis.raster.functions.colormap to apply colormap

opacity

Optional number. When displaying a raster in aMap widget, what opacity to apply. 0is completely transparent, 1 is completely opaque.Default: 1

Deprecated

Please set the opacity in options parameter in the add method of the map widget.{“opacity”:0.7}

engine

Optional string. The backend engine to be used.Possible options:

  • “arcpy” : Use the arcpy engine for processing.

  • “image_server” : Use the Image Server engine for processing.

gis

Optional GIS.GIS of the Raster object.

# Example Usagemap=gis.map()# Overlay an image service on the 'Map' widgetservice_url=gis.content.search("my_image_service",item_type="Imagery Layer")[0].urlraster=Raster(path=service_url,gis=gis)map.content.add(raster)# Overlay .tif file present in user's registered fileShare datastore# (Requires RasterRendering service to be enabled in the active GIS)raster=Raster("/fileShares/data/Amberg.tif",gis=gis)map.content.add(raster)# Overlay a publicly accesible Cloud-Optimized GeoTIFF# (Requires RasterRendering service to be enabled in the active GIS)raster=Raster("https://sentinel-cogs.s3.us-west-2.amazonaws.com/sentinel-s2-l2a-cogs/43/M/BP/2021/6/S2A_43MBP_20210622_0_L2A/B08.tif",gis=gis)map.content.add(raster)# Overlay a local .tif fileraster=Raster(r"./data/Amberg.tif")map.content.add(raster)# Overlay a 1-channel .gdb file with the "Orange Red" colormap at 85% opacityraster=Raster("./data/madison_wi.gdb/Impervious_Surfaces")rendered_raster=colormap(raster,colorramp="Orange-Red (Continuous)")map.content.add(rendered_raster,options={"opacity":0.85})# Overlay a local .jpg file by manually specifying its extentraster=Raster("./data/newark_nj_1922.jpg",extent={"xmin":-74.22655,"ymin":40.712216,"xmax":-74.12544,"ymax":40.773941,"spatialReference":{"wkid":4326}})map.content.add(raster)
propertyRAT

TheRAT property returns the attribute table as a dictionary, if the table exists.

Returns:

A dictionary

add_dimension(variable:str,new_dimension_name:str,dimension_value:str,dimension_attributes:str|None=None)

Theadd_dimension method adds a new dimension to a given variable.

Note

Theadd_dimension operation is not supported on image services

Parameter

Description

variable

Required string. variable to which the new dimension is to be added

new_dimension_name

Required string. name of the new dimension to be added

dimension_value

Required string. dimension value

dimension_attributes

Optional attributes of the new dimension like Description, Unit etc.

Returns:

The variable names and their dimensions in the multidimensional raster

# Usage Example: Adds a new dimension to the specified variable of multidimensional rasterraster1=Raster(r"/path/to/mult_dim.crf")raster1.add_dimension(variable="variable_name",new_dimension_name="new_dimension_name",dimension_value="dimension_value")
append_slices(md_raster:Raster|None=None)

Theappend_slices method appends the slices from another multidimensional raster.

Note

Theadd_dimension operation is not supported on image services

Parameter

Description

md_raster

Required multidimensional raster. The multidimensional raster containingthe slices to be appended.

This raster must have the same variables, with the same dimension names,as the target raster. The cell sizes, extents, and spatial referencesystems must also match.

The slices in this raster must be for dimension values that followthe dimension values of the slices in the target raster.

If a variable has two dimensions, slices will be appended alongone dimension. The other dimension must have the same number ofslices as the dimension in the target raster.

For example, if a salinity variable contains slices over time anddepth dimensions, time slices can be appended to another salinitymultidimensional raster but only if the same number of depth slicesexist in both rasters.

Return (string):

A string containing the variable names and the associated dimensions in the multidimensional raster.For example, if the resulting raster has 10 time slices with precipitation data, it will return ‘prcp(StdTime=10)’.

# Usage Example: Append slices to target raster from source multidimensional rastertarget_raster.append_slices(md_raster=source_raster_obj)
propertyband_count

Theband_count property returns the band count of the raster

Returns:

An integer

propertyband_names

Theband_names property returns the band names of the raster

Returns:

The band names as a List of Strings

propertyblock_size

Theblock_size property returns the block size of the raster

Returns:

A tuple

propertycatalog_path

Thecatalog_path property represents the full path and the name of the referenced raster.

Returns:

A String

propertycatalog_paths

Thecatalog_paths property represents the full paths and the names of each item comprising a mosaic dataset.

Returns:

A list of paths of each item comprising a mosaic dataset.

propertycolumns

Thecolumns property returns the number of columns in the raster.

Returns:

An integer

propertycompression_type

Thecompression_type property returns the compression type of the raster.

Returns:

A string

draw_graph(show_attributes:bool=False,graph_size:str='14.25,15.25')

Thedraw_graph method displays a structural representation of the function chain and it’s raster inputvalues. Ifshow_attributes is set toTrue, then thedraw_graph function also displays the attributesof all the functions in the function chain, representing the rasters in a blue rectangularbox, attributes in green rectangular box and the raster function names in yellow.

Parameter

Description

show_attributes

Optional boolean. If True, the graph displayed includes all theattributes of the function and not only it’s function name and rasterinputsSet to False by default, to display only the raster function name andthe raster inputs to it.

graph_size

Optional string. Maximum width and height of drawing, in inches,seperated by a comma. If only a single number is given, this is usedfor both the width and the height. If defined and the drawing islarger than the given size, the drawing is uniformly scaled down sothat it fits within the given size.

Returns:

A Graph

# Usage Example 1: Draws the function chain applied on the Raster object created from an Image service.service_url=gis.content.search("my_image_service",item_type="Imagery Layer")[0].urlraster=Raster(service_url,gis=gis)grayscale_raster=grayscale(raster=raster)invert_raster=boolean_not(rasters=[grayscale_raster])invert_raster.draw_graph(show_attributes=True)# Usage Example 2:  Draws the function chain applied on the Raster object created from local datasetraster=Raster(r"/path/to/raster")ndvi_raster=ndvi(raster=raster,band_indexes="5 6")ndvi_raster.draw_graph(show_attributes=True)
export_image(bbox:dict[str,Any]|str|None=None,image_sr:str|SpatialReference|None=None,bbox_sr:str|SpatialReference|None=None,size:list[int]|None=None,time:str|list[int]|date|datetime|None=None,export_format:str='jpgpng',pixel_type:str|None=None,no_data:float|None=None,no_data_interpretation:str='esriNoDataMatchAny',interpolation:str|None=None,compression:str|None=None,compression_quality:int|None=None,band_ids:list[int]|None=None,mosaic_rule:dict[str,Any]|None=None,rendering_rule:dict[str,Any]|None=None,f:str='image',save_folder:str|None=None,save_file:str|None=None,compression_tolerance:float|None=None,adjust_aspect_ratio:bool|None=None,lerc_version:int|None=None)

Theexport_image operation is performed on a raster layer to visualise it.

Parameter

Description

bbox

Optional dict or string. The extent (bounding box) of the exportedimage. Unless the bbox_sr parameter has been specified, the bbox isassumed to be in the spatial reference of the raster layer.The bbox should be specified as an arcgis.geometry.Envelope object,it’s json representation or as a list or string with thisformat: ‘<xmin>, <ymin>, <xmax>, <ymax>’If omitted, the extent of the raster layer is used

image_sr

Optional string, SpatialReference. The spatial reference of theexported image. The spatial reference can be specified as either awell-known ID, it’s json representation or as anarcgis.geometry.SpatialReference object.If the image_sr is not specified, the image will be exported in thespatial reference of the raster.

bbox_sr

Optional string, SpatialReference. The spatial reference of thebbox.The spatial reference can be specified as either a well-known ID,it’s json representation or as an arcgis.geometry.SpatialReferenceobject.If the image_sr is not specified, bbox is assumed to be in thespatial reference of the raster.(Available only when image_server engine is used)

size

Optional list. The size (width * height) of the exported image inpixels. If size is not specified, an image with a default size of400*450 will be exported.Syntax: list of [width, height]

time

Optional datetime.date, datetime.datetime or timestamp string. Thetime instant or the time extent of the exported image.Time instant specified as datetime.date, datetime.datetime ortimestamp in milliseconds since epochSyntax: time=<timeInstant>Time extent specified as list of [<startTime>, <endTime>]For time extents one of <startTime> or <endTime> could be None. ANone value specified for start time or end time will representinfinity for start or end time respectively.Syntax: time=[<startTime>, <endTime>] ; specified asdatetime.date, datetime.datetime or timestamp(Available only when image_server engine is used)

export_format

Optional string. The format of the exported image. The defaultformat is jpgpng. The jpgpng format returns a JPG if there are notransparent pixels in the requested extent; otherwise, it returns aPNG (png32).Values: jpgpng,png,png8,png24,jpg,bmp,gif,tiff,png32,bip,bsq,lerc

pixel_type

Optional string. The pixel type, also known as data type, pertainsto 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.(Available only when image_server engine is used)

no_data

Optional float. The pixel value representing no information.(Available only when image_server engine is used)

no_data_interpretation

Optional string. Interpretation of the no_data setting. The defaultis NoDataMatchAny when no_data is a number, and NoDataMatchAll whenno_data is a comma-delimited string: NoDataMatchAny,NoDataMatchAll.(Available only when image_server engine is used)

interpolation

Optional string. The resampling process of extrapolating the pixelvalues while transforming the raster dataset when it undergoeswarping or when it changes coordinate space.One of: RSP_BilinearInterpolation, RSP_CubicConvolution,RSP_Majority, RSP_NearestNeighbor(Available only when image_server engine is used)

compression

Optional string. Controls how to compress the image when exportingto TIFF format: None, JPEG, LZ77. It does not control compression onother formats.(Available only when image_server engine is used)

compression_quality

Optional integer. Controls how much loss the image will be subjectedto by the compression algorithm. Valid value ranges of compressionquality are from 0 to 100.(Available only when image_server engine is used)

band_ids

Optional list. If there are multiple bands, you can specify a singleband 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](Available only when image_server engine is used)

mosaic_rule

Optional dict. Specifies the mosaic rule when defining howindividual images should be mosaicked. When a mosaic rule is notspecified, the default mosaic rule of the image layer will be used(as advertised in the root resource: defaultMosaicMethod,mosaicOperator, sortField, sortValue).

rendering_rule

Optional dict. Specifies the rendering rule for how the requestedimage should be rendered.

f

Optional string. The response format. default is jsonValues: json,image,kmz,numpy_array

Note: If f=”numpy_array” and if the raster is a single or multiband raster,the dimensions of the array will be rows, columns, and number of bands.If the raster is a multidimensional raster, the dimensions of the arraywill be number of slices, rows, columns, and number of bands.LERC needs to be installed to export image service as numpy array.

If f=”image”, the bytes of the exported image arereturned unless save_folder and save_file parameters are alsopassed, in which case the image is written to the specified file(Available only when image_server engine is used)

save_folder

Optional string. The folder in which the exported image is savedwhen f=image(Available only when image_server engine is used)

save_file

Optional string. The file in which the exported image is saved whenf=image(Available only when image_server engine is used)

compression_tolerance

Optional float. Controls the tolerance of the lerc compressionalgorithm. The tolerance defines the maximum possible error of pixelvalues in the compressed image.Example: compression_tolerance=0.5 is loseless for 8 and 16 bitimages, but has an accuracy of +-0.5 for floating point data. Thecompression tolerance works for the LERC format only.(Available only when image_server engine is used)

adjust_aspect_ratio

Optional boolean. Indicates whether to adjust the aspect ratio ornot. By default adjust_aspect_ratio is true, that means the actualbbox will be adjusted to match the width/height ratio of sizeparamter, and the response image has square pixels.(Available only when image_server engine is used)

lerc_version

Optional integer. The version of the Lerc format if the user setsthe format as lerc.Values: 1 or 2If a version is specified, the server returns the matching version,or otherwise the highest version available.(Available only when image_server engine is used)

Returns:

The raw raster data

# Usage Example: Creates Raster object from a local dataset location and exports the image.raster_source=Raster(r"/path/to/raster")raster_source.export_image(size=[1000,1000])
propertyextent

Get/Set the area of interest. Used for displaying theRaster when queried.

Returns:

The extent of the Raster as a dictionary

propertyformat

Theformat property returns the raster format.

Returns:

A string

staticfrom_stac_item(stac_item:str|Item,request_params:dict[str,Any]|None=None,engine:dict[str,Any]|None=None,context:dict|None=None,*,gis:GIS|None=None)

Thefrom_stac_item method creates a Raster object from aSpatioTemporal Asset Catalog (STAC) Item.

Parameter

Description

stac_item

Required string orpystac.Item object. If string, then it should bethe URL of the STAC item. It can be a Static STAC item URL or a STACAPI Item URL.

Note

STAC items from the following STAC APIs are supported:

  • https://planetarycomputer.microsoft.com/api/stac/v1 (Following collections are supported: daymet-annual-pr, daymet-daily-hi, 3dep-seamless, 3dep-lidar-dsm, sentinel-1-rtc, gridmet, daymet-annual-na, daymet-monthly-na, daymet-annual-hi, daymet-monthly-hi, daymet-monthly-pr, hgb, cop-dem-glo-30, cop-dem-glo-90, terraclimate, gnatsgo-rasters, 3dep-lidar-hag, 3dep-lidar-intensity, 3dep-lidar-pointsourceid, mtbs, noaa-c-cap, alos-fnf-mosaic, 3dep-lidar-returns, mobi, landsat-c2-l2, chloris-biomass, daymet-daily-pr, 3dep-lidar-dtm-native, 3dep-lidar-classification, 3dep-lidar-dtm, gap, alos-dem, jrc-gsw, hrea, sentinel-2-l2a, daymet-daily-na, nrcan-landcover, ecmwf-forecast, noaa-mrms-qpe-24h-pass2, sentinel-1-grd, nasadem, io-lulc, landsat-c2-l1, drcog-lulc, chesapeake-lc-7, chesapeake-lc-13, chesapeake-lu, noaa-mrms-qpe-1h-pass1, noaa-mrms-qpe-1h-pass2, noaa-nclimgrid-monthly, usda-cdl, esa-cci-lc, esa-cci-lc-netcdf, noaa-climate-normals-netcdf, noaa-climate-normals-gridded, io-lulc-9-class, io-biodiversity, naip, noaa-cdr-sea-surface-temperature-whoi, noaa-cdr-ocean-heat-content, noaa-cdr-sea-surface-temperature-whoi-netcdf, sentinel-3-olci-wfr-l2-netcdf, noaa-cdr-ocean-heat-content-netcdf, sentinel-3-synergy-v10-l2-netcdf, sentinel-3-olci-lfr-l2-netcdf, sentinel-3-slstr-lst-l2-netcdf, sentinel-3-slstr-wst-l2-netcdf, sentinel-3-synergy-syn-l2-netcdf, sentinel-3-synergy-vgp-l2-netcdf, sentinel-3-synergy-vg1-l2-netcdf, esa-worldcover, modis-64A1-061, modis-17A2H-061, modis-11A2-061, modis-17A2HGF-061, modis-17A3HGF-061, modis-09A1-061, modis-16A3GF-061, modis-21A2-061, modis-43A4-061, modis-09Q1-061, modis-14A1-061, modis-13Q1-061, modis-14A2-061, modis-15A2H-061, modis-11A1-061, modis-15A3H-061, modis-13A1-061, modis-10A2-061, modis-10A1-061, aster-l1t)

  • https://earth-search.aws.element84.com/v0 (All collections are suported)

  • https://earth-search.aws.element84.com/v1 (All collections are suported)

  • https://services.sentinel-hub.com/api/v1/catalog (All collections are suported)

  • https://landsatlook.usgs.gov/stac-server (All collections are suported)

  • https://geoportalstac.azurewebsites.net/stac (All collections are suported)

  • https://gpt.geocloud.com/sentinel/stac (All collections are suported)

STAC items from the following Static Catalogs (and their underying Child Catalogs) are supported:

Example:

https://planetarycomputer.microsoft.com/api/stac/v1/collections/naip/items/tx_m_2609719_se_14_060_20201217

request_params

Optional dictionary. This parameter can be used to set the propertiesfor making the STAC Item request. These are therequests.get() methodparameters and values will be specified in dictionary format.

This parameter is honoured when the stac_item parameter is set to a string (URL).
Example:

{“verify”:False}

engine

Optional string. The backend engine to be used for Raster processing.

Possible options:
  • “arcpy” : Use the arcpy engine for processing.

  • “image_server” : Use the Image Server engine for processing (This is the default).

Example:

“image_server”

Note

When usingimage_server engine, RasterRendering service should be enabled in the active GIS connection.

context

Optional dictionary. Additional properties to control the creation of the Raster object.

Possible options:
  • assetManagement: Specifies how to manage and select assets for your Raster object.

    If multiple assets are selected, the raster will be composed of multiband rastersfrom those selected asset types.

    Type: List, String or Dictionary

    Format:When working with individual assets, the asset key can be specified directly (Eg: “B02”, {“key”: “B02”})Else it could be a list. Each item in the list represents an asset key or identifier. Items inside the listcan either be strings representing the asset key directly, or dictionaries providingadditional details for locating the asset.

    The following keys could be used to provide the additional information of the assets (through individual dictionaries):

    • key: A string representing the unique identifier for an asset. For example: “red”.

    • path: A dictionary representing the hierarchy of keys to navigate to the asset. For example: [“alternate”, “s3”]

    • hrefKey: A string representing the key to access the asset URL. If different from the default “href” key, it should be specified here. For example: “msft:https-url”.

    Usage examples:
    • “red”

    • [“red”, “green”, “blue”]

    • {“key”: “tasmin”, “hrefKey”: “msft:https-url”}

    • [{“key”: “TRAD”, “path”: [“alternate”, “s3”]}, {“key”: “DRAD”, “path”: [“alternate”, “s3”]}]

    Example:

    {"assetManagement":["red","blue"]}
  • processingTemplate: Specifies the processing template to be applied to the raster.

    Supported for selected collections and raster types. Read more about this in theSatellite sensor raster types documentation.

    Type: String

    Default: “Multiband” (for supported raster types only else None)

    Example:

    {"processingTemplate":"Surface Reflectance"}

gis

OptionalGIS object. The GIS of the Raster object.

Tip

get_stac_info() method can be used beforehand to gather necessary STAC information,which can then be used to create Raster objects with this method.

Returns:

ARaster object

# Usage Example 1: Construct a raster object from NAIP data accesible through# Planetary Computer STAC APInaip_pc_ras=Raster.from_stac_item(stac_item="https://planetarycomputer.microsoft.com/api/stac/v1/collections/naip/items/tx_m_2609719_se_14_060_20201217")# Usage Example 2: Construct a raster object from a pystac.Item object created using# Sentinel-2 L2A data accesible through Earth Search STAC APIitem_url="https://earth-search.aws.element84.com/v1/collections/sentinel-2-l2a/items/S2B_37TCM_20240219_0_L2A"item=pystac.Item.from_file(item_url)pystac_s2_ras=Raster.from_stac_item(stac_item=item,gis=gis)# Usage Example 3: Construct a raster object from Landsat C2-L2 data accesible through USGS# LandsatLook STAC API (with custom processing template selection) - Requires a registered cloudStore.qa_landsat_ras=Raster.from_stac_item(stac_item="https://landsatlook.usgs.gov/stac-server/collections/landsat-c2l2-sr/items/LC09_L2SP_088084_20230729_20230801_02_T2_SR",context={"processingTemplate":"QA",},)# Usage Example 4: Construct a raster object from Landsat C2-L2 data accesible through USGS# LandsatLook STAC API (with custom asset selection) - Requires a registered cloudStore.rad_landsat_ras=Raster.from_stac_item(stac_item="https://landsatlook.usgs.gov/stac-server/collections/landsat-c2l2alb-st/items/LC09_L2SP_072022_20230729_20230801_02_A1_ST",gis=gis,context={"assetManagement":[{"key":"TRAD","path":["alternate","s3"]},{"key":"DRAD","path":["alternate","s3"]},],},)# Usage Example 5: Construct a raster object from CBERS data accesible through# CBERS/AMAZONIA on AWS (static) STAC (with custom asset selection) - Requires a registered cloudStore.cbers_ras=Raster.from_stac_item(stac_item="https://br-eo-stac-1-0-0.s3.amazonaws.com/CBERS4/MUX/043/076/CBERS_4_MUX_20230630_043_076_L2.json",context={"assetManagement":["B7","B6","B5"]},)
get_colormap(variable_name:str|None=None)

Theget_colormap method retrieves the color map of the raster.

Note

If the raster is multidimensional, returns the color map of a variable.

Parameter

Description

variable_name

Optional string. The variable name of the multidimensional raster.If a variable is not specified and the raster is multidimensional,the color map of the first variable will be returned.

Returns:

A dictionary representing the colormap of the raster or the given variable.

# Usage Example: Returns the colormap of specificied variable of a multidimensional rasterraster1.get_colormap(variable_name="variable_name")
get_dimension_attributes(variable_name:str,dimension_name:str)

Theget_dimension_attributes method retrieves the attribute information of a dimension within a variable,such as min value, max value, unit, etc.

Parameter

Description

variable_name

Required string. the name of the variable

dimension_name

Required string. the name of the dimension

Returns:

A dictionary. The attribute information of the given dimension within the given variable.

# Usage Example: Returns specified dimension attribute dictionary for given variableraster1.get_dimension_attributes(variable_name="variable_name",dimension_name="dimension_name")
get_dimension_names(variable_name:str)

Theget_dimension_names method retrieves a list of the dimension names that the variable contains.

Parameter

Description

variable_name

Required string. the name of the variable

Returns:

A list. The dimension names that the given variable contains.

# Usage Example: Returns the list of the dimension names that the variable "variable_name" containsraster1.get_dimension_names(variable_name="variable_name")
get_dimension_values(variable_name:str,dimension_name:str,return_as_datetime_object:bool=False)

Theget_dimension_values method retrieves a list of values along the given dimension within thegiven variable.

Parameter

Description

variable_name

Required string. the name of the variable

dimension_name

Required string. the name of the dimension

return_as_datetime_object

Set to True, to return the dimension values as datetime object.Valid only if the dimension name is StdTime

Returns:

A list. The dimension values along the given dimension within the given variable.

# Usage Example: Returns the values of a given dimension associated with the given variable.raster1.get_dimension_values(variable_name="variable_name",dimension_name="dimension_name")
get_histograms(variable_name:str|None=None)

Theget_histograms method retrieves the histograms of the raster.

Note

If the raster is multidimensional, it returns the histogram of a variable.If the raster is multiband, it returns the histogram of each band.

Parameter

Description

variable_name

Optional string. The variable name of the multidimensional raster dataset.If a variable is not specified and the raster is multidimensional,the histogram of the first variable will be returned.

Returns:

A list of dictionaries. The histogram values of the raster or variable.

# Usage Example: Returns the histograms of the rasterraster1.get_histograms()
get_property(property_name:str)

Theget_property method returns the value of the given property.

Parameter

Description

property_name

Required string. the name of the property

Returns:

A string.

# Usage Example 1: Returns value of the propertyraster2.get_property(property_name="property_name")
get_raster_bands(band_ids_or_names:list[str]|None=None)

Theget_raster_bands method returns aRaster object for each band specified in amultiband raster.

Parameter

Description

band_ids_or_names

Required list. The index number (uses one-based indexing) or names of the bands to return asRaster objects. If not specified, all bands will be extracted.

Returns:

A list ofRaster objects (or a singleRaster object if only one band is specified)

# Usage Example: Generates the raster pertaining to the first bandraster1=Raster(r"./data/Amberg.tif")raster1.get_raster_bands(band_ids_or_names=[1])
get_statistics(variable_name:str|None=None)

Theget_statistics method retrieves the statistics of the raster.

Note

If the raster is multidimensional, returns the statistics of a variable.

Parameter

Description

variable_name

Optional string. The variable name of the multidimensional raster dataset.If a variable is not specified and the raster is multidimensional,the statistics of the first variable will be returned.

Returns:

A dictionary. The statistics of the raster or the given variable.

# Usage Example: Returns the statistics of the rasterraster1.get_statistics()
get_variable_attributes(variable_name:str)

Theget_variable_attributes method returns the attribute information of a variable, such asdescription, unit, etc.

Parameter

Description

variable_name

Required string. the name of the variable

Returns:

A dictionary. The attribute information of the given variable.

# Usage Example: Returns variable attribute informationraster1.get_variable_attributes(variable_name="variable_name")
propertyhas_RAT

Thehas_RAT property identifies if there is an associated attribute table:True if an attribute table exists, orFalse if no attribute table exists.

Returns:

A boolean

propertyheight

Theheight property returns height of the raster in the units of its spatial reference.

Returns:

A float representing the height

propertyis_integer

Theis_integer property returnsTrue if the raster has integer type.

Returns:

A boolean

propertyis_multidimensional

Theis_multidimensional property returnsTrue if the raster is multidimensional.

Returns:

A boolean

propertyis_temporary

Theis_temporary property returnsTrue if the raster is temporary, orFalse if it is permanent.

Returns:

A boolean

propertymaximum

Themaximum property returns the maximum value in the referenced raster.

Returns:

A float

propertymean

Themean property returns the mean value in the referenced raster.

Returns:

A float

propertymean_cell_height

Themean_cell_height property returns the cell size in the y direction.

Returns:

A float

propertymean_cell_width

Themean_cell_width property returns the cell size in the x direction.

Returns:

A float

propertyminimum

Theminimum property returns minimum value in the referenced raster.

Returns:

A float

propertymultidimensional_info

Themultidimensional_info property returns the multidimensional information of the raster dataset,including variable names, descriptions and units, and dimension names, units, intervals, units, and ranges.

propertyname

Thename property returns the name of the raster.

Returns:

A String

propertynames

Thenames property returns the names of each item comprising a mosaic dataset.

Returns:

A list of names of each item comprising a mosaic dataset.

propertyno_data_value

Theno_data_value property returns theNoData value of the raster.

Returns:

TheNoData value

propertyno_data_values

Theno_data_values property returns theNoData value for each band in the multiband raster.

Returns:

A list ofNoData values

propertypath

Thepath property represents the full path and name of the referenced raster.

Returns:

A string

propertypixel_type

Thepixel_type property returns the pixel type of theRaster object.

Returns:

The pixel type

plot_histograms(geometry:Geometry|Polygon|Envelope|None=None,pixel_size:str|dict[str,float]|None=None,time:str|list[int]|date|datetime|None=None,bands:list[int]=[],display_stats:bool=True,plot_properties:dict[str,Any]|None=None,subplot_properties:list[dict[str,Any]]|dict[str,Any]|None=None)

Theplot_histograms method plots the image histograms of a raster.

Image histograms visually summarize the distribution of a continuous numeric variable by measuringthe frequency at which certain values appear in the image. The x-axis in the image histogram is a number line that displays the range of image pixel values that has been split into number ranges, or bins. A bar is drawn for each bin, and the width of the bar represents the density number range of the bin; the height of the bar represents the number of pixels that fall into that range. Understanding the distribution of your data is an important step in the data exploration process.

plot_histograms can be used for plotting the band-wise image histogram charts of anyRaster object.

Parameter

Description

geometry

OptionalGeometry (PolygonorEnvelope).A geometry that defines the geometry within which the histogram is computed.

If not provided, then the full extent of theraster will be used for the computation.

Note: This parameter is honoured if the raster usesimage_server engine.

pixel_size

Optional string or dictionary. The pixel level being used (or theresolution being looked at). If pixel size is not specified, thenpixel_size will default to the base resolution of the dataset.The structure of the pixel_size parameter is the same as thestructure of the point object returned by the ArcGIS REST API.In addition to the dictionary structure, you can specify the pixel sizewith a comma-separated string.

Syntax:- dictionary structure: pixel_size={point}- Point simple syntax: pixel_size=’<x>,<y>’Examples:- pixel_size={“x”: 0.18, “y”: 0.18}- pixel_size=’0.18,0.18’

Note: This parameter is honoured if the raster uses “image_server” engine.

time

Optional datetime.date, datetime.datetime or timestamp string. Thetime instant or the time extent to compute statistics and histograms.Time instant specified as datetime.date, datetime.datetime ortimestamp in milliseconds since epochSyntax: time=<timeInstant>

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

Added at 10.8

Note: This parameter is honoured if the raster uses “image_server” engine.

bands

Optional list of band indices. By default takes the first band (band index - 0).Image histogram charts are plotted for these specific bands.

Example:
  • [0,2,3]

display_stats

Optional boolean. Specifies whether to plot the band-wise statisticsalong with the histograms.

Some basic descriptive statistics are calculated and displayed onhistograms. The mean and median are displayed with one line each, andone standard deviation above and below the mean is displayed using two lines.

  • False - The statistics will not be displayed along with the histograms.

  • True - The statistics will be displayed along with the histograms. This is the default.

plot_properties

Optional dictionary. This parameter can be used to set the figureproperties. These are thematplotlib.pyplot.figure()parameters and values specified in dictionary format.

Example:
  • {“figsize”:(15,15)}

subplot_properties

Optional list or dictionary. This parameter can be used to set band-wisehistogram (subplot) display properties. These are thematplotlib.axes.Axes.bar()parameters and values specified in dictionary format.

Example:
  • [
{“color”:”r”},
{“color”:”g”},
{“color”:”b”,”edgecolor”:”w”}
]

Note:matplotlib.axes.Axes.bar()parameters: ‘’x’, ‘height’ or ‘align’ cannot be passed into subplot_properties.

Tip

When working with multidimensional rasters, you can use themultidimensional_filter()raster function on the Raster object for slicing the data along defined variables and dimensions.plot_histograms can then be used on the output raster returned upon applying the filter.

Returns:

None

# Usage Example: Plots histograms of the raster with specified resolution and bandsraster1.plot_histograms(pixel_size="0.18, 0.18",bands=[1,2,3])
propertyproperties

Theproperties property returns the property name and value pairs in the referenced raster.

Returns:

A dictionary

propertyraster_info

Theraster_info property returns information about theRaster such asbandCount,extent,pixelSizeX,pixelSizeY,pixelType.

Returns:

The raster info

read(upper_left_corner:tuple[int]=(0,0),origin_coordinate:tuple[int]=None,ncols:int=0,nrows:int=0,nodata_to_value:int|None=None,cell_size:tuple[int]|None=None)

Theread method reads a numpy array from the callingRaster object.

Parameter

Description

upper_left_corner

2-D tuple. a tuple with 2 values representing the number of pixels along x and ydirection relative to the origin_coordinate. E.g., (2, 0), means thatthe real origin to extract the array is 2 pixels away in xdirection from the origin_coordinate

origin_coordinate

2-d tuple (X, Y). The x and y values are in map units.If no value is specified, the top left corner of the calling raster,

ncols

Integer. the number of columns from the real origin in the callingraster to convert to the NumPy array.If no value is specified, the number of columns of the calling rasterwill be used. Default: None

nrows

Integer. the number of rows from the real origin in the callingraster to convert to the NumPy array.If no value is specified, the number of rows of the calling rasterwill be used. Default: None

nodata_to_value

Numeric. pixels with nodata values in the raster would be assignedwith the given value in the NumPy array. If no value is specified,the NoData value of the calling raster will be used. Default: None

cell_size

2-D tuple. a tuple with 2 values shows the x_cell_size and y_cell_size,e.g., cell_size = (2, 2).if no value is specified, the original cell size of the calling rasterwill be used. Otherwise, pixels would be resampled to the requested cell_size

Returns:

A numpy.ndarray. If self is a multidimensional raster, the array has shape (slices, height, width, bands)

# Usage Example: Reads a numpy array from (2, 2) pixels away from the origin of the rasterraster1.read(upper_left_corner=(2,2))
propertyread_only

Theread_only property returns whether the raster cell values are writable or not using the [row, column]notation.When this property isTrue, they are not writable. Otherwise, they are writable.

Returns:

A boolean

refresh_service(options:str=None,future:bool=True)str

Refresh Service is a task in the existing out-of-the-boxPublishing Tools geoprocessing service used by the service publisherto refresh a GIS service to reflect back-end data changes.

remove_variables(variable_names:list[str])

Theremove_variables method removes the given variables.

Note

Theremove_variables operation is not supported on image services.

Parameter

Description

variable_names

Required list. the list of variables to be removed

Returns:

A List. A list of all variables.

# Usage Example: Removes specified variable and returns the list of remaining variables in the raster dataset.raster1.remove_variables(variable_names=["variable_name_1","variable_name_2"])
rename_variable(current_variable_name:str,new_variable_name:str)

Therename_variable method renames the given variable name.

Note

Therename_variable operation is not supported on image services.

Parameter

Description

current_variable_name

Required string. the name of the variable to be renamed

new_variable_name

Required string. the new variable name

Returns:

A List. The dimension names that the given variable contains

# Usage Example: Rename variable nameraster1.rename_variable(current_variable_name="current_variable_name",new_variable_name="new_variable_name")
propertyrows

Therows property returns the number of rows in the raster.

Returns:

An integer

save(output_name:str|None=None,for_viz:bool=False,process_as_multidimensional:bool|None=None,build_transpose:bool|None=None,gis:GIS|None=None,future:bool=False,estimate:bool=False,**kwargs)

When run using image_server engine,save method persists thisRaster to theGIS as anImageryLayer item.

Iffor_viz isTrue, a newItem is created that uses the applied rasterfunctions for visualization at display resolution using on-the-fly image processing.Iffor_viz isFalse, distributed raster analysis is used for generating a new raster informationproduct by applying raster functions at source resolution across the extent of the output imagery layer.

Note

When run using arcpy engine,save persists this raster to location specified inoutput_name.

Parameter

Description

output_name

Optional string.

When run using image_server engine, specify output name.If not provided, an Imagery Layer item is createdby the method and used as the output.You can pass in the name of the output raster that should becreated by this method to be used as the output for the tool.Alternatively, if for_viz is False, you can pass in an existingImage Layer Item from your GIS to use that instead.A RuntimeError is raised if a layer by that name already exists

When run using arcpy engine, output_name is the name stringrepresenting the output location.

for_viz

Optional boolean. If True, a new Item is created that uses theapplied raster functions for visualization at display resolutionusing on-the-fly image processing.If for_viz is False, distributed raster analysis is used forgenerating a new raster information product for use in analysis andvisualization by applying raster functions at source resolutionacross the extent of the output raster.

(Available only when image_server engine is used)

process_as_multidimensional

Optional bool. If the input is multidimensional raster, the outputwill be processed as multidimensional if set to True

build_transpose

Optional bool, if set to true, transforms the outputmultidimensional raster. Valid only if process_as_multidimensionalis set to True

gis

Optional arcgis.gis.GIS object. The GIS to be used for saving theoutput. Keyword only parameter.

(Available only when image_server engine is used)

future

Optional boolean. If True, the result will be a GPJob object andresults will be returned asynchronously. Keyword only parameter.

(Available only when image_server engine is used)

estimate

Keyword only parameter. Optional Boolean. If True, the number of credits needed to run the operation will be returned as a float.Available only on ArcGIS Online.

folder

Optional string or dictionary. Creates a folder in the portal, if it doesnot exist, with the given folder name and persists the output in this folder.The properties property on the Folder object returned by thecreate() can also be passed in as input.

(Available only when image_server engine is used)

Example:

{‘username’: ‘user1’, ‘id’: ‘6a3b77c187514ef7873ba73338cf1af8’, ‘title’: ‘trial’}

tiles_only

In ArcGIS Online, the default output image service for this function would be a Tiled Imagery Layer.

To create Dynamic Imagery Layer as output on ArcGIS Online, set tiles_only parameter to False.

Function will not honor tiles_only parameter in ArcGIS Enterprise and will generate Dynamic Imagery Layer by default.

(Available only when image_server engine is used)

Returns:

A String representing the location of the output data

# Usage Example 1: Saves the local raster output to a new location (usecase for arcpy engine rasters)raster1.save(output_name=r"/path/to/output_location/raster.crf",process_as_multidimensional=True)# Usage Example 2: Saves the raster to the active GIS as an Imagery Layer Item (usecase for image_server engine rasters)raster2.save(output_name="output_imagery_layer_name",folder="my_rasters",gis=gis)
set_colormap(color_map:str|dict[str,Any],variable_name:str|None=None)

Theset_colormap method sets the color map for the raster.

Note

  • If the raster is multidimensional, it sets the color map for a variable.

  • Theset_colormap operation is not supported on image services

Parameter

Description

color_map

Optional (string, dict): The color map to apply to the raster. Thiscan be a string indicating the name of the color map or color rampto use, for example, NDVI or Yellow To Red, respectively. This canalso be a Python dictionary with a custom color map or color rampobject.

For example:

customized colormap object, e.g., {‘values’: [0, 1, 2, 3, 4, 5, 6], ‘colors’: [‘#000000’, ‘#DCFFDF’, ‘#B8FFBE’, ‘#85FF90’, ‘#50FF60’,’#00AB10’, ‘#006B0A’]}

colorramp name, e.g., “Yellow To Red”

colormap name, e.g., “NDVI”

customized colorramp object, e.g., {“type”: “algorithmic”, “fromColor”: [115, 76, 0, 255],”toColor”: [255, 25, 86, 255], “algorithm”: “esriHSVAlgorithm”}

variable_name

Optional string. The variable name of the multidimensional raster dataset.If a variable is not specified and the raster is multidimensional, the colormap of the first variable will be set.

Returns:

None

# Usage Example: Sets "NDVI" color map for the rasterraster1.set_colormap(color_map="NDVI")
set_engine(engine)

Theset_engine method can be used to change the back end engine of theRasterobject.

set_histograms(histogram_obj:list[dict[str,float]],variable_name:str|None=None)

Theset_histograms method sets the histogram for the raster or a given variable, if the raster ismultidimensional.

Note

Theset_histograms operation is not supported on image services

Parameter

Description

histogram_obj

Optional list of histogram objects(dict),

If the raster is multiband, the histogram for each band will be setwith each dictionary in the list. The first band will use the histogramin the first dictionary. The second band will use the histogram inthe second dictionary, and so on.

size - The number of bins in the histogram

min - The minimum pixel value

max - The maximum pixel value

counts - A list containing the number of pixels in each bin, in the order of bins

For example:

[{‘size’: number_of_bins, ‘min’: min_val, ‘max’: max_val, ‘counts’: [pixel_count_at_each_bin, …]}, …]

variable_name

Optional string. The variable name of the multidimensional raster dataset.If a variable is not specified and the raster is multidimensional,the histogram will be set for the first variable.

Returns:

None

# Usage Example: Sets specified histograms for the rasterraster1.set_histograms(histogram_obj=[{"size":number_of_bins,"min":min_val,"max":max_val,"counts":[pixel_count_at_each_bin]}])
set_property(property_name:str,property_value:str)

Theset_property method adds a customized property to the raster. If the property name exists,the existing property value will be overwritten.

Note

Theset_property operation is not supported on image services

Parameter

Description

property_name

Required string. The property name of the raster

property_value

Required string. The value to assign to the property.

Returns:

None

# Usage Example: Add user-defined property name and value to rasterraster1.set_property(property_name="property_name",property_value="property_value")
set_statistics(statistics_obj:list[dict[str,float]]|None,variable_name:str|None=None)

Theset_statistics method sets the statistics for the raster.If the raster is multiband, it sets the statistics for each band.If the raster is multidimensional, it sets the statistics for a variable.

Note

Theset_statistics operation is not supported on image services.

Parameter

Description

statistics_obj

Optional list of statistics objects. A list of Python dictionaries containing statistics and correspondingvalues to set. For example, [{‘min’: 10, ‘max’: 20}] sets the minimumand maximum pixel values.

If the raster is multiband, the statistics for each band will be set witheach dictionary in the list. The first band will use the statistics in thefirst dictionary. The second band will use the statistics in the seconddictionary, and so on.

min - The minimum pixel valuemax - The maximum pixel valuemean - The mean pixel valuemedian - The median pixel valuestandardDeviation - The standard deviation of the pixel valuescount - The total number of pixelsskipX - The horizontal skip factorskipY - The vertical skip factor

For example:

[{‘min’: val, ‘max’: val, ‘mean’: val, ‘standardDeviation’: val,‘median’: val, ‘mode’: val, ‘count’: val}, …]

variable_name

Optional string. The variable name of the multidimensional raster.If a variable is not specified and the raster is multidimensional,the statistics of the first variable will be set.

Returns:

None

# Usage Example: Sets statistics of the rasterraster1.set_statistics(statistics_obj=[{"min":val,"max":val,"mean":val,"standardDeviation":val}],variable_name="variable_name")
set_variable_attributes(variable_name:str,variable_attributes:dict[str,Any])

Theset_variable_attributes method sets the attribute information of a variable in a multidimensional raster.For example, description, unit, and so on.

Note

Theset_variable_attributes operation is not supported on image services

Parameter

Description

variable_name

Required string. The variable name of the multidimensional raster dataset.

variable_attributes

Required dict that contains attribute information to replace the currentattribute information of the variable.

For example:

{“Description”: “Daily total precipitation”, “Unit”: “mm/day”}.

Returns:

The attribute information of the variable as a dictionary

# Usage Example: Sets variable attributes to the specified variableraster1.set_variable_attributes(variable_name="variable_name",variable_attributes={"attribute_1":"value_1","attribute_2":"value_2"})
propertyslices

Theslices property returns the attribute information of each slice,including its variable name, dimension names, anddimension values returned as a list of dictionaries.

Returns:

A list of dictionaries

propertyspatial_reference

Thespatial_reference property returns the spatial reference of the referenced raster.

Returns:

A spatial reference

propertystandard_deviation

Thestandard_deviation property returns the standard deviation of the values in the referenced raster.

Returns:

A float

summarize(geometry:Geometry|Polygon|Envelope,pixel_size:str|dict[str,float]|None=None)

Thesummarize method retrieves the statistics of aRaster for a given geometry.

Parameter

Description

geometry

RequiredGeometry (PolygonorEnvelope).A geometry that defines the geometry within which the statistics are computed.

pixel_size

Optional string or dict. The pixel level being used (or theresolution being looked at). If pixel size is not specified, thenpixel_size will default to the base resolution of the dataset. Theraster at the specified pixel size in the mosaic dataset will beused for histogram calculation.

Syntax:
  • dictionary structure: pixel_size={point}

  • Point simple syntax: pixel_size=’<x>,<y>’

Examples:
  • pixel_size={“x”: 0.18, “y”: 0.18}

  • pixel_size=’0.18,0.18’

Returns:

A dictionary. (Dictionary at each index represents the statistics of the corresponding band.)

[{
“min”: 0,
”max”: 9,
”mean”: 3.271703916996627,
”standardDeviation”: 1.961013669880657,
”median”: 4,
”mode”: 4,
”skipX”: 1,
”skipY”: 1,
”count”: 2004546
}]

# Usage Example: Summarize a raster at an area.stats=raster.summarize(geometry=geom_obj)mean_of_first_band=stats[0]["mean"]
propertyuncompressed_size

Theuncompressed_size property returns the size of the referenced raster dataset on disk.

Returns:

A float

propertyvariable_names

Thevariable_names property returns the variable names in the multidimensional raster.

Returns:

A List of variable names

propertyvariables

Thevariables property returns the variable names and their dimensions in the multidimensional rasterdataset.

For example, a multidimensional raster containing temperature data over 24 months wouldreturn the following: [‘temp(StdTime=24)’]

Returns:

A list of names and dimensions.

propertywidth

Thewidth property returns width of the raster in the units of its spatial reference.

Returns:

A float representing the width

write(array:ndarray,upper_left_corner:tuple[int]=(0,0),origin_coordinate:tuple[int]|None=None,value_to_nodata:int|None=None)

Thewrite method writes a numpy array to the callingRaster object.

Note

Thewrite operation is not supported on image services.

Parameter

Description

array

Required numpy.ndarray. the array must be in the shape of (slices,height, width, bands) for writing a multidimensional raster and(height, width bands) for writing a normal raster

upper_left_corner

2-D tuple.a tuple with 2 values representing the number of pixelsalong x and y direction that shows the position relative to theorigin_coordinate. E.g., (2, 0), means that the position from which thenumpy array will be written into the calling Raster is 2 pixels awayin x direction from the origin_coordinate.Default value is (0, 0)

origin_coordinate

2-D tuple (X, Y) from where the numpy array will be writteninto the calling Raster. The x- and y-values are in map units.If no value is specified, the top left corner of thecalling raster,

value_to_nodata

Numeric. The value in the numpy array assigned to be theNoData values in the calling Raster.

If no value is specified, the NoData value of the calling Raster willbe used. Default None

Returns:

None

# Usage Example: Write a numpy array (2, 2) pixels away from the origin to the rasterraster1.write(upper_left_corner=(2,2))

RasterCatalogItem

classarcgis.raster.RasterCatalogItem(url,imglyr,initialize=True)

TheRasterCatalogItem object represents a single catalog item on anImageryLayer.RasterCatalogItemis only to be used withImageryLayer objects that haveCatalog in the layer’scapabilities property.

Parameter

Description

url

required string. Web address to the catalog item.

imglyr

requiredImageryLayer. The imagery layer object.

initialize

optional boolean. Default isTrue. IfFalse, the properties of theitem will not be loaded until requested.

propertyics

The rasterics property returns the image coordinate system of theassociated raster in an image layer.

Note

The returned ics can be used as the SR parameter.

propertyics_to_pixel

Theics_to_pixel property returns coefficients to build up a mathematic model for geometrictransformation.

Note

With this transformation, ICS coordinates basedfrom the catalog item raster can be used to calculate the originalcolumn and row numbers on the corresponding image.

image(bbox:str,return_format:str='JSON',bbox_sr:str|SpatialReference|None=None,size:list[int]|None=None,image_sr:str|SpatialReference|None=None,image_format:str='png',pixel_type:str|None=None,no_data:float|None=None,interpolation:str|None=None,compression:int=75)

Theimage method returns a composite image for a singleraster catalog item. You can use this method for generatingdynamic images based on a single catalog item.This method provides information about the exported image, suchas its URL, width and height, and extent.

Note

Apart from the usual response formats of html and json, you canalso request a format called image for the image. When you specifyimage as the format, the server responds by directly streaming theimage bytes to the client. With this approach, you don’t get anyinformation associated with the image other than the actual image.

Parameter

Description

bbox

Required string. The extent (bounding box) of the exported image.Unless the bbox_sr parameter has been specified, the bbox is assumedto be in the spatial reference of the image layer.Syntax: <xmin>, <ymin>, <xmax>, <ymax>Example: bbox=-104,35.6,-94.32,41

return_format

Optional string. The response can either be IMAGER or JSON. Imagewill return the image file to disk where as the JSON value willThe default value is JSON.

bbox_sr

Optional string. The spatial reference of the bbox.

size

Optional string.The size (width * height) of the exported image inpixels. If the size is not specified, an image with a default sizeof 400 * 400 will be exported.Syntax: <width>, <height>Example: size=600,550

image_sr

Optional string/integer. The spatial reference of the image.

format

Optional string. The format of the exported image. The defaultformat is png.Values:png, png8, png24, jpg, bmp, gif

pixel_type

Optional string. The pixel type, also known as data type, thatpertains to the type of values stored in the raster, such as signedinteger, unsigned integer, or floating point. Integers are wholenumbers; floating points have decimals.Values:C128, C64, F32, F64, S16, S32, S8, U1, U16, U2, U32, U4,U8, UNKNOWN

no_data

Optional float. The pixel value representing no information.

interpolation

Optional string. The resampling process of extrapolating the pixelvalues while transforming the raster dataset when it undergoeswarping or when it changes coordinate space.Values:RSP_BilinearInterpolation,RSP_CubicConvolution, RSP_Majority, RSP_NearestNeighbor

compression

Optional integer. Controls how much loss the image will be subjectedto by the compression algorithm. Valid value ranges of compressionquality are from 0 to 100.

Returns:

A composite image

propertyimage_support_data

Theimage_support_data property returns image support data ofthe NITF based raster catalog item. Specifically, the Image SupportData resource returns the NITF file structure and contents in XMLformat to provide more detailed information about a particular NITF file.

propertyinfo

Theinfo property returns information about the associated rastersuch as its width, height, number of bands, and pixel type.

Returns:

Raster properties

propertykey_properties

Thekey_properties property returns key properties of theassociated raster in an imagery layer.

Returns:

Key properties of aRaster object

propertymetadata

Themetadata property returns metadata of the imagery layer or araster catalog item.

Note

The output format is always XML.

Returns:

Metadata in XML format

propertyproperties

Theproperties property retrieves the object’s properties.

Returns:

Raster properties

propertysensor

Thesensor property returns information about the sensor.Example:{

“name”: “IdentityXform”,“sensor_provider”: “esri”

}

propertythumbnail

Thethumbnail property returns a thumbnail of the current item.

Returns:

A thumbnail

RasterManager

classarcgis.raster.RasterManager(imglyr)

TheRasterManager class allows users to update, add, and delete rasters to anImageryLayer object.

The functions are only available if the layer has ‘Edit’ on it’s capabilities property.

Note

This class is not created by users directly. An instance of this class, calledrasters,is available as a property of an ImageryLayer object. Users call methods on thisrasters objectto update, add and delete rasters from anImageryLayer.

Parameter

Description

imglyr

requiredImageryLayer object.The imagery layer object where ‘Edit’ is in the capabilities.

add(raster_type,item_ids:str|None=None,service_url:str|None=None,compute_statistics:bool=False,build_pyramids:bool=False,build_thumbnail:bool=False,minimum_cell_size_factor:float|None=None,maximum_cell_size_factor:float|None=None,attributes:dict[str,Any]|None=None,geodata_transforms:list[dict[str,Any]]|None=None,geodata_transform_apply_method:str='esriGeodataTransformApplyAppend')

Theadd operation is performed on an image layer method, adding new rasters to an image layer.(POST only).The added rasters can either be uploaded items, using theitem_idsparameter, or published services, using theservice_url parameter.Ifitem_ids is specified, uploaded rasters are copied to the imagelayer’s dynamic image workspace location; if theservice_url isspecified, the image layer adds the URL to the mosaic dataset noraster files are copied. Theservice_url is required input for thefollowing raster types: Image Layer, Map Service, WCS, and WMS.

Note

Theadd operation is supported at 10.1 and later.

Parameter

Description

item_ids

The upload items (raster files) to be added. Either item_ids orservice_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 layer 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 Layer, 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 layer resource.

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>

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>

attributes

Any attribute for the added rasters.

Syntax:

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

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

Returns:

A dictionary

# Example Usageadded=raster_manager.add(item_ids="ib740c7bb-e5d0-4156-9cea-12fa7d3a472c,ib740c7bb-e2d0-4106-9fea-12fa7d3a482c",service_url="http://myserver/arcgis/services/Portland/ImageServer",raster_type="Raster Dataset",build_thumbnail=True,minimum_cell_size_factor=0.1,maximum_cell_size_factor=10,attributes={"MinPS":0,"MaxPS":20;"Year":2002,"State":"Florida"},geodata_transforms=[{"geodataTransform":"<geodataTransformName1>","geodataTransformArguments":{<geodataTransformArguments1>}},{"geodataTransform":"<geodataTransformName2>","geodataTransformArguments":{<geodataTransformArguments2>}}],geodata_transform_apply_method="esriGeodataTransformApplyOverwrite")
delete(raster_ids:str)

Thedelete operation deletes one or more rasters in an imagery layer.

Parameter

Description

raster_ids

Required string. The object IDs of a raster catalog items to beremoved. This is a comma seperated string.

example 1: raster_ids=’1,2,3,4’ # Multiple IDs
example 2: raster_ids=’10’ # single ID
Returns:

A dictionary

update(raster_id:int,files:list[str]|None=None,item_ids:str|None=None,service_url:str|None=None,compute_statistics:bool=False,build_pyramids:bool=False,build_thumbnail:bool=False,minimum_cell_size_factor:float|None=None,maximum_cell_size_factor:float|None=None,attributes:dict[str,Any]|None=None,footprint:Polygon|None=None,geodata_transforms:list[dict[str,Any]]|None=None,apply_method:str='esriGeodataTransformApplyAppend')

Theupdate operation updates rasters (attributes andfootprints, or replaces existing raster files) in an image layer.In most cases, this operation is used to update attributes orfootprints of existing rasters in an image layer.

Note

In cases where the original raster needs to be replaced, the new raster can eitherbe items uploaded using the items parameter or URLs of publishedservices using the serviceUrl parameter.

Parameter

Description

raster_id

Required integer. The object IDs of a raster catalog items to beupdated.

files

Optional list. Local source location to the raster to replace thedataset with.Example: [r”<path>data.tiff”]

item_ids

Optional string. The uploaded items (raster files) being used toreplace existing raster.

service_url

Optional string. The URL of the layer to be uploaded to replaceexisting raster data. The image layer will add this URL to themosaic dataset. The serviceUrl is required for the following rastertypes: Image Layer, Map Service, WCS, and WMS.

compute_statistics

If true, statistics for the uploaded raster will be computed. Thedefault is false.

build_pyramids

Optional boolean. If true, builds pyramids for the uploaded raster.The default is false.

build_thumbnail

Optional boolean. If true, generates a thumbnail for the uploadedraster. The default is false.

minimum_cell_size_factor

Optional float. The factor (times raster resolution) used topopulate MinPS field (minimum cell size above which raster isvisible).

maximum_cell_size_factor

Optional float. The factor (times raster resolution) used topopulate MaxPS field (maximum cell size below which raster isvisible).

footprint

Optional Polygon. A JSON 2D polygon object that defines thefootprint of the raster. If the spatial reference is not defined, itwill default to the image layer’s spatial reference.

attributes

Optional dictionary. Any attribute for the uploaded raster.

geodata_transforms

Optional list. The geodata transformations applied on the updatedrasters. A geodata transformation is a mathematical model thatperforms geometric transformation on a raster. It defines how thepixels will be transformed when displayed or accessed, such aspolynomial, projective, or identity transformations. The geodatatransformations will be applied to the updated dataset.

apply_method

Optional string. Defines how to apply the provided geodataTransform. The default is esriGeodataTransformApplyAppend.

Values:esriGeodataTransformApplyAppend, esriGeodataTransformApplyReplace, esriGeodataTransformApplyOverwrite

Returns:

A dictionary

# Example Usageupdated=raster_manager.update(raster_id=087631,item_ids="ib740c7bb-e5d0-4156-9cea-12fa7d3a472c,ib740c7bb-e2d0-4106-9fea-12fa7d3a482c",service_url="http://myserver/arcgis/services/Portland/ImageServer",build_thumbnail=True,minimum_cell_size_factor=0.1,maximum_cell_size_factor=10,attributes={"MinPS":0,"MaxPS":20;"Year":2002,"State":"Florida"},geodata_transforms=[{"geodataTransform":"<geodataTransformName1>","geodataTransformArguments":{<geodataTransformArguments1>}},{"geodataTransform":"<geodataTransformName2>","geodataTransformArguments":{<geodataTransformArguments2>}}],apply_method="esriGeodataTransformApplyOverwrite")

RasterCollection

classarcgis.raster.RasterCollection(rasters=None,attribute_dict:dict|None=None,where_clause:str|None=None,query_geometry:dict|None=None,engine:str|None=None,gis:GIS|None=None,context:dict|None=None)

TheRasterCollection object allows a group of rasters to be sorted andfiltered easily, and prepares a collection for additional processing and analysis.

Parameter

Description

rasters

The input raster datasets. Supported inputs include a list oflocal or datastore rasters, a mosaic dataset, a multidimensionalraster in Cloud Raster Format, a NetCDF file, or an image service.If you’re using a list of raster datasets, all rasters must havethe same cell size and spatial reference.

arcpy should be available if the input is a local raster dataset.

attribute_dict

Optional dict. attribute information to be added to each raster,when the input is a list of rasters. For each key-value pair,the key is the attribute name and the value is a list of valuesthat represent the attribute value for each raster. For example,to add a name field to a list of three rasters, use{“name”: [“Landsat8_Jan”, “Landsat8_Feb”, “Landsat8_Mar”]}.

where_clause

Optional string. An expression that limits the records returned.

query_geometry

Optional. An object that filters the items such thatonly those that intersect with the object will be returned.

engine

Optional string. The backend engine to be used.Possible options:

  • arcpy : Use the arcpy engine for processing.

  • image_server : Use the Image Server engine for processing.

gis

OptionalGIS of the RasterCollection object.

context

Optional. Additional properties to control the creation of RasterCollection.The context parameter would be honoured by all other collections created from thisi.e., the map/filter outputs. The filter/map methods also support the context parameterwhich can be configured separately for each method.

Currently available:

  • query_boundary:The boolean value set to this option determines whether to add SHAPE field to the RasterCollection.The value in the SHAPE field represents the boundary/geometry of the raster.The query_boundary parameter is honoured only when the RasterCollectionis created from a list of Rasters.

    • True: Set query_boundary to True to add the SHAPE field to the RasterCollection.

    • False: Set query_boundary to False to not add the SHAPE field to the RasterCollection. (Creation of RasterCollection would be faster)

    By default, query_boundary is set to True, i.e, SHAPE field will be added.

    Example:{“query_boundary”:True}

# Usage Example 1: Creates a raster collection from image service urlservice_url=gis.content.search('my_rasters',item_type="Imagery Layer")[0].urlrc=RasterCollection(rasters=service_url,gis=gis)
# Usage Example 2: Creates a raster collection from rasters stored locallyras1=Raster(r"./data/ras1.tif")ras2=Raster(r"./data/ras2.tif")ras3=Raster(r"./data/ras3.tif")ras_list=[ras1,ras2,ras3]# Add attributes to the raster collectionacquisition_date=["2016-01-01T00:00:00","2016-02-01T00:00:00","2016-03-01T00:00:00"]name_list=["Landsat8_Jan","Landsat8_Feb","Landsat8_Mar"]rc=RasterCollection(rasters=ras_list,attribute_dict={"name":name_list,"AcquisitionDate":acquisition_date})
add_field(field_name:str,field_values:list,context:dict[str,Any]|None=None)

Adds a new field to the raster collection and populates it with values.

Parameter

Description

field_name

Required string. The name of the field to be added.

field_values

Required list. The list of values associated with the field name.The length of the list should match the number of items in the raster collectionProviding only one value will set the same value for all rows.

context

Optional dictionary. Additional properties to control the creation of RasterCollection.The default value for the context parameter would be the same as that of thecontext settings applied to the parent collection.

Currently available:

  • query_boundary:This boolean value set to this option determines whether to add SHAPE fieldto the RasterCollection. The value in the SHAPE field represents theboundary/geometry of the raster. The query_boundary parameter is honouredonly when the RasterCollection is created from a list of Rasters.

    • True: Set query_boundary to True to add the SHAPE field to the RasterCollection.

    • False: Set query_boundary to False to not add the SHAPE field to the RasterCollection. (Creation of RasterCollection would be faster)

    Example:

    {“query_boundary”:True}

Returns:

A newRasterCollection that has the new field added.

propertycount

Thecount property returns the count of items in theRasterCollection.

Returns:

An integer

propertyfields

Thefields property returns the fields available in theRasterCollection.

Returns:

A list of available fields

filter_by(where_clause:str|None=None,query_geometry_or_extent:Geometry|None=None,raster_query:str|None=None,context:dict[str,Any]|None=None)

Thefilter_by method filters aRasterCollection based on attribute and/or spatial queries.

Parameter

Description

where_clause

Optional String. An SQL expression used to select a subset of rasters

query_geometry_or_extent

Optional Geometry object. Items in the collection that fails tointersect the given geometry will be excluded

raster_query

Optional string. An SQL expression used to select a subset of rastersby the raster’s key properties.

context

Optional dictionary. Additional properties to control the creation of RasterCollection.The default value for the context parameter would be the same as that of thecontext settings applied to the parent collection.

Currently available:

  • query_boundary:This boolean value set to this option determines whether to add SHAPE fieldto the RasterCollection. The value in the SHAPE field represents theboundary/geometry of the raster. The query_boundary parameter is honouredonly when the RasterCollection is created from a list of Rasters.

    • True: Set query_boundary to True to add the SHAPE field to the RasterCollection.

    • False: Set query_boundary to False to not add the SHAPE field to the RasterCollection. (Creation of RasterCollection would be faster)

    Example:

    {“query_boundary”:True}

Returns:

ARasterCollection object that only contains items satisfying the queries

# Usage Example: Creates a Raster collection and filters rasters satisfying the raster query.service_url=gis.content.search('my_image_service')[0].urlrc=RasterCollecton(service_url,gis=gis)filtered_rc=rc.filter_by(raster_query="raster_query")
filter_by_attribute(field_name:str,operator:str,field_values:str|list[str]|list[int]|int,context:dict[str,Any]|None=None)

Thefilter_by_attribute method filters the collection of raster items by an attribute query and returns araster collection containing only the items that satisfy the query.

Parameter

Description

field_name

Required string. The field name to use in the filter.

operator

Required string. The keyword to filter the attributes.Keywords include the following:

  • CONTAINS - The attribute in the field contains the specified string, list, or number.

  • ENDS_WITH - The attribute ends with the specified string or number.

  • EQUALS - The attribute equals the specified string, list, or number.

  • GREATER_THAN - The attribute is greater than the specified number.

  • IN - The attribute is one of the items in the specified list.

  • LESS_THAN - The attribute is less than the specified number.

  • NOT_CONTAINS - The attribute does not contain the specified string, list, or number.

  • NOT_ENDS_WITH - The attribute does not end with the specified string or number.

  • NOT_EQUALS - The attribute does not equal the specified string, list, or number.

  • NOT_GREATER_THAN - The attribute is not greater than the specified number.

  • NOT_IN - The attribute is not one of the items in the specified list.

  • NOT_LESS_THAN - The attribute is not less than the specified number.

  • NOT_STARTS_WITH - The attribute does not start with the specified string or number.

  • STARTS_WITH - The attribute starts with the specified string or number.

field_values

Required object. The attribute value or values against which to compare.This can be specified as a string, a list, or a number.

context

Optional dictionary. Additional properties to control the creation of RasterCollection.The default value for the context parameter would be the same as that of thecontext settings applied to the parent collection.

Currently available:

  • query_boundary:This boolean value set to this option determines whether to add SHAPE fieldto the RasterCollection. The value in the SHAPE field represents theboundary/geometry of the raster. The query_boundary parameter is honouredonly when the RasterCollection is created from a list of Rasters.

    • True: Set query_boundary to True to add the SHAPE field to the RasterCollection.

    • False: Set query_boundary to False to not add the SHAPE field to the RasterCollection. (Creation of RasterCollection would be faster)

    Example:

    {“query_boundary”:True}

Returns:

aRasterCollection object that only contains items satisfying the filter

# Usage Example 1: Filters the raster collection based on matching field name.filtered_rc_attribute=rc.filter_by_attribute(field_name="Name",operator="EQUALS",field_values="field_values")# Usage Example 2: Filters the raster collection based on unmatching field name.filtered_rc_attribute2=rc.filter_by_attribute(field_name="Name",operator="NOT_EQUALS",field_values="field_values")
filter_by_calendar_range(calendar_field:str,start:int,end:int|None=None,time_field_name:str='StdTime',date_time_format:str|None=None,context:dict[str,Any]|None=None)

Thefilter_by_calendar_range method filters theRasterCollection by acalendar_field and its start and end value (inclusive).

For example, if you would like to select all the rasters that have the time stamp onMonday, specifycalendar_field as ‘DAY_OF_WEEK’ and put start and end to 1.

Parameter

Description

calendar_field

Required String, one of ‘YEAR’, ‘MONTH’, ‘QUARTER’, ‘WEEK_OF_YEAR’,‘DAY_OF_YEAR’, ‘DAY_OF_MONTH’, ‘DAY_OF_WEEK’, ‘HOUR’

start

Required integer.The start value of the calendar_field. For example, to filter allitems that were collected in January,

filtered_rc = rc.filter_by_calendar_range(calendar_field=”MONTH”, start=1).

end

Optional integer.

The end value of the calendar_field. For example, to filter all itemsthat were collected in the first 5 days of each year,

filtered_rc = rc.filter_by_calendar_range(calendar_field=”DAY_OF_YEAR”,start=1, end=5)

time_field_name

Optional string. The name of the field that contains the time attributefor each item in the collection. The default is StdTime.

date_time_format

Optional string. The time format of the values in the time field.For example, if the input time value is “1990-01-31”, thedate_time_format is “%Y-%m-%d”.

context

Optional dictionary. Additional properties to control the creation of RasterCollection.The default value for the context parameter would be the same as that of thecontext settings applied to the parent collection.

Currently available:

  • query_boundary:This boolean value set to this option determines whether to add SHAPE fieldto the RasterCollection. The value in the SHAPE field represents theboundary/geometry of the raster. The query_boundary parameter is honouredonly when the RasterCollection is created from a list of Rasters.

    • True: Set query_boundary to True to add the SHAPE field to the RasterCollection.

    • False: Set query_boundary to False to not add the SHAPE field to the RasterCollection. (Creation of RasterCollection would be faster)

    Example:

    {“query_boundary”:True}

Returns:

aRasterCollection object that only contains items satisfying the filter

# Usage Example 1: Filters the raster collection to hold rasters from the month of January.filtered_rc_month=rc2.filter_by_calendar_range(calendar_field="MONTH",start=1)# Usage Example 2: Filter the raster collection over the years 2015-2020.filtered_rc_years=rc2.filter_by_calendar_range(calendar_field="YEAR",start=2015,end=2020)
filter_by_geometry(query_geometry_or_extent:Geometry|Raster|ImageryLayer,context:dict[str,Any]|None=None)

Thefilter_by_geometry method filters theRasterCollection such that only those rasters thatintersect with the geometry will be returned.

Parameter

Description

query_geometry_or_extent

Required object that filters the items such that only those thatintersect with the object will be returned. This can be specifiedwith a Geometry object, Raster object, ImageryLayer object.

context

Optional dictionary. Additional properties to control the creation of RasterCollection.The default value for the context parameter would be the same as that of thecontext settings applied to the parent collection.

Currently available:

  • query_boundary:This boolean value set to this option determines whether to add SHAPE fieldto the RasterCollection. The value in the SHAPE field represents theboundary/geometry of the raster. The query_boundary parameter is honouredonly when the RasterCollection is created from a list of Rasters.

    • True: Set query_boundary to True to add the SHAPE field to the RasterCollection.

    • False: Set query_boundary to False to not add the SHAPE field to the RasterCollection. (Creation of RasterCollection would be faster)

    Example:

    {“query_boundary”:True}

Returns:

aRasterCollection object that only contains items satisfying the filter

# Usage Example: Filters the raster collection based on specified geometry.aoi={"spatialReference":{"wkid":32610},"xmax":725000,"xmin":720000,"ymax":4300000,"ymin":4250000}aoi_geometry=Geometry(aoi)filtered_rc_geom=rc.filter_by_geometry(query_geometry_or_extent=aoi_geometry)
filter_by_raster_property(property_name:str,operator:str,property_values:str|list[str,list[int],int],context:dict[str,Any]|None=None)

Thefilter_by_raster_property method filters theRasterCollection by a rasterproperty query and returns aRasterCollection containing only theitems that satisfy the query.

Parameter

Description

property_name

Required string. The name of the property to use in the filter.

operator

Required string. The keyword to filter the attributes.Keywords include the following:

  • CONTAINS - The attribute in the field contains the specified string, list, or number.

  • ENDS_WITH - The attribute ends with the specified string or number.

  • EQUALS - The attribute equals the specified string, list, or number.

  • GREATER_THAN - The attribute is greater than the specified number.

  • IN - The attribute is one of the items in the specified list.

  • LESS_THAN - The attribute is less than the specified number.

  • NOT_CONTAINS - The attribute does not contain the specified string, list, or number.

  • NOT_ENDS_WITH - The attribute does not end with the specified string or number.

  • NOT_EQUALS - The attribute does not equal the specified string, list, or number.

  • NOT_GREATER_THAN - The attribute is not greater than the specified number.

  • NOT_IN - The attribute is not one of the items in the specified list.

  • NOT_LESS_THAN - The attribute is not less than the specified number.

  • NOT_STARTS_WITH - The attribute does not start with the specified string or number.

  • STARTS_WITH - The attribute starts with the specified string or number.

property_values

Required object. The property value or values against which to compare.This can be specified as a string, a list, or a number.

context

Optional dictionary. Additional properties to control the creation of RasterCollection.The default value for the context parameter would be the same as that of thecontext settings applied to the parent collection.

Currently available:

  • query_boundary:This boolean value set to this option determines whether to add SHAPE fieldto the RasterCollection. The value in the SHAPE field represents theboundary/geometry of the raster. The query_boundary parameter is honouredonly when the RasterCollection is created from a list of Rasters.

    • True: Set query_boundary to True to add the SHAPE field to the RasterCollection.

    • False: Set query_boundary to False to not add the SHAPE field to the RasterCollection. (Creation of RasterCollection would be faster)

    Example:

    {“query_boundary”:True}

Returns:

ARasterCollection object that only contains items satisfying the filter

# Usage Example: Filters out rasters with a band count of 3 from the raster collectionfiltered_rc=rc.filter_by_raster_property(property_name="BAND_COUNT",operator="EQUALS",property_values=3)
filter_by_time(start_time:str='',end_time:str='',time_field_name:str='StdTime',date_time_format:str|None=None,context:dict[str,Any]|None=None)

Thefilter_by_time method filters aRasterCollection by time.

Parameter

Description

start_time

Optional String representation of the start time.

end_time

Optional String representation of the end time.

time_field_name

Optional string. the name of the field containing the time informationfor each item. Default: “StdTime”

date_time_format

Optional string. the time format that is used to format the time field values.Please ref the python date time standard for this argument (See this).

Default is None and this means using the Pro standard time format‘%Y-%m-%dT%H:%M:%S’ and ignoring the following sub-second.

context

Optional dictionary. Additional properties to control the creation of RasterCollection.The default value for the context parameter would be the same as that of thecontext settings applied to the parent collection.

Currently available:

  • query_boundary:This boolean value set to this option determines whether to add SHAPE fieldto the RasterCollection. The value in the SHAPE field represents theboundary/geometry of the raster. The query_boundary parameter is honouredonly when the RasterCollection is created from a list of Rasters.

    • True: Set query_boundary to True to add the SHAPE field to the RasterCollection.

    • False: Set query_boundary to False to not add the SHAPE field to the RasterCollection. (Creation of RasterCollection would be faster)

    Example:

    {“query_boundary”:True}

Returns:

aRasterCollection object that only contains items satisfying the filter

# Usage Example: Filters the raster collection based on time parameters.filtered_rc_time=rc.filter_by_time(start_time="1990-01-01 00:00:00",end_time="1999-12-31 00:00:00",time_field_name="AcquisitionDate")
staticfrom_stac_api(stac_api:str,query:dict[str,Any]|None=None,attribute_dict:dict[str,Any]|None=None,request_method:str='POST',request_params:dict[str,Any]|None=None,engine:str=None,context:dict|None=None,*,gis:GIS|None=None)

Thefrom_stac_api method creates aRasterCollection object from aSpatioTemporal Asset Catalog (STAC) APIsearch query.

Parameter

Description

stac_api

Required string. URL of the STAC API root endpoint. The STAC API wherethe search needs to be performed.

Note

The following STAC APIs are supported:

  • https://planetarycomputer.microsoft.com/api/stac/v1 (Following collections are supported: 3dep-seamless, 3dep-lidar-dsm, sentinel-1-rtc, hgb, cop-dem-glo-30, cop-dem-glo-90, gnatsgo-rasters, 3dep-lidar-hag, 3dep-lidar-intensity, 3dep-lidar-pointsourceid, mtbs, noaa-c-cap, alos-fnf-mosaic, 3dep-lidar-returns, chloris-biomass, 3dep-lidar-dtm-native, 3dep-lidar-classification, 3dep-lidar-dtm, gap, alos-dem, jrc-gsw, hrea, sentinel-2-l2a, nrcan-landcover, ecmwf-forecast, noaa-mrms-qpe-24h-pass2, sentinel-1-grd, nasadem, io-lulc, landsat-c2-l1, drcog-lulc, chesapeake-lc-7, chesapeake-lc-13, chesapeake-lu, noaa-mrms-qpe-1h-pass1, mobi, landsat-c2-l2, noaa-mrms-qpe-1h-pass2, noaa-nclimgrid-monthly, usda-cdl, esa-cci-lc, esa-cci-lc-netcdf, noaa-climate-normals-netcdf, noaa-climate-normals-gridded, io-lulc-9-class, io-biodiversity, naip, noaa-cdr-sea-surface-temperature-whoi, noaa-cdr-ocean-heat-content, noaa-cdr-sea-surface-temperature-whoi-netcdf, sentinel-3-olci-wfr-l2-netcdf, noaa-cdr-ocean-heat-content-netcdf, sentinel-3-synergy-v10-l2-netcdf, sentinel-3-olci-lfr-l2-netcdf, sentinel-3-slstr-lst-l2-netcdf, sentinel-3-slstr-wst-l2-netcdf, sentinel-3-synergy-syn-l2-netcdf, sentinel-3-synergy-vgp-l2-netcdf, sentinel-3-synergy-vg1-l2-netcdf, esa-worldcover, modis-64A1-061, modis-17A2H-061, modis-11A2-061, modis-17A2HGF-061, modis-17A3HGF-061, modis-09A1-061, modis-16A3GF-061, modis-21A2-061, modis-43A4-061, modis-09Q1-061, modis-14A1-061, modis-13Q1-061, modis-14A2-061, modis-15A2H-061, modis-11A1-061, modis-15A3H-061, modis-13A1-061, modis-10A2-061, modis-10A1-061, aster-l1t)

  • https://earth-search.aws.element84.com/v0 (All collections are suported)

  • https://earth-search.aws.element84.com/v1 (All collections are suported)

  • https://services.sentinel-hub.com/api/v1/catalog (All collections are suported)

  • https://landsatlook.usgs.gov/stac-server (All collections are suported)

  • https://geoportalstac.azurewebsites.net/stac (All collections are suported)

  • https://gpt.geocloud.com/sentinel/stac (All collections are suported)

Example:

https://planetarycomputer.microsoft.com/api/stac/v1

query

Optional dictionary. The GET/POST request query dictionary that can beused to query a STAC API’s search endpoint. (keys/values would dependon the specification of the STAC API in use and the request_methodparameter value).

For thebbox query parameter,EnvelopeandPolygonobjects are also accepted (in any spatial reference).

Note

limit key of the query should be explicitly set asNone when trying to create a RasterCollection from all the matched items (retrieving them from all the pages). By default, the RasterCollection is created from the first page of matches.

Example:
{
“collections”: [“sentinel-2-l2a”],
“bbox”: [-110, 39.5, -105, 40.5],
“query”: {“eo:cloud_cover”: {“lt”: 0.5}},
“datetime”: “2020-10-05T00:00:00Z/2020-10-10T12:31:12Z”,
“limit”: 100
}

attribute_dict

Optional dictionary. The attribute information to be added to each(STAC Item) raster returned from the query. For each key-value pair, the key isthe attribute name, and the value is a list of values that representthe attribute value for each raster.

Attribute values can also be collected from the STAC Items automaticallyusing the STAC Item metadata information. It can be done by specifyingthe STAC Item property name for the Attribute of interest in this format:

  • key : value -> Attribute display name : STAC item property name

Example:
{
“Name”:”id”,
“Sensor”:”platform”,
“StdTime”:”datetime”,
“Cloud Cover”:”eo:cloud_cover”,
“Spatial Reference”:”proj:epsg”,
“Extent”:”bbox”
}

Note

If ‘Geometry’ is not specified in theattribute_dict then it wouldbe automatically added for each Raster in theRasterCollection basedon its STAC Item ‘geometry’ property and would be inSpatial reference:{'wkid':4326}.

request_method

Optional string. The HTTP request method used with the STAC API for making the search.

Acceptable methods:

  • GET

  • POST (This is the default)

Example:

“POST”

request_params

This parameter can be used to set the properties for making the STACAPI search request. These are therequests.post()orrequests.get()method parameters and values will be specified in dictionary format.

Example:
{
“verify”:True,
“headers”:{“Authorization”: “Bearer access_token_string”}
}

engine

Optional string. The backend engine to be used for Raster processing.

Possible options:
  • “arcpy” : Use the arcpy engine for processing.

  • “image_server” : Use the Image Server engine for processing (This is the default).

Example:

“image_server”

Note

When usingimage_server engine, RasterRendering service should be enabled in the active GIS connection.

context

Optional dictionary. Additional properties to control the creation of RasterCollection.

Possible options:
  • assetManagement: Specifies how to manage and select assets for your RasterCollection.

    If multiple assets are selected, the collection will be composed of multiband rastersfrom those selected asset types.

    Type: List, String or Dictionary

    Format:When working with individual assets, the asset key can be specified directly (Eg: “B02”, {“key”: “B02”})else it could be a list. Each item in the list represents an asset key or identifier. Items inside the listcan either be strings representing the asset key directly, or dictionaries providingadditional details for locating the asset.

    The following keys could be used to provide the additional information of the assets (through individual dictionaries):

    • key: A string representing the unique identifier for an asset. For example: “red”.

    • path: A dictionary representing the hierarchy of keys to navigate to the asset. For example: [“alternate”, “s3”]

    • hrefKey: A string representing the key to access the asset URL. If different from the default “href” key, it should be specified here. For example: “msft:https-url”.

    Usage examples:
    • “red”

    • [“red”, “green”, “blue”]

    • {“key”: “tasmin”, “hrefKey”: “msft:https-url”}

    • [{“key”: “TRAD”, “path”: [“alternate”, “s3”]}, {“key”: “DRAD”, “path”: [“alternate”, “s3”]}]

    Example:

    {"assetManagement":["red","blue"]}
  • processingTemplate: Specifies the processing template to be applied to the individual rasters in the collection.

    Supported for selected collections and raster types. Read more about this in theSatellite sensor raster types documentation.

    Type: String

    Default: “Multiband” (for supported raster types only else None)

    Example:

    {"processingTemplate":"Surface Reflectance"}

gis

OptionalGIS object. The GIS of the RasterCollection object.

Tip

get_stac_info() method can be used beforehand to gather necessary STAC information,enabling effective querying of STAC APIs and Collections. This information can then be used to createRasterCollection objects with this method.

Returns:

ARasterCollection object

# Usage Example 1: Construct a collection from the Sentinel-2 L2A data accesible through# Earth Search STAC APIsentinel_2_aws_rc=RasterCollection.from_stac_api(stac_api="https://earth-search.aws.element84.com/v1",query={"collections":["sentinel-2-l2a"],"bbox":[-110,39.5,-105,40.5],"query":{"eo:cloud_cover":{"lt":0.5}},"datetime":"2020-10-05T00:00:00Z/2020-10-10T12:31:12Z","limit":100,},attribute_dict={"Name":"id","Sensor":"platform","StdTime":"datetime","Cloud Cover":"eo:cloud_cover","Spatial Reference":"proj:epsg","Extent":"bbox",},gis=gis,)# Usage Example 2: Construct a collection from the NAIP data accesible through# Planetary Computer STAC APInaip_pc_rc=RasterCollection.from_stac_api(stac_api="https://planetarycomputer.microsoft.com/api/stac/v1",query={"collections":["naip"],"bbox":[-122.2751,47.5469,-121.9613,47.7458],"datetime":"2018-12-01/2020-12-31","limit":5,},attribute_dict={"Name":"id","GSD":"gsd","StdTime":"datetime","State":"naip:state","Spatial Reference":"proj:epsg","Extent":"bbox",},gis=gis,)# Usage Example 3: Construct a collection from the Landsat-9 C2-L2 data accesible through# Digital Earth Africa STAC API (with custom asset selection) - Requires a registered cloudStore.landsat_dea_rc=RasterCollection.from_stac_api(stac_api="https://explorer.digitalearth.africa/stac",query={"collections":["ls9_sr"],"bbox":[25.982987096443583,29.249912751222965,28.30879111403085,31.348538968581714,],"datetime":"2020-12-01/2023-12-31","limit":20,},attribute_dict={"Name":"id","Sensor":"platform","Cloud Cover":"eo:cloud_cover","Row":"landsat:wrs_row","Path":"landsat:wrs_path",},context={"assetManagement":["SR_B4","SR_B3","SR_B2"]},# rgbgis=gis,)
staticfrom_stac_catalog(stac_catalog,attribute_dict:dict[str,Any]|None=None,request_params:dict[str,Any]|None=None,engine:str|None=None,context:dict|None=None,*,gis:GIS|None=None)

Thefrom_stac_catalog method creates aRasterCollection object from aStatic SpatioTemporal Asset Catalog (STAC).

Parameter

Description

stac_catalog

Required string orpystac.Catalog /pystac.Collection object. If string, then it should be the URL of the Static STAC (Catalog).

Example:

https://maxar-opendata.s3.amazonaws.com/events/India-Floods-Oct-2023/collection.json

attribute_dict

Optional dictionary. The attribute information to be added to each(STAC Item) raster of the catalog. For each key-value pair, the key isthe attribute name, and the value is a list of values that representthe attribute value for each raster.

Attribute values can also be collected from the STAC Items automaticallyusing the STAC Item metadata information. It can be done by specifyingthe STAC Item property name for the Attribute of interest in this format:

  • key : value -> Attribute display name : STAC item property name

Example:
{
“Name”:”id”,
“Sensor”:”platform”,
“StdTime”:”datetime”,
“Cloud Cover”:”eo:cloud_cover”,
“Extent”:”bbox”
}

Note

If ‘Geometry’ is not specified in theattribute_dict then it wouldbe automatically added for each Raster in theRasterCollection basedon its STAC Item ‘geometry’ property and would be inSpatial reference:{'wkid':4326}.

request_params

Optional dictionary. This parameter can be used to set the propertiesfor making the STAC Item/Catalog requests. These are therequests.get() methodmethod parameters and values will be specified in dictionary format.

This parameter is honoured when the stac_catalog parameter is set to a string (URL).
Example:

{“verify”:False}

engine

Optional string. The backend engine to be used for Raster processing.

Possible options:
  • “arcpy” : Use the arcpy engine for processing.

  • “image_server” : Use the Image Server engine for processing (This is the default).

Example:

“image_server”

Note

When usingimage_server engine, RasterRendering service should be enabled in the active GIS connection.

context

Optional dictionary. Additional properties to control the creation of RasterCollection.

Possible options:
  • assetManagement: Specifies how to manage and select assets for your RasterCollection.

    If multiple assets are selected, the collection will be composed of multiband rastersfrom those selected asset types.

    Type: List, String or Dictionary

    Format:When working with individual assets, the asset key can be specified directly (Eg: “B02”, {“key”: “B02”})else it could be a list. Each item in the list represents an asset key or identifier. Items inside the listcan either be strings representing the asset key directly, or dictionaries providingadditional details for locating the asset.

    The following keys could be used to provide the additional information of the assets (through individual dictionaries):

    • key: A string representing the unique identifier for an asset. For example: “red”.

    • path: A dictionary representing the hierarchy of keys to navigate to the asset. For example: [“alternate”, “s3”]

    • hrefKey: A string representing the key to access the asset URL. If different from the default “href” key, it should be specified here. For example: “msft:https-url”.

    Usage examples:
    • “red”

    • [“red”, “green”, “blue”]

    • {“key”: “tasmin”, “hrefKey”: “msft:https-url”}

    • [{“key”: “TRAD”, “path”: [“alternate”, “s3”]}, {“key”: “DRAD”, “path”: [“alternate”, “s3”]}]

    Example:

    {"assetManagement":["red","blue"]}
  • processingTemplate: Specifies the processing template to be applied to the individual rasters in the collection.

    Supported for selected collections and raster types. Read more about this in theSatellite sensor raster types documentation.

    Type: String

    Default: “Multiband” (for supported raster types only else None)

    Example:

    {"processingTemplate":"Surface Reflectance"}

gis

OptionalGIS object. The GIS of the RasterCollection object.

Tip

get_stac_info() method can be used beforehand to gather necessary STAC information,which can then be used to create RasterCollection objects with this method.

Returns:

ARasterCollection object

# Usage Example 1: Construct a collection from Maxar STACmaxar_rc=RasterCollection.from_stac_catalog(stac_catalog="https://maxar-opendata.s3.amazonaws.com/events/Emilia-Romagna-Italy-flooding-may23/ard/acquisition_collections/103005009DF96A00_collection.json",attribute_dict={"Name":"id","Platform":"platform","StdTime":"datetime","Data Area":"tile:data_area","Clouds Percent":"tile:clouds_percent","Spatial Reference":"proj:epsg",},gis=gis,)# Usage Example 2: Construct a collection from a pystac.Collection object created using# California Forest Observatory STACcollection_url="https://storage.googleapis.com/cfo-public/wildfire/collection.json"cat=pystac.Collection.from_file(collection_url)wildfire_rc=RasterCollection.from_stac_catalog(stac_catalog=cat,attribute_dict={"Name":"id","StdTime":"datetime","Metric":"metric","GSD":"gsd",},gis=gis,)# Usage Example 3: Construct a collection from UMBRA STAC (with custom asset selection)umbra_rc=RasterCollection.from_stac_catalog(stac_catalog="https://s3.us-west-2.amazonaws.com/umbra-open-data-catalog/stac/2024/2024-02/2024-02-19/catalog.json",attribute_dict={"Name":"id","Sensor":"platform","StdTime":"datetime","Polarizations":"sar:polarizations","Extent":"bbox",},context={"assetManagement":["GEC"]},gis=gis,)
get_field_values(field_name:str,max_count:int=0)

Theget_field_values method retrieves the values of a specified field from theRasterCollection.

Parameter

Description

field_name

Required string. The name of the field from which to extract values.

max_count

Optional integer. An integer that specifies the maximum number offield values to be returned. The values will be returned in theorder that the raster items are ordered in the collection. Ifno value is specified, all the field values for the given fieldwill be returned.

Returns:

A List of values of the specified field from theRasterCollection.

group_by(field_name:str,context:dict[str,Any]|None=None)

group_by method can be used to group the raster collection based on a field.

Parameter

Description

field_name

Required string. The name of the field that is used to group the raster collection.Items with the same field values will be grouped together.

context

Optional dictionary. Additional properties to control the creation of RasterCollection.The default value for the context parameter would be the same as that of thecontext settings applied to the parent collection.

Currently available:

  • query_boundary:This boolean value set to this option determines whether to add SHAPE fieldto the RasterCollection. The value in the SHAPE field represents theboundary/geometry of the raster. The query_boundary parameter is honouredonly when the RasterCollection is created from a list of Rasters.

    • True: Set query_boundary to True to add the SHAPE field to the RasterCollection.

    • False: Set query_boundary to False to not add the SHAPE field to the RasterCollection. (Creation of RasterCollection would be faster)

    Example:

    {“query_boundary”:True}

Returns:

A Dictionary. The dictionary that contains the grouped raster collections. The key of the dictionary is afield value of the field name that the grouping is based on. The value of the dictionary is a rastercollection whose field name contains the same field value.

# Usage Example 1: This example groups the raster collection into yearly data and creates a new raster collection using data from 1990.group_by_year=rc.group_by(field_name="Year",context=None)rc_1990=group_by_year[1990]
majority(ignore_nodata:bool=True,extent_type:str='FirstOf',cellsize_type:str='FirstOf')

Themajority method returns aRaster object in which each band contains the pixelvalue that occurs most frequently for that band across allrasters in the raster collection.

For example, if there are ten raster items in theRasterCollection,each with four bands, the majority method will determine thepixel value that occurs most frequently across all rasteritems for band 1, for band 2, for band 3, and for band 4;a four-band raster is returned. Band numbers are matchedbetween raster items using the band index, so the itemsin the raster collection must follow the same band order.

Parameter

Description

ignore_nodata

Optional Boolean. Specifies whether NoData values are ignored.

  • True : The method will include all valid pixels and ignore any NoData pixels. This is the default.

  • False : The method will result in NoData if there are any NoData values.

extent_type

Optional string. Specifies the extent to be used for the function.

  • “FirstOf” - Use the extent of the first input raster to determine the processing extent. This is the default.

  • “IntersectionOf” - Use the extent of the overlapping pixels to determine the processing extent.

  • “UnionOf” - Use the extent of all the rasters to determine the processing extent.

  • “LastOf” - Use the extent of the last input raster to determine the processing extent.

cellsize_type

Optional string. Specifies the cell size to be used for the function.

  • “FirstOf” - Use the first cell size of the input rasters. This is the default.

  • “MinOf” - Use the smallest cell size of all the input rasters.

  • “MaxOf” - Use the largest cell size of all the input rasters.

  • “MeanOf” - Use the mean cell size of all the input rasters.

  • “LastOf” - Use the last cell size of the input rasters.

Returns:

ARaster object

map(func:dict[str,Any],context:dict[str,Any]|None=None)

Themap method maps a Python function over a raster collection.

Parameter

Description

func

Required. The Python function to map over the raster collection.The return value of the function must be a dictionary in which oneof the keys is raster. For example,{“raster”: output_raster_object, “name”: input_item_name[“name”]}.

context

Optional dictionary. Additional properties to control the creation of RasterCollection.The default value for the context parameter would be the same as that of thecontext settings applied to the parent collection.

Currently available:

  • query_boundary:This boolean value set to this option determines whether to add SHAPE fieldto the RasterCollection. The value in the SHAPE field represents theboundary/geometry of the raster. The query_boundary parameter is honouredonly when the RasterCollection is created from a list of Rasters.

    • True: Set query_boundary to True to add the SHAPE field to the RasterCollection.

    • False: Set query_boundary to False to not add the SHAPE field to the RasterCollection. (Creation of RasterCollection would be faster)

    Example:

    {“query_boundary”:True}

Returns:

A newRasterCollection created from the existingRasterCollection after applying the func on each item.

# Usage Example: This snippet maps grayscale function to each raster item in the raster collection.rc_local=RasterCollection(r"./data/rasters.gdb/rasters")defapply_grayscale(item):raster=item["Raster"]gray=grayscale(raster)return{"raster":gray,"Name":item["Name"],"StdTime":item["AcquisitionDate"]}gray_rc=rc_local.map(func=apply_grayscale)
max(ignore_nodata:bool=True,extent_type:str='FirstOf',cellsize_type:str='FirstOf')

Themax method returns aRaster object in which each band contains themaximum pixel values for that band across all rasters in the raster collection.

For example, if there are ten raster items in theRasterCollection, each withfour bands, the max method will calculate the maximum pixel value that occurs across all rasteritems for band 1, band 2, band 3, and band 4; a four-band raster is returned.Band numbers are matched between raster items using the band index, so the itemsin the raster collection must follow the same band order.

Parameter

Description

ignore_nodata

Optional Boolean. Specifies whether NoData values are ignored.

  • True : The method will include all valid pixels and ignore any NoData pixels. This is the default.

  • False : The method will result in NoData if there are any NoData values.

extent_type

Optional string. Specifies the extent to be used for the function.

  • “FirstOf” - Use the extent of the first input raster to determine the processing extent. This is the default.

  • “IntersectionOf” - Use the extent of the overlapping pixels to determine the processing extent.

  • “UnionOf” - Use the extent of all the rasters to determine the processing extent.

  • “LastOf” - Use the extent of the last input raster to determine the processing extent.

cellsize_type

Optional string. Specifies the cell size to be used for the function.

  • “FirstOf” - Use the first cell size of the input rasters. This is the default.

  • “MinOf” - Use the smallest cell size of all the input rasters.

  • “MaxOf” - Use the largest cell size of all the input rasters.

  • “MeanOf” - Use the mean cell size of all the input rasters.

  • “LastOf” - Use the last cell size of the input rasters.

Returns:

ARaster object

mean(ignore_nodata:bool=True,extent_type:str='FirstOf',cellsize_type:str='FirstOf')

Themean method returns aRaster object in which each band contains the averagepixel values for that band across all rasters in the raster collection.

For example, if there are ten raster items in theRasterCollection,each with four bands, the mean method will calculate the mean pixel valuethat occurs across all raster items for band 1, for band 2, for band 3,and for band 4; a four-band raster is returned. Band numbers are matchedbetween raster items using the band index, so the items in the rastercollection must follow the same band order.

Parameter

Description

ignore_nodata

Optional Boolean. Specifies whether NoData values are ignored.

  • True : The method will include all valid pixels and ignore any NoData pixels. This is the default.

  • False : The method will result in NoData if there are any NoData values.

extent_type

Optional string. Specifies the extent to be used for the function.

  • “FirstOf” - Use the extent of the first input raster to determine the processing extent. This is the default.

  • “IntersectionOf” - Use the extent of the overlapping pixels to determine the processing extent.

  • “UnionOf” - Use the extent of all the rasters to determine the processing extent.

  • “LastOf” - Use the extent of the last input raster to determine the processing extent.

cellsize_type

Optional string. Specifies the cell size to be used for the function.

  • “FirstOf” - Use the first cell size of the input rasters. This is the default.

  • “MinOf” - Use the smallest cell size of all the input rasters.

  • “MaxOf” - Use the largest cell size of all the input rasters.

  • “MeanOf” - Use the mean cell size of all the input rasters.

  • “LastOf” - Use the last cell size of the input rasters.

Returns:

ARaster object

median(ignore_nodata:bool=True,extent_type:str='FirstOf',cellsize_type:str='FirstOf')

Themedian method returns aRaster object in which each band contains themedian pixel values for that band across all rasters in theRasterCollection.

For example, if there are ten raster items in the raster collection,each with four bands, the median method will calculate the median pixel valuethat occurs across all raster items for band 1, for band 2, for band 3,and for band 4; a four-band raster is returned. Band numbers are matchedbetween raster items using the band index, so the items in the rastercollection must follow the same band order.

Parameter

Description

ignore_nodata

Optional Boolean. Specifies whether NoData values are ignored.

  • True : The method will include all valid pixels and ignore any NoData pixels. This is the default.

  • False : The method will result in NoData if there are any NoData values.

extent_type

Optional string. Specifies the extent to be used for the function.

  • “FirstOf” - Use the extent of the first input raster to determine the processing extent. This is the default.

  • “IntersectionOf” - Use the extent of the overlapping pixels to determine the processing extent.

  • “UnionOf” - Use the extent of all the rasters to determine the processing extent.

  • “LastOf” - Use the extent of the last input raster to determine the processing extent.

cellsize_type

Optional string. Specifies the cell size to be used for the function.

  • “FirstOf” - Use the first cell size of the input rasters. This is the default.

  • “MinOf” - Use the smallest cell size of all the input rasters.

  • “MaxOf” - Use the largest cell size of all the input rasters.

  • “MeanOf” - Use the mean cell size of all the input rasters.

  • “LastOf” - Use the last cell size of the input rasters.

Returns:

ARaster object

merge(collection2)

Themerge method merges twoRasterCollections into one. The output has all the items that were in either collection.

Parameter

Description

collection2

RasterCollection object. The second collection to merge.

Returns:

a new Collection that has all the items that were in either collection.

# Usage Example 1: merges two image collections rc1 and rc2 into one.rc1=rc.filter_by_attribute("OBJECTID","EQUALS",1)rc2=rc.filter_by_attribute("OBJECTID","EQUALS",2)new_rc=rc1.merge(rc2)
min(ignore_nodata:bool=True,extent_type:str='FirstOf',cellsize_type:str='FirstOf')

Themin method returns aRaster object in which each band contains theminimum pixel values for that band across all rasters in theRasterCollection.

For example, if there are ten raster items in the raster collection, each with four bands,the min method will calculate the minimum pixel value that occurs across all rasteritems for band 1, band 2, band 3, and band 4; a four-band raster is returned.Band numbers are matched between raster items using the band index, so the itemsin the raster collection must follow the same band order.

Parameter

Description

ignore_nodata

Optional Boolean. Specifies whether NoData values are ignored.

  • True : The method will include all valid pixels and ignore any NoData pixels. This is the default.

  • False : The method will result in NoData if there are any NoData values.

extent_type

Optional string. Specifies the extent to be used for the function.

  • “FirstOf” - Use the extent of the first input raster to determine the processing extent. This is the default.

  • “IntersectionOf” - Use the extent of the overlapping pixels to determine the processing extent.

  • “UnionOf” - Use the extent of all the rasters to determine the processing extent.

  • “LastOf” - Use the extent of the last input raster to determine the processing extent.

cellsize_type

Optional string. Specifies the cell size to be used for the function.

  • “FirstOf” - Use the first cell size of the input rasters. This is the default.

  • “MinOf” - Use the smallest cell size of all the input rasters.

  • “MaxOf” - Use the largest cell size of all the input rasters.

  • “MeanOf” - Use the mean cell size of all the input rasters.

  • “LastOf” - Use the last cell size of the input rasters.

Returns:

aRaster object

mosaic(mosaic_method:str='FIRST')

Themosaic method returns aRaster object in which all items in aRasterCollection have been mosaicked into a single raster.

Parameter

Description

mosaic_method

Optional string. The method used to handle overlapping areasbetween adjacent raster items. Mosaic method options include the following:

  • FIRST - Determines the pixel value from the first raster that is overlapping.

  • LAST - Determines the pixel value from the last raster that is overlapping.

  • MEAN - Determines the average pixel value from the two rasters that are overlapping.

  • MIN - Determines the lower pixel value from the two raster datasets that are overlapping.

  • MAX - Determines the higher pixel value from the two raster datasets that are overlapping.

  • SUM - Determines the sum of pixel values from the two rasters that are overlapping.

The default value isFIRST

Returns:

ARaster object

quality_mosaic(quality_rc_or_list:RasterCollection|list[Raster],statistic_type:str|None=None)

Thequality_mosaic method returns aRaster object in which all items in aRasterCollection have been mosaicked into a single raster based on a qualityrequirement.

Parameter

Description

quality_rc_or_list

Required. TheRasterCollectionor list of rasters to be used as quality indicators.

For example, Landsat 8’s Band 1 is the Coastal/Aerosol band,which can be used to estimate the concentration of fine aerosolparticles such as smoke and haze in the atmosphere. For acollection of Landsat 8 images, use the select_bands method toreturn a RasterCollection object containing only Band 1 fromeach raster item. The number of raster items in thequality_rc_or_list must match the number of raster itemsin the raster collection to be mosaicked.

statistic_type

Required string. The statistic used to compare the input collectionor list of quality rasters.

MAX - The highest pixel value in the input quality rasters will be the pixel value in the output raster. This is the default.

MEDIAN - The median pixel value in the input quality rasters will be the pixel value in the output raster.

MIN - The minimum pixel value in the input quality rasters will be the pixel value in the output raster.

Note

For example, to mosaic the input raster collection such thatthose with the lowest aerosol content are on top,use theMIN statistic type.

Returns:

aRaster object

reduce(func,func_args=None)

Thereduce method composites all the images in the collection to a single image based on a reducer function.

Parameter

Description

func

Required. The Python function to reduce the raster collection.The function should accept a list of rasters and return a single reduced raster

func_args

Optional dictionary. Additional paramters to be passed to the reducer function.

Returns:

aRaster object

# Usage Example 1: This snippet reduces a raster collection based on a reducer function from arcgis.raster.functions module that can accept a list of rasters.rc=RasterCollection("https://myserver/arcgis/rest/services/ImageServiceName/ImageServer")fromarcgis.raster.functionsimportmaxmax_raster=rc.reduce(func=max,func_args={"cellsize_type":"MinOf"})# Usage Example 2: This snippet reduces a raster collection based on a custom reducer function.rc=RasterCollection("https://myserver/arcgis/rest/services/ImageServiceName/ImageServer")defskewness(ras_list):fromarcgis.raster.functionsimportmean,std,medcs_mean=mean(ras_list,process_as_multiband=True)cs_stddev=std(ras_list,process_as_multiband=True)cs_median=med(ras_list,process_as_multiband=True)out_skewness=3*(cs_mean-cs_median)/cs_stddevreturnout_skewnessskewness=rc.reduce(func=skewness)
select_bands(band_ids_or_names:str|int|list[str]|list[int],context:dict[str,Any]|None=None)

Theselect_bands method selects a list of bands from everyRaster item in aRasterCollection and returns a raster collection that containsRaster items with onlythe selected bands.

Parameter

Description

band_ids_or_names

Required. The names or index numbers of bands to be included inthe returned raster items. This can be specified with a single string,integer, or a list of strings or integers.

context

Optional dictionary. Additional properties to control the creation of RasterCollection.The default value for the context parameter would be the same as that of thecontext settings applied to the parent collection.

Currently available:

  • query_boundary:This boolean value set to this option determines whether to add SHAPE fieldto the RasterCollection. The value in the SHAPE field represents theboundary/geometry of the raster. The query_boundary parameter is honouredonly when the RasterCollection is created from a list of Rasters.

    • True: Set query_boundary to True to add the SHAPE field to the RasterCollection.

    • False: Set query_boundary to False to not add the SHAPE field to the RasterCollection. (Creation of RasterCollection would be faster)

    Example:

    {“query_boundary”:True}

Returns:

ARasterCollection that containsRaster items with only the selected bands.

set_engine(engine:str)

Theset_engine method can be used to change the back end engine of theRasterCollection.

sort(field_name:str,ascending:bool=True,context:dict[str,Any]|None=None)

Thesort method sorts theRasterCollection by a field name and returnsaRasterCollection that is in the order specified.

Parameter

Description

field_name

Required string. The name of the field to use for sorting.

ascending

Optional bool. Specifies whether to sort in ascending or descending order.(The default value is True)

context

Optional dictionary. Additional properties to control the creation of RasterCollection.The default value for the context parameter would be the same as that of thecontext settings applied to the parent collection.

Currently available:

  • query_boundary:This boolean value set to this option determines whether to add SHAPE fieldto the RasterCollection. The value in the SHAPE field represents theboundary/geometry of the raster. The query_boundary parameter is honouredonly when the RasterCollection is created from a list of Rasters.

    • True: Set query_boundary to True to add the SHAPE field to the RasterCollection.

    • False: Set query_boundary to False to not add the SHAPE field to the RasterCollection. (Creation of RasterCollection would be faster)

    Example:

    {“query_boundary”:True}

Returns:

A sortedRasterCollection object

std(ignore_nodata:bool=True,extent_type:str='FirstOf',cellsize_type:str='FirstOf')

Thestd method returns aRaster object in which each band contains the stdof pixel values for that band across all rasters in theRasterCollection.

For example, if there are ten raster items in the raster collection,each with four bands, the std method will calculate the std of pixelvalues for each pixel that occurs across all raster items for band 1,band 2, band 3, and band 4; a four-band raster is returned.Band numbers are matched between raster items using the band index,so the items in the raster collection must follow the same band order.

Parameter

Description

ignore_nodata

Optional Boolean. Specifies whether NoData values are ignored.

  • True : The method will include all valid pixels and ignore any NoData pixels. This is the default.

  • False : The method will result in NoData if there are any NoData values.

extent_type

Optional string. Specifies the extent to be used for the function.

  • “FirstOf” - Use the extent of the first input raster to determine the processing extent. This is the default.

  • “IntersectionOf” - Use the extent of the overlapping pixels to determine the processing extent.

  • “UnionOf” - Use the extent of all the rasters to determine the processing extent.

  • “LastOf” - Use the extent of the last input raster to determine the processing extent.

cellsize_type

Optional string. Specifies the cell size to be used for the function.

  • “FirstOf” - Use the first cell size of the input rasters. This is the default.

  • “MinOf” - Use the smallest cell size of all the input rasters.

  • “MaxOf” - Use the largest cell size of all the input rasters.

  • “MeanOf” - Use the mean cell size of all the input rasters.

  • “LastOf” - Use the last cell size of the input rasters.

Returns:

ARaster object

sum(ignore_nodata:bool=True,extent_type:str='FirstOf',cellsize_type:str='FirstOf')

Thesum method returns aRaster object in which each band contains the sumof pixel values for that band across all rasters in theRasterCollection.

For example, if there are ten raster items in the raster collection,each with four bands, the sum method will calculate the sum of pixelvalues for each pixel that occurs across all raster items for band 1,band 2, band 3, and band 4; a four-band raster is returned.Band numbers are matched between raster items using the band index,so the items in the raster collection must follow the same band order.

Parameter

Description

ignore_nodata

Optional Boolean. Specifies whether NoData values are ignored.

  • True : The method will include all valid pixels and ignore any NoData pixels. This is the default.

  • False : The method will result in NoData if there are any NoData values.

extent_type

Optional string. Specifies the extent to be used for the function.

  • “FirstOf” - Use the extent of the first input raster to determine the processing extent. This is the default.

  • “IntersectionOf” - Use the extent of the overlapping pixels to determine the processing extent.

  • “UnionOf” - Use the extent of all the rasters to determine the processing extent.

  • “LastOf” - Use the extent of the last input raster to determine the processing extent.

cellsize_type

Optional string. Specifies the cell size to be used for the function.

  • “FirstOf” - Use the first cell size of the input rasters. This is the default.

  • “MinOf” - Use the smallest cell size of all the input rasters.

  • “MaxOf” - Use the largest cell size of all the input rasters.

  • “MeanOf” - Use the mean cell size of all the input rasters.

  • “LastOf” - Use the last cell size of the input rasters.

Returns:

ARaster object

summarize_field(field_name,summary_type='ALL')

Summarizes a numeric field of the RasterCollection based on the specified summary_type

Parameter

Description

field_name

Required string. The name of the field to be summarized

summary_type

Required string or list of strings representing the summary type.Possible values - “COUNT”, “COUNT_DISTINCT”, “FIRST”,”HISTOGRAM”, “MAX”, “MEAN”, “MIN”,“PRODUCT”, “SAMPLE_SD”, “SAMPLE_VAR”, “SUM”, “TOTAL_SD”, “TOTAL_VAR”, “ALL”.

Returns:

A dictionary with key being the summary type and the value being the summary value.

to_multidimensional_raster(variable_field_name:str,dimension_field_names:str)

Theto_multidimensional_raster method returns a multidimensional raster dataset, in which each item in theRasterCollection is a slice in the multidimensional raster.

Parameter

Description

variable_field_name

Required string. The name of the field that contains the variable names.

dimension_field_names

Required string. The name of the field or fields that contains the dimension names.This can be specified as a single string or a list of strings.

For time-related dimensions, the field name must match one of thefollowing to be recognized as a time field: StdTime, Date, Time,or AcquisitionDate. For nontime-related dimensions, the values inthose fields must be type Double. If there are two or more dimensions,use a comma to separate the fields (for example,dimension_field_names = [“Time”, “Depth”]).

Returns:

ARaster object

# Usage Example: Generates a multidimensional raster from the raster collection.multidim_raster=rc.to_multidimensional_raster(variable_field_name="Name",dimension_field_name="AcquisitionDate")

RasterInfo

classarcgis.raster.RasterInfo(raster_info_dict=None)

TheRasterInfo class allows for creation of aRasterInfo object that describes a set of raster properties tofacilitate the creation of local raster dataset using theRaster class

Note

TheRasterInfo class requires ArcPy

ARasterInfo object can be created by instantiating it from a dictionary,or by calling anImageryLayer orRaster object’sraster_info property.

Information about the raster can also be set through the following properties available on theRasterInfoobject:band_count,extent,pixel_size_x,pixel_size_y,pixel_type,block_height,block_width,no_data_values,spatial_reference

To construct aRasterInfo object from a dictionary, use thefrom_dict method on this class.

# Usage Example 1: This example creates a new Raster object from the raster_info of another Raster object. (requires arcpy)raster_obj=Raster(<rasterdatasetpath>)ras_info=RasterInfo(raster_obj.raster_info)rinfo_based_ras=Raster(rasInfo2)#To write pixel values to this temporary Raster object:rinfo_based_ras.write(<numpy_array>)#To save this temporary raster locally:rinfo_based_ras.save(r"C:\data\persisted_raster.crf")

RasterInfo object can also be used in raster functions that take in raster info as a parameter. (does not require arcpy)example: As value to the raster_info parameter forarcgis.raster.functions.constant_raster() andarcgis.raster.functions.random_raster()

propertyband_count

Get/Set information about the band count of a raster.

propertyblock_height

Get/Set information about the block height of a raster.

propertyblock_width

Get/Set information about the block width of a raster.

propertyextent

Get/Set information about the extent of a raster.

from_dict(raster_info_dict)

Thefrom_dict method can be used to initialise aRasterInfo object from a raster infodictionary.

# Usage Example :rinfo=RasterInfo()rinfo.from_dict({'bandCount':3,'extent':{"xmin":4488761.95,"ymin":5478609.805,"xmax":4489727.05,"ymax":5479555.305,"spatialReference":{"wkt":"PROJCS["Deutsches_Hauptdreiecksnetz_Transverse_Mercator",GEOGCS["GCS_Deutsches_Hauptdreiecksnetz",DATUM["D_Deutsches_Hauptdreiecksnetz",SPHEROID["Bessel_1841",6377397.155,299.1528128]],PRIMEM["Greenwich",0.0],UNIT["Degree",0.0174532925199433]],PROJECTION["Transverse_Mercator"],PARAMETER["false_easting",4500000.0],PARAMETER["false_northing",0.0],PARAMETER["central_meridian",12.0],PARAMETER["scale_factor",1.0],PARAMETER["latitude_of_origin",0.0],UNIT["Meter",1.0]]"}},'pixelSizeX':0.0999999999999614,'pixelSizeY':0.1,'pixelType':'U8'})
propertyno_data_values

Get/Set information about theno_data_values of araster.

propertypixel_size_x

Get/Set information about the pixel size of a raster inx direction.

propertypixel_size_y

Get/Set information about the pixel size of a raster inthe y direction.

propertypixel_type

Get/Set information about the pixel type of a raster.

propertyspatial_reference

Get/Set information about the extent of a raster.

to_dict()

Theto_dict method is used to return Raster Info in dictionary format.

Submodules

Your browser is no longer supported. Please upgrade your browser for the best experience. See ourbrowser deprecation post for more details.


[8]ページ先頭

©2009-2025 Movatter.jp