Files
2026-11-22 19:34:02 +01:00

160 lines
4.7 KiB
Python
Executable File

#!/usr/bin/env python3
"""Visualize a GPX track: route in upper half, stats in lower half, photo as background."""
import argparse
from datetime import timedelta
import gpxpy
import matplotlib.pyplot as plt
from matplotlib.patches import Rectangle
import numpy as np
from PIL import Image, ImageFilter, ImageOps
def parse_gpx(filepath):
with open(filepath) as f:
gpx = gpxpy.parse(f)
return [
(p.latitude, p.longitude, p.time)
for track in gpx.tracks
for segment in track.segments
for p in segment.points
]
def haversine_km(lat1, lon1, lat2, lon2):
R = 6371.0
dlat = np.radians(lat2 - lat1)
dlon = np.radians(lon2 - lon1)
a = (
np.sin(dlat / 2) ** 2
+ np.cos(np.radians(lat1)) * np.cos(np.radians(lat2)) * np.sin(dlon / 2) ** 2
)
return R * 2 * np.arctan2(np.sqrt(a), np.sqrt(1 - a))
def total_distance_km(points):
return sum(
haversine_km(points[i][0], points[i][1], points[i + 1][0], points[i + 1][1])
for i in range(len(points) - 1)
)
def format_pace(seconds, dist_km):
if dist_km <= 0:
return "\u2014"
pace = seconds / dist_km
return f"{int(pace // 60)}:{int(pace % 60):02d} min/km"
def main():
parser = argparse.ArgumentParser(description="GPX track visualizer with photo background")
parser.add_argument("gpx", help="GPX file")
parser.add_argument("photo", help="Background photo")
parser.add_argument("-o", "--output", help="Save to file")
args = parser.parse_args()
points = parse_gpx(args.gpx)
if not points:
print("No track points found.")
return
lats = np.array([p[0] for p in points])
lons = np.array([p[1] for p in points])
dist = total_distance_km(points)
if points[0][2] and points[-1][2]:
elapsed = (points[-1][2] - points[0][2]).total_seconds()
time_str = f"{str(timedelta(seconds=int(elapsed)))} h"
pace_str = format_pace(elapsed, dist)
else:
time_str = pace_str = "N/A"
img = Image.open(args.photo)
transposed = ImageOps.exif_transpose(img)
if transposed is not None:
img = transposed
img_w, img_h = img.size
# --- Blurred version for track box background ---
img_blur = img.filter(ImageFilter.GaussianBlur(radius=40))
fig = plt.figure(figsize=(9, 16))
fig.patch.set_facecolor("black")
# --- Background photo (full figure) ---
ax_bg = fig.add_axes([0, 0, 1, 1], zorder=0)
ax_bg.imshow(img, aspect="auto")
ax_bg.set_axis_off()
# --- Blurred box behind the track ---
left_fig, bottom_fig, w_fig, h_fig = 0.06, 0.47, 0.88, 0.50
# Map figure coords -> image pixel coords
# imshow with origin='upper': figure_y=0 → img row = img_h (bottom)
# figure_y=1 → img row = 0 (top)
col_start = int(left_fig * img_w)
col_end = int((left_fig + w_fig) * img_w)
row_start = int((1 - bottom_fig - h_fig) * img_h)
row_end = int((1 - bottom_fig) * img_h)
img_blur_arr = np.array(img_blur)
crop_blur = img_blur_arr[row_start:row_end, col_start:col_end]
ax_blur = fig.add_axes([left_fig, bottom_fig, w_fig, h_fig], zorder=1, facecolor="none")
ax_blur.imshow(crop_blur, aspect="auto")
ax_blur.set_axis_off()
ax_blur.add_patch(Rectangle(
(0, 0), 1, 1, transform=ax_blur.transAxes,
fill=False, edgecolor="white", linewidth=1.5,
))
# --- Track with padding inside the box ---
pad_x = w_fig * 0.05
pad_y = h_fig * 0.05
ax1 = fig.add_axes(
[left_fig + pad_x, bottom_fig + pad_y, w_fig - 2 * pad_x, h_fig - 2 * pad_y],
zorder=2, facecolor="none",
)
ax1.set_axis_off()
ax1.plot(lons, lats, color="#f0e8d8", linewidth=2.5, zorder=5)
ax1.scatter(lons[0], lats[0], c="#90d090", s=50, zorder=6)
ax1.scatter(lons[-1], lats[-1], c="#d09090", s=50, zorder=6)
mid_lat = np.mean(lats)
ax1.set_aspect(1.0 / np.cos(np.radians(mid_lat)))
# --- Lower half: stats ---
ax2 = fig.add_axes([0, 0, 1, 1], zorder=3, facecolor="none")
ax2.set_axis_off()
ax2.text(
0.5, 0.26, f"{dist:.2f} km",
fontsize=56, fontweight="bold", color="white",
ha="center", va="center", transform=fig.transFigure,
)
ax2.text(
0.5, 0.155, time_str,
fontsize=36, fontweight="bold", color="white",
ha="center", va="center", transform=fig.transFigure,
)
ax2.text(
0.5, 0.06, pace_str,
fontsize=30, fontweight="bold", color="white",
ha="center", va="center", transform=fig.transFigure,
)
if args.output:
plt.savefig(args.output, dpi=300, bbox_inches="tight", facecolor="black", pad_inches=0)
else:
plt.show()
if __name__ == "__main__":
main()