Examples

Example 1: Basic GPS Extraction

Extract GPS coordinates from a GoPro video:

 1#!/usr/bin/env python
 2"""
 3Example 1: Basic GPS Extraction from GoPro Video
 4
 5This example demonstrates how to:
 61. Extract GPMF stream from a GoPro MP4 file
 72. Parse GPS data
 83. Print GPS coordinates
 9
10Requirements:
11    - GoPro video file with GPS data
12    - FFmpeg installed on your system
13"""
14
15import gpmf
16
17# Path to your GoPro video file
18VIDEO_FILE = 'GOPR0001.MP4'
19
20def main():
21    print("=" * 60)
22    print("Example 1: Basic GPS Extraction")
23    print("=" * 60)
24    
25    # Step 1: Extract GPMF binary stream from video
26    print("\n[1/3] Extracting GPMF stream from video...")
27    try:
28        stream = gpmf.io.extract_gpmf_stream(VIDEO_FILE)
29        print(f"✓ Extracted {len(stream)} bytes of GPMF data")
30    except Exception as e:
31        print(f"✗ Error extracting stream: {e}")
32        print("\nMake sure:")
33        print("  - Video file exists")
34        print("  - FFmpeg is installed")
35        print("  - Video contains GPMF metadata")
36        return
37    
38    # Step 2: Extract GPS blocks from stream
39    print("\n[2/3] Parsing GPS blocks...")
40    try:
41        gps_blocks = gpmf.gps.extract_gps_blocks(stream)
42        print(f"✓ Found {len(gps_blocks)} GPS blocks")
43    except Exception as e:
44        print(f"✗ Error parsing GPS: {e}")
45        return
46    
47    # Step 3: Parse GPS data
48    print("\n[3/3] Processing GPS data...")
49    gps_data = list(map(gpmf.gps.parse_gps_block, gps_blocks))
50    
51    if not gps_data:
52        print("✗ No GPS data found in video")
53        print("\nPossible reasons:")
54        print("  - GPS was disabled during recording")
55        print("  - Camera was indoors (no GPS fix)")
56        print("  - Older GoPro model without GPS")
57        return
58    
59    print(f"✓ Parsed {len(gps_data)} GPS points")
60    
61    # Display first 5 GPS points
62    print("\n" + "=" * 60)
63    print("First 5 GPS Points:")
64    print("=" * 60)
65    
66    for i, point in enumerate(gps_data[:5], 1):
67        print(f"\nPoint {i}:")
68        print(f"  Latitude:    {point.get('lat', 'N/A'):.6f}°")
69        print(f"  Longitude:   {point.get('lon', 'N/A'):.6f}°")
70        print(f"  Altitude:    {point.get('alt', 'N/A'):.1f} m")
71        print(f"  Speed (2D):  {point.get('speed_2d', 0):.2f} m/s")
72        print(f"  Timestamp:   {point.get('timestamp', 'N/A')}")
73    
74    # Summary statistics
75    print("\n" + "=" * 60)
76    print("Summary Statistics:")
77    print("=" * 60)
78    
79    latitudes = [p.get('lat') for p in gps_data if p.get('lat')]
80    longitudes = [p.get('lon') for p in gps_data if p.get('lon')]
81    altitudes = [p.get('alt') for p in gps_data if p.get('alt')]
82    speeds = [p.get('speed_2d', 0) for p in gps_data]
83    
84    if latitudes and longitudes:
85        print(f"\nTotal GPS points:  {len(gps_data)}")
86        print(f"Latitude range:    {min(latitudes):.6f}° to {max(latitudes):.6f}°")
87        print(f"Longitude range:   {min(longitudes):.6f}° to {max(longitudes):.6f}°")
88        
89        if altitudes:
90            print(f"Altitude range:    {min(altitudes):.1f} m to {max(altitudes):.1f} m")
91        
92        if speeds:
93            print(f"Max speed:         {max(speeds):.2f} m/s ({max(speeds) * 3.6:.1f} km/h)")
94    
95    print("\n✓ Done!")
96
97
98if __name__ == '__main__':
99    main()

Example 2: Export to GPX

Export GPS track to GPX format:

  1#!/usr/bin/env python
  2"""
  3Example 2: Export GPS Track to GPX Format
  4
  5This example demonstrates how to:
  61. Extract GPS data from GoPro video
  72. Convert to GPX format
  83. Save GPX file for use in mapping applications
  9
 10GPX files can be imported into:
 11    - Google Earth
 12    - Strava
 13    - Garmin Connect
 14    - MapMyRide
 15    - And many other GPS applications
 16"""
 17
 18import gpmf
 19import gpxpy
 20import gpxpy.gpx
 21from datetime import datetime
 22
 23# Configuration
 24VIDEO_FILE = 'GOPR0001.MP4'
 25OUTPUT_GPX = 'track.gpx'
 26
 27def main():
 28    print("=" * 60)
 29    print("Example 2: Export to GPX Format")
 30    print("=" * 60)
 31    
 32    # Extract GPMF stream
 33    print("\n[1/4] Extracting GPMF stream...")
 34    try:
 35        stream = gpmf.io.extract_gpmf_stream(VIDEO_FILE)
 36        print(f"✓ Extracted {len(stream)} bytes")
 37    except Exception as e:
 38        print(f"✗ Error: {e}")
 39        return
 40    
 41    # Extract and parse GPS
 42    print("\n[2/4] Parsing GPS data...")
 43    try:
 44        gps_blocks = gpmf.gps.extract_gps_blocks(stream)
 45        gps_data = list(map(gpmf.gps.parse_gps_block, gps_blocks))
 46        print(f"✓ Parsed {len(gps_data)} GPS points")
 47    except Exception as e:
 48        print(f"✗ Error: {e}")
 49        return
 50    
 51    if not gps_data:
 52        print("✗ No GPS data found")
 53        return
 54    
 55    # Create GPX structure
 56    print("\n[3/4] Creating GPX structure...")
 57    gpx = gpxpy.gpx.GPX()
 58    
 59    # Add metadata
 60    gpx.creator = "pygpmf-oz v0.3.0"
 61    gpx.name = f"GoPro Track - {datetime.now().strftime('%Y-%m-%d')}"
 62    gpx.description = f"GPS track extracted from {VIDEO_FILE}"
 63    
 64    # Create track
 65    gpx_track = gpxpy.gpx.GPXTrack()
 66    gpx_track.name = "GoPro GPS Track"
 67    gpx.tracks.append(gpx_track)
 68    
 69    # Create segment and add points
 70    gpx_segment = gpmf.gps.make_gpx_segment(gps_data)
 71    gpx_track.segments.append(gpx_segment)
 72    
 73    print(f"✓ Created GPX with {len(gpx_segment.points)} points")
 74    
 75    # Save GPX file
 76    print(f"\n[4/4] Saving to {OUTPUT_GPX}...")
 77    try:
 78        with open(OUTPUT_GPX, 'w', encoding='utf-8') as f:
 79            f.write(gpx.to_xml())
 80        print(f"✓ Saved GPX file")
 81    except Exception as e:
 82        print(f"✗ Error saving: {e}")
 83        return
 84    
 85    # Display GPX statistics
 86    print("\n" + "=" * 60)
 87    print("GPX Statistics:")
 88    print("=" * 60)
 89    
 90    # Calculate statistics using gpxpy
 91    moving_data = gpx.get_moving_data()
 92    uphill_downhill = gpx.get_uphill_downhill()
 93    
 94    if moving_data:
 95        print(f"\nMoving time:       {moving_data.moving_time / 60:.1f} minutes")
 96        print(f"Stopped time:      {moving_data.stopped_time / 60:.1f} minutes")
 97        print(f"Moving distance:   {moving_data.moving_distance / 1000:.2f} km")
 98        print(f"Max speed:         {moving_data.max_speed * 3.6:.1f} km/h")
 99    
100    if uphill_downhill:
101        print(f"\nElevation gain:    {uphill_downhill.uphill:.1f} m")
102        print(f"Elevation loss:    {uphill_downhill.downhill:.1f} m")
103    
104    # Bounds
105    bounds = gpx.get_bounds()
106    if bounds:
107        print(f"\nBounds:")
108        print(f"  North: {bounds.max_latitude:.6f}°")
109        print(f"  South: {bounds.min_latitude:.6f}°")
110        print(f"  East:  {bounds.max_longitude:.6f}°")
111        print(f"  West:  {bounds.min_longitude:.6f}°")
112    
113    print("\n" + "=" * 60)
114    print("Next steps:")
115    print("=" * 60)
116    print(f"\n1. Open {OUTPUT_GPX} in Google Earth")
117    print("2. Upload to Strava or Garmin Connect")
118    print("3. View in any GPX-compatible mapping software")
119    print("\n✓ Done!")
120
121
122if __name__ == '__main__':
123    main()

Example 3: Visualize GPS Track

Create a visual map with your GPS track:

 1#!/usr/bin/env python
 2"""
 3Example 3: Visualize GPS Track on Map
 4
 5This example demonstrates how to:
 61. Extract GPS data from GoPro video
 72. Create a visual map with the GPS track
 83. Save as an HTML file or PNG image
 9
10Requirements:
11    - geopandas
12    - matplotlib
13    - contextily (for map tiles)
14"""
15
16import gpmf
17
18# Configuration
19VIDEO_FILE = 'GOPR0001.MP4'
20OUTPUT_PNG = 'gps_track.png'
21OUTPUT_HTML = 'gps_track.html'
22
23def main():
24    print("=" * 60)
25    print("Example 3: Visualize GPS Track")
26    print("=" * 60)
27    
28    # Extract GPMF stream
29    print("\n[1/3] Extracting GPS data...")
30    try:
31        stream = gpmf.io.extract_gpmf_stream(VIDEO_FILE)
32        print(f"✓ Extracted {len(stream)} bytes")
33    except Exception as e:
34        print(f"✗ Error: {e}")
35        return
36    
37    # Create visualization
38    print("\n[2/3] Creating map visualization...")
39    try:
40        gpmf.gps_plot.plot_gps_trace_from_stream(stream)
41        print("✓ Map created")
42    except ImportError as e:
43        print(f"✗ Missing dependency: {e}")
44        print("\nInstall required packages:")
45        print("  pip install geopandas matplotlib contextily")
46        return
47    except Exception as e:
48        print(f"✗ Error: {e}")
49        return
50    
51    print("\n[3/3] Saving visualization...")
52    print(f"✓ Saved to {OUTPUT_PNG}")
53    
54    print("\n" + "=" * 60)
55    print("Map Features:")
56    print("=" * 60)
57    print("\n- GPS track displayed on OpenStreetMap tiles")
58    print("- Start point marked in green")
59    print("- End point marked in red")
60    print("- Track colored by speed (if available)")
61    
62    print("\n✓ Done! Open the image to view your GPS track.")
63
64
65if __name__ == '__main__':
66    main()

More Examples

Find more examples in the examples directory of the repository: https://github.com/ozand/pygpmf-oz/tree/main/examples