Raster/Elevation Layer Query Samples

Raster and elevation layer queries are used to gather information like elevation, color, or pixel data from provided imagery and terrain layers. Users can specify a location to query by providing (x,y) coordinate pairs in the current projection or (row,column) coordinates for a specific pixel. These tools can help you understand the surface characteristics at specific points or areas in the loaded raster layers.

Display Vector Attributes with NumPy and Matplotlib

Note

Before running this sample, configure these variables and modules:

  • export_dir: the directory for resulting files to be exported to

  • import numpy as np

  • import matplotlib.pyplot as plt

This script places raster elevation values (in meters), and (x,y) pixel coordinate values into a python list from a defined area. The (x,y) pixel cooridnates are converted to (x,y) ground coorindate values based on the current project of the map. Ground coordinate values and elevation values are placed into a numpy array for use with Matplotlib. As an example of data visualization with external packages, a heat grid of the retrived grid of values is exported to a specified directory.

# Displays information about the raster layer
info = gm.GetLayerInfo(loaded_array[0])
print("Layer %d, 0x%x:" % (0, loaded_array[0]))
print("    Description: %s" % info.mDescription)
print("    Type: %s" % info.mTypeName)
print("    Raster Data: %s" % info.mHasRasterData)
print("    Pixel Height: %s" % info.mGlobalPixelHeight)
print("    Pixel Width: %s" % info.mGlobalPixelWidth)
print("    Max Elevation: %s" % info.mMaxElevation)
print("    Min Elevation: %s" % info.mMinElevation)

# Collects elevation values and x,y pixel coordinates converted to ground
# coordinate values

# Python lists of elevation and x,y ground coordinate values
elevation_values = []
x_coord = []
y_coord = []
# i is defined as a starting y pixel coordinate
i = 3073
# i, j are definded for 10x10 pixel coordinate grid
while i < 3083:
    j = 6066
    while j < 6076:
        # Collects elevation values as specific x, y pixel coordinates
        err_GetPixelElevation, elevation = gm.GetPixelElevation(loaded_array[0], j, i)
        # X,Y pixel coordinates are converted to ground coordinates
        err_ConvertCoordLayerPixelToGround, coordinateX, coordinateY = (
            gm.ConvertCoordLayerPixelToGround(loaded_array[0], j, i)
        )
        # All values are added to their respective lists
        elevation_values.append(elevation)
        x_coord.append(coordinateX)
        y_coord.append(coordinateY)
        j += 1
    i += 1

# Numpy arrays are created for elevation and x, y ground coordinates
# Elevation is changed from a 1-d to 2-d array with 10 values per row
elevation = np.array(elevation_values).reshape(-1, 10)
# Duplicates are removed from x and y ground coordinate arrays
x_values = np.unique(np.array(x_coord))
y_values = np.unique(np.array(y_coord))
# Rounds ground coordinates to 3 decimal points
x = np.round(x_values, 3)
y = np.round(y_values, 3)
# Displays a simple heat grid with Matplotlib
fig, ax = plt.subplots()
# Creates image for heat grid
im = ax.imshow(elevation)

# Sets labels for x and y coordinate values
ax.set_xticks(np.arange(len(x)), labels=x, fontsize=10)
ax.set_yticks(np.arange(len(y)), labels=y, fontsize=10)
ax.set_ylabel("Y Ground Coordinate Values")
ax.set_xlabel("X Ground Coordinate Values")

# Rotate the tick labels and set their alignment
plt.setp(ax.get_xticklabels(), rotation=45, ha="right", rotation_mode="anchor")

# Loop over data dimensions and create text annotations of elevation values
for i in range(len(y)):
    for j in range(len(x)):
        text = ax.text(
            j, i, elevation[i, j], ha="center", va="center", color="w", fontsize=6
        )

# Displays title for grid
ax.set_title("Change of Elevation (meters) of a Selected Area")
fig.tight_layout()
plt.savefig(export_dir + "heat_grid.jpg")

GetPixelElevationRow Sample

A demonstration on how to use GetPixelElevationRow. The pixel elevations for a specified row are collected, and statistical data is displayed, including the row’s average elevation and the number of points falling within defined elevation ranges.

# Get the metadata for the loaded image layer
info = gm.GetLayerInfo(layers_list[0])
metadata_array = gm.GM_AttrValue_array_frompointer(info.mMetadataList)
metadata_list = gm.carray_to_list(metadata_array, info.mMetadataListSize)
num_pxs = 0

# Find the attribute that holds the number of pixel columns
for attr in metadata_list:
    if attr.mName == 'NUM COLUMNS':
        num_pxs = int(attr.mVal)

if num_pxs == 0:
    print("Error: Attribute for the number of columns not found.")

# The number of pixel columns denotes the maximum number
# of pixels that can be held in each row of the loaded imagery
elevation_array = gm.float_array(num_pxs)
# Gets the elevations from the specified pixel row
err_GetPixelElevationRow = gm.GetPixelElevationRow(
    layers_list[0], 5858, elevation_array, -9999
)

# Display elevation results
elevation_list = gm.carray_to_list(elevation_array, num_pxs)
elev_range_0_50 = []
elev_range_50_100 = []
elev_range_100_150 = []
elev_range_150_On = []
valid = 0
total = 0
for i in range(18674):
    if elevation_list[i] != -9999.0:
        valid += 1
        total += elevation_list[i]
        if elevation_list[i] <= 50:
            elev_range_0_50.append(elevation_list[i])
        elif elevation_list[i] <= 100:
            elev_range_50_100.append(elevation_list[i])
        elif elevation_list[i] <= 150:
            elev_range_100_150.append(elevation_list[i])
        elif elevation_list[i] > 150:
            elev_range_150_On.append(elevation_list[i])

print("\nTotal valid points in pixel row:", valid)
print("Average elevation:", total / valid)
print("Pixels with elevation 0-50m:", len(elev_range_0_50))
print("Pixels with elevation 50-100m:", len(elev_range_50_100))
print("Pixels with elevation 100-150m:", len(elev_range_100_150))
print("Pixels with elevation >150m:", len(elev_range_150_On), "\n")

GetLocationElevationList Sample

A demonstration on how to use GetLocationElevationList. Elevations are extracted from the pixels corresponding to the points in the point list, across all layers, starting from the topmost layer. The collected elevations are then displayed.

point1 = gm.GM_Point_t(1553978, 326704)
point2 = gm.GM_Point_t(1093280, 256782)
point_list = [point1, point2]
size = len(point_list) * len(layers_list)
elevation_array = gm.float_array(size)
# Gets the elevation at each location from a layer/layer list (starting with the top-most layer)
err_GetLocationElevationList = gm.GetLocationElevationList(
    layers_list, point_list, elevation_array, 0
)

# Display elevations at the specified points (2 layers were loaded for this sample)
elevation_list = gm.carray_to_list(elevation_array, size)
print("\nLayer 1 data:", elevation_list[0], elevation_list[1])
print("Layer 0 data:", elevation_list[2], elevation_list[3], "\n")