Coordinate conversion and measurement functions are used to change map and point projections, convert coordinates (ground, layer, and pixel), add custom datums, and more. This is useful for combining and adjusting data from various different sources and/or regions.
Using Python Libraries to Display Vector Attributes
Note: Before running this sample, configure these variables and modules:
export_dir: the directory for resulting files to be exported toimport 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.
import os
import globalmapper as gm
import numpy as np
import matplotlib.pyplot as plt
layer_path = "Z:/GM-20069/raster_elevation_to_numpy_sample_data/Depth_to_Water.tif"
export_dir = os.path.join(os.path.dirname(os.path.dirname(__file__)), "../misc/raster_elevation_to_numpy_output/")
os.makedirs(export_dir, exist_ok=True)
# 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.
# Closes all layers that may be open
layers_are_open = gm.GetLoadedLayerList()
if layers_are_open:
arr_ptr, arr_size = layers_are_open
initial_layers = gm.GM_LayerHandle_array_frompointer(arr_ptr)
for i in range(arr_size):
gm.CloseLayer(initial_layers[i])
# Force load a raster layer with unknown interpretation as a grid layer
err_LoadLayerList, arr_ptr, arr_size = gm.LoadLayerList(
layer_path, gm.GM_LoadFlags_LoadUnknownAsGrid
)
loaded_array = gm.GM_LayerHandle_array_frompointer(arr_ptr)
### START SAMPLE
# 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")
### END SAMPLE
assert (
gm.GM_Error_None == err_LoadLayerList
), f"LoadLayerList: Expected {gm.GM_Error_None}, got {err_LoadLayerList}"
assert (
gm.GM_Error_None == err_GetPixelElevation
), f"GetPixelElevation: Expected {gm.GM_Error_None}, got {err_GetPixelElevation}"
assert (
gm.GM_Error_None == err_ConvertCoordLayerPixelToGround
), f"ConvertCoordLayerPixelToGround: Expected {gm.GM_Error_None}, got {err_ConvertCoordLayerPixelToGround}"
assert os.path.exists(layer_path), f"Sample data doesn't exist: {layer_path}"
assert os.path.isdir(export_dir), f"Error creating the export directory: {export_dir}"
# Expected path for file export
exported_filepath = os.path.join(export_dir, "heat_grid.jpg")
# Assert that the final expected output file exists and is not empty
assert os.path.exists(
exported_filepath
), f"Expected output file does not exist: {exported_filepath}"
assert (
os.path.getsize(exported_filepath) > 0
), f"Exported file is empty: {exported_filepath}"
Loading a Rectified JPG Using GCPs from a CSV
Note: Before running this sample, configure these variables:
resource_dir: the directory path containing sample dataCSV_file: the name of a CSV fileJPG_file: the name of a JPG file
A script to interpret world-coordinate/pixel-coordinate pairs parsed from a CSV file. It builds a c-style array of ground control points and uses them to rectify the JPG layer as it loads.
import os
import globalmapper as gm
resource_dir = "Z:/GM-20069/rectify_JPG_from_CSV_sample_data/"
CSV_file = "centralpark_gcps.csv"
JPG_file = "Central_Park.jpg"
# A script to interpret world-coordinate/pixel-coordinate pairs parsed from a CSV file. It builds a c-style array of ground
# control points and uses them to rectify the JPG layer as it loads.
### START SAMPLE
# Open csv source file
source = open(resource_dir + CSV_file, "r")
# Extract the numeric values from the source file
values = source.read().split(",")
values = [float(val) for val in values]
source.close()
# Build the list of ground control points
gcp_list = gm.GM_GroundControlPoint_array(int(len(values) / 4))
i = 0
while i + 3 < len(values):
# Assume that the csv file is formatted like: ...,pixelX,pixelY,longitude,latitude,...
the_gcp = gm.GM_GroundControlPoint_t(
values[i], values[i + 1], values[i + 2], values[i + 3]
)
gcp_list[int(i / 4)] = the_gcp
i += 4
# Rectify the layer while loading it, using the ground control points
num_gcps = int(i / 4)
err_LoadProjectionFromEPSGCode, projection = gm.LoadProjectionFromEPSGCode(4326)
err_LoadRectifiedLayer, layer = gm.LoadRectifiedLayer(
resource_dir + JPG_file, gm.GM_LoadFlags_UseDefaultLoadOpts, gcp_list, num_gcps, projection
)
### END SAMPLE
err = gm.CloseLayer(layer)
assert (
gm.GM_Error_None == err_LoadProjectionFromEPSGCode
), f"LoadProjectionFromEPSGCode: Expected {gm.GM_Error_None}, got {err_LoadProjectionFromEPSGCode}"
assert (
gm.GM_Error_None == err_LoadRectifiedLayer
), f"LoadRectifiedLayer: Expected {gm.GM_Error_None}, got {err_LoadRectifiedLayer}"
assert os.path.isdir(resource_dir), f"Resource directory doesn't exist: {resource_dir}"
assert os.path.exists(
os.path.join(resource_dir, CSV_file)
), f"Sample CSV data doesn't exist: {CSV_file}"
assert os.path.exists(
os.path.join(resource_dir, JPG_file)
), f"Sample JPG data doesn't exist: {JPG_file}"
assert num_gcps == 6, "Incorrect number of GCPs"