CtrlK
BlogDocsLog inGet started
Tessl Logo

tessl/pypi-srtm-py

Python parser for the Shuttle Radar Topography Mission elevation data

Pending

Quality

Pending

Does it follow best practices?

Impact

Pending

No eval scenarios have been run

Overview
Eval results
Files

gpx-processing.mddocs/

GPX Track Processing

Integration with GPX files to add elevation data to GPS tracks, with options for smoothing, interpolation, and batch processing of multiple tracks.

Capabilities

Adding Elevations to GPX Tracks

Add elevation data to GPX track points with configurable options for handling existing data and applying smoothing algorithms.

class GeoElevationData:
    def add_elevations(
        self, 
        gpx, 
        only_missing: bool = False, 
        smooth: bool = False, 
        gpx_smooth_no: int = 0
    ) -> None: ...

Parameters:

  • gpx: GPX object (from gpxpy library) containing tracks to process
  • only_missing (bool): Only add elevations to points that don't already have elevation data. Default: False
  • smooth (bool): Apply interpolated elevation sampling for smoother elevation profiles. Default: False
  • gpx_smooth_no (int): Number of smoothing passes to apply. Default: 0 (no additional smoothing)

Returns: None (modifies the GPX object in-place)

Usage Example:

import srtm
import gpxpy

# Load GPX file
with open('track.gpx', 'r') as gpx_file:
    gpx = gpxpy.parse(gpx_file.read())

# Create elevation data object
elevation_data = srtm.get_data()

# Add elevations to all track points
elevation_data.add_elevations(gpx)

# Save modified GPX
with open('track_with_elevations.gpx', 'w') as output_file:
    output_file.write(gpx.to_xml())

print(f"Processed {gpx.get_track_points_no()} track points")

Selective Elevation Processing

Add elevations only to track points that are missing elevation data, preserving existing elevation information.

Usage Example:

import srtm
import gpxpy

# Load GPX that may already have some elevation data
with open('partial_track.gpx', 'r') as gpx_file:
    gpx = gpxpy.parse(gpx_file.read())

elevation_data = srtm.get_data()

# Only fill missing elevations, preserve existing data
elevation_data.add_elevations(gpx, only_missing=True)

# Count points with elevation data
points_with_elevation = sum(
    1 for track in gpx.tracks 
    for segment in track.segments 
    for point in segment.points 
    if point.elevation is not None
)
print(f"Points with elevation data: {points_with_elevation}")

Smooth Elevation Profiles

Apply interpolation and smoothing to create more natural elevation profiles, reducing noise from discrete SRTM data points.

Usage Example:

import srtm
import gpxpy

# Load GPX file
with open('noisy_track.gpx', 'r') as gpx_file:
    gpx = gpxpy.parse(gpx_file.read())

elevation_data = srtm.get_data()

# Add smoothed elevations with multiple smoothing passes
elevation_data.add_elevations(
    gpx, 
    smooth=True,           # Enable interpolated sampling
    gpx_smooth_no=2        # Apply 2 additional smoothing passes
)

# Calculate elevation statistics
elevations = [
    point.elevation for track in gpx.tracks 
    for segment in track.segments 
    for point in segment.points 
    if point.elevation is not None
]

if elevations:
    print(f"Elevation range: {min(elevations):.1f}m to {max(elevations):.1f}m")
    print(f"Average elevation: {sum(elevations)/len(elevations):.1f}m")

Batch GPX Processing

Process multiple GPX files efficiently using batch mode to minimize memory usage.

Usage Example:

import srtm
import gpxpy
import os

# Configure for batch processing
elevation_data = srtm.get_data(batch_mode=True)

gpx_files = ['track1.gpx', 'track2.gpx', 'track3.gpx']

for gpx_filename in gpx_files:
    print(f"Processing {gpx_filename}...")
    
    # Load GPX
    with open(gpx_filename, 'r') as gpx_file:
        gpx = gpxpy.parse(gpx_file.read())
    
    # Add elevations
    elevation_data.add_elevations(gpx, smooth=True)
    
    # Save processed GPX
    output_filename = f"processed_{gpx_filename}"
    with open(output_filename, 'w') as output_file:
        output_file.write(gpx.to_xml())
    
    print(f"Saved {output_filename}")

print("Batch processing complete")

Advanced GPX Processing

Combine elevation processing with track analysis and validation.

Usage Example:

import srtm
import gpxpy
from datetime import datetime

elevation_data = srtm.get_data()

def process_gpx_with_stats(filename):
    """Process GPX file and return elevation statistics."""
    with open(filename, 'r') as gpx_file:
        gpx = gpxpy.parse(gpx_file.read())
    
    # Store original elevation count
    original_elevations = sum(
        1 for track in gpx.tracks 
        for segment in track.segments 
        for point in segment.points 
        if point.elevation is not None
    )
    
    # Add missing elevations with smoothing
    elevation_data.add_elevations(gpx, only_missing=True, smooth=True)
    
    # Calculate statistics
    elevations = []
    distances = []
    prev_point = None
    
    for track in gpx.tracks:
        for segment in track.segments:
            for point in segment.points:
                if point.elevation is not None:
                    elevations.append(point.elevation)
                
                if prev_point:
                    distance = point.distance_2d(prev_point)
                    if distance:
                        distances.append(distance)
                prev_point = point
    
    total_distance = sum(distances) if distances else 0
    elevation_gain = sum(
        max(0, elevations[i] - elevations[i-1]) 
        for i in range(1, len(elevations))
    ) if len(elevations) > 1 else 0
    
    return {
        'filename': filename,
        'total_points': gpx.get_track_points_no(),
        'original_elevations': original_elevations,
        'final_elevations': len(elevations),
        'min_elevation': min(elevations) if elevations else None,
        'max_elevation': max(elevations) if elevations else None,
        'total_distance_km': total_distance / 1000,
        'elevation_gain_m': elevation_gain
    }

# Process multiple files
stats = [process_gpx_with_stats(f) for f in ['hike1.gpx', 'hike2.gpx']]

for stat in stats:
    print(f"\n{stat['filename']}:")
    print(f"  Points: {stat['total_points']}")
    print(f"  Elevations added: {stat['final_elevations'] - stat['original_elevations']}")
    print(f"  Distance: {stat['total_distance_km']:.1f} km")
    print(f"  Elevation: {stat['min_elevation']:.0f}m - {stat['max_elevation']:.0f}m")
    print(f"  Total gain: {stat['elevation_gain_m']:.0f}m")

Integration with GPXpy

SRTM.py is designed to work seamlessly with the gpxpy library for GPX file processing:

Required Installation:

pip install gpxpy SRTM.py

Basic GPXpy Integration:

import gpxpy
import srtm

# Parse GPX from string
gpx_string = """<?xml version="1.0"?>
<gpx version="1.1" creator="example">
  <trk>
    <trkseg>
      <trkpt lat="45.0" lon="7.0"></trkpt>
      <trkpt lat="45.1" lon="7.1"></trkpt>
    </trkseg>
  </trk>
</gpx>"""

gpx = gpxpy.parse(gpx_string)
elevation_data = srtm.get_data()
elevation_data.add_elevations(gpx)

# Output enhanced GPX
print(gpx.to_xml())

Performance Considerations

  • Memory Usage: Use batch_mode=True when processing many large GPX files
  • Network Efficiency: SRTM files are cached locally after first download
  • Processing Speed: Smoothing and interpolation add processing time but improve accuracy
  • File Size: Adding elevations increases GPX file size by approximately 10-20%

Install with Tessl CLI

npx tessl i tessl/pypi-srtm-py

docs

advanced-interpolation.md

data-management.md

elevation-queries.md

gpx-processing.md

image-generation.md

index.md

tile.json