Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
8 changes: 8 additions & 0 deletions docs/command_reference.md
Original file line number Diff line number Diff line change
Expand Up @@ -298,6 +298,13 @@ Images are placed on the track by their capture time; videos by the times of the
- Files outside the track fail with `MapillaryOutsideGPXTrackError`: images captured before the track starts,
after it ends, or in a gap of more than an hour between two points (such as between two trips in one file).
Set `MAPILLARY_TOOLS_MAX_GPX_GAP_SECONDS` to allow longer gaps.
- GPS loggers, such as the Mapillary apps, start a new GPX track segment (`<trkseg>`) where they lost the GPS.
`process` keeps such a gap inside a video in its description (`MAPGPSTrackGaps`), where the next segment starts
more than 5 seconds (`MAPILLARY_TOOLS_MAX_GPX_SEGMENT_GAP_SECONDS`) after the previous one ends, with no point
of another segment in between. Where the start or the end of the video falls in such a gap, the fixes on its far
side are left out, and the video has no position until the first fix after the gap (or after the last one before
it). The track of a video without a GPS clock that lasts twice as long as the video or more may be that of a
timelapse, and keeps no gap. Sampling (`video_process`) still places frames across these gaps.
- If the camera and GPS clocks differ, `--interpolation_offset_time N` adds N seconds to the capture times before
placing them. It moves videos geotagged from a track too: in a folder with images and videos, an offset that
fixes the image camera clock can push the videos off their tracks. Process the images alone with
Expand Down Expand Up @@ -602,6 +609,7 @@ in the user data folder (or `MAPILLARY_TOOLS_EXIFTOOL_INSTALL_DIR`) and prints t
| `MAPILLARY_TOOLS_EXIFTOOL_INSTALL_DIR` | in the user data folder | Where `install_exiftool` installs ExifTool. |
| `MAPILLARY_TOOLS_FFMPEG_PATH`, `MAPILLARY_TOOLS_FFPROBE_PATH` | `ffmpeg`, `ffprobe` | The FFmpeg executables. |
| `MAPILLARY_TOOLS_MAX_GPX_GAP_SECONDS` | 3600 | The longest gap in a GPX or NMEA track that files can be placed in, and how far from the rest of a track ExifTool points can be. |
| `MAPILLARY_TOOLS_MAX_GPX_SEGMENT_GAP_SECONDS` | 5 | The longest time between two segments of a GPX track inside a video that `process` keeps no gap for. |
| `MAPILLARY_UPLOAD_HISTORY_PATH` | in the user data folder | Where the upload history is kept. |
| `MAPILLARY_TOOLS_MAX_SEQUENCE_LENGTH` | 1000 | The most images in a sequence. |
| `MAPILLARY_TOOLS_MAX_CAPTURE_SPEED_KMH` | 400 | The fastest average speed that passes the speed check. |
Expand Down
8 changes: 8 additions & 0 deletions mapillary_tools/constants.py
Original file line number Diff line number Diff line change
Expand Up @@ -87,6 +87,14 @@ def _parse_scaled_integers(
# logger switched off between trips: the time inside it is outside the track,
# like the time before its start or after its end
MAX_GPX_GAP_SECONDS = float(os.getenv(_ENV_PREFIX + "MAX_GPX_GAP_SECONDS", 3600))
# In seconds. Where a GPX file starts a new track segment more than this after
# the previous one ends, inside a video that process geotags from it, the GPS
# was lost, and the gap is kept in the description of the video
# (MAPGPSTrackGaps). Segments that follow each other a few fixes apart, as one
# logged once a second does, leave no gap
MAX_GPX_SEGMENT_GAP_SECONDS = float(
os.getenv(_ENV_PREFIX + "MAX_GPX_SEGMENT_GAP_SECONDS", 5)
)


############################
Expand Down
2 changes: 1 addition & 1 deletion mapillary_tools/geotag/geotag_images_from_gpx_file.py
Original file line number Diff line number Diff line change
Expand Up @@ -66,7 +66,7 @@ def _read_gpx_points(source_path: Path) -> list[geo.Point]:
utils.warn_once(
source_path,
("tracks", len(tracks)),
"Found %s tracks in the GPX file %s. Will merge points in all the tracks as a single track for interpolation",
"Found %s track segments in the GPX file %s. Will merge their points into one track by time for interpolation",
len(tracks),
source_path,
)
Expand Down
203 changes: 187 additions & 16 deletions mapillary_tools/geotag/video_extractors/gpx.py
Original file line number Diff line number Diff line change
Expand Up @@ -224,6 +224,11 @@ def __init__(
# What extract() warned of about the placement of the track, which it
# returns with the metadata of the video
self.warnings: list[exceptions.MapillaryProcessWarning] = []
# The last point of a segment of the track file and the first of the
# next, as _read_gpx_points() reads them (see _segment_boundaries).
# They are those of the track it returns, which placing the track on
# the video moves in place
self._segment_boundaries: list[tuple[geo.Point, geo.Point]] = []

@override
def extract(self) -> types.VideoMetadata:
Expand All @@ -245,8 +250,11 @@ def extract(self) -> types.VideoMetadata:
rate = self._duration_ratio()
self._apply_offset_time(gpx_points, rate=rate)
self._check_coverage(gpx_points, gpx_unix_times, [], start_clock, rate)
segment_gaps: list[tuple[float, float]] = []
if self.clip_to_video:
gpx_points = self._clip_to_video(gpx_points, start_clock, rate)
gpx_points, segment_gaps = self._clip_to_video(
gpx_points, start_clock, rate
)
# The camera that the video names is no less known without its GPS
make, model = extract_make_and_model(self.video_path)
return types.VideoMetadata(
Expand All @@ -257,6 +265,7 @@ def extract(self) -> types.VideoMetadata:
make=make,
model=model,
warnings=list(self.warnings),
track_gaps=segment_gaps,
)

video_clock = self._read_video_clock(native_video_metadata.points)
Expand Down Expand Up @@ -306,11 +315,15 @@ def extract(self) -> types.VideoMetadata:
None if self.sync_mode is SyncMode.REBASE else clock,
rate,
)
segment_gaps = []
if self.clip_to_video:
gpx_points = self._clip_to_video(gpx_points, clock, rate)
gpx_points, segment_gaps = self._clip_to_video(gpx_points, clock, rate)

return dataclasses.replace(
native_video_metadata, points=gpx_points, warnings=list(self.warnings)
native_video_metadata,
points=gpx_points,
warnings=list(self.warnings),
track_gaps=segment_gaps,
)

def read_tracks(self) -> None:
Expand All @@ -332,7 +345,8 @@ def read_tracks(self) -> None:

def _read_gpx_points(self) -> list[geo.Point]:
"""
Read the points of the GPX file, merged into one track in time order
Read the points of the GPX file, merged into one track in time order,
and the boundaries between its segments (see _segment_boundaries)
"""
warned = self._tracks is not None
gpx_tracks = self._parse_tracks()
Expand All @@ -343,16 +357,16 @@ def _read_gpx_points(self) -> list[geo.Point]:
# other readers of the file. With the garbage collector paused, as
# there are as many as the file has points (see utils.gc_paused())
with utils.gc_paused():
gpx_points = [
dataclasses.replace(p)
segments = [
[dataclasses.replace(p) for p in track if _GPS_EPOCH <= p.time]
for track in gpx_tracks
for p in track
if _GPS_EPOCH <= p.time
]
gpx_points = [p for segment in segments for p in segment]

# The tracks need not be in time order, and interpolation needs the
# merged points to be
gpx_points.sort(key=lambda p: p.time)
self._segment_boundaries = _segment_boundaries(segments, gpx_points)
return gpx_points

def _warn_of_tracks(self, gpx_tracks: list[list[geo.Point]]) -> None:
Expand All @@ -361,14 +375,19 @@ def _warn_of_tracks(self, gpx_tracks: list[list[geo.Point]]) -> None:
once for each file
"""
if 1 < len(gpx_tracks):
geotag_utils.warn_once(
self.gpx_path,
("tracks", len(gpx_tracks)),
"Found %d tracks in the %s file %s. Will merge points in all the tracks as a single track for interpolation",
# Each <trkseg> of each <trk> is read as a track
message = "Found %d track segments in the %s file %s. Will merge their points into one track by time for interpolation"
args: tuple[object, ...] = (
len(gpx_tracks),
self.file_format,
self.gpx_path,
)
if self.clip_to_video:
message += ", keeping a gap of more than %g seconds between two segments inside a video as a gap"
args += (constants.MAX_GPX_SEGMENT_GAP_SECONDS,)
geotag_utils.warn_once(
self.gpx_path, ("tracks", len(gpx_tracks)), message, *args
)

num_points = sum(len(track) for track in gpx_tracks)
num_kept = sum(1 for track in gpx_tracks for p in track if _GPS_EPOCH <= p.time)
Expand Down Expand Up @@ -409,7 +428,7 @@ def _read_tracks(self) -> list[list[geo.Point]]:

def _clip_to_video(
self, gpx_points: list[geo.Point], clock: VideoClock | None, rate: float
) -> list[geo.Point]:
) -> tuple[list[geo.Point], list[tuple[float, float]]]:
"""
Clip a GPX track to the video, from video time 0 to where the video
ends along it, which is known when a **clock** gives its pace along
Expand All @@ -431,14 +450,98 @@ def _clip_to_video(
nothing of where the video was: the fixes on its far side are left
out, with no point interpolated across it, as if the track started
(or ended) there. One inside the video fails it (see _check_coverage).
So is a gap between two segments of the track (see _segment_gaps)
that video time 0 or the end of the video falls in.

Return the clipped track, and the video times of the points on either
side of each gap between two of its segments inside the video.
"""
video_duration = _video_duration(self.video_path)
gpx_points = _leave_out_far_side_of_gaps(
gpx_points, constants.MAX_GPX_GAP_SECONDS, video_duration, rate
)
segment_gaps = self._segment_gaps(gpx_points, clock, rate, video_duration)
if segment_gaps:
gpx_points = _leave_out_far_side_of_gaps(
gpx_points,
constants.MAX_GPX_SEGMENT_GAP_SECONDS,
video_duration,
rate,
between=segment_gaps,
)
if clock is None:
return _clip_track(gpx_points, None)
return _clip_track(gpx_points, video_duration)
gpx_points = _clip_track(gpx_points, None)
else:
gpx_points = _clip_track(gpx_points, video_duration)
return gpx_points, [
(before.time, after.time)
for before, after in segment_gaps
if video_duration is not None
and 0 <= before.time
and after.time <= video_duration
]

def _segment_gaps(
self,
gpx_points: T.Sequence[geo.Point],
clock: VideoClock | None,
rate: float,
video_duration: float | None,
) -> list[tuple[geo.Point, geo.Point]]:
"""
The gaps of a GPX track, placed on the video, where the GPS was lost
in the video: the boundaries between two of its segments (see
_segment_boundaries) that leave more than
constants.MAX_GPX_SEGMENT_GAP_SECONDS (at **rate** GPS seconds per
second of video) between them, inside the video or across its start
or end. A GPS logger, such as that of the Mapillary apps, starts a new
segment where it lost the GPS, so the track says nothing of where the
video was in the gap. Each gap is given by the points on either side
of it.

A gap before the start or after the end of the video is none of them.
Nor is any gap of the track of a video without a **clock** that lasts
twice as long as the video or more: it may be that of a timelapse (see
_check_length), whose frames are paced along the whole track.
"""
if (
video_duration is None
or len(gpx_points) < 2
or (
clock is None
and 2 * video_duration
<= gpx_points[-1].time - max(gpx_points[0].time, 0.0)
)
):
return []

gaps: list[tuple[geo.Point, geo.Point]] = []
for before, after in self._segment_boundaries:
if not (before.time < video_duration and 0 < after.time):
continue
# Not "<=", so that no gap is kept for a limit that is no number
if not (
constants.MAX_GPX_SEGMENT_GAP_SECONDS
< gps_seconds_apart(before, after, rate)
):
continue
gaps.append((before, after))
before_time, after_time = before.get_unix_time(), after.get_unix_time()
LOG.warning(
"The %s track in %s has %s between two of its segments, in the video %s (%s to %s seconds into it): no position of the video is known in it",
self.file_format,
self.gpx_path,
describe_gap(
before,
after,
before.time if before_time is None else before_time,
after.time if after_time is None else after_time,
),
self.video_path,
round(max(before.time, 0.0), 3),
round(min(after.time, video_duration), 3),
)
return gaps

def _place_without_video_gps(
self, gpx_points: T.Sequence[geo.Point]
Expand Down Expand Up @@ -1305,16 +1408,81 @@ def describe_long_track(
)


def _segment_boundaries(
segments: T.Sequence[T.Sequence[geo.Point]], track: T.Sequence[geo.Point]
) -> list[tuple[geo.Point, geo.Point]]:
"""
The boundaries between the segments of a track, in time order: the last
point of a segment, and the point that follows it in **track**, the
points of all the segments in time order, where that is the first point
of another segment, and later. Where segments overlap, as the tracks of
two loggers merged into one file do, the points of one fall between the
ends of the other, which leave no boundary there. Segments that touch,
one starting when the other ends, leave none either

>>> p = lambda t: geo.Point(time=t, lat=0, lon=0, alt=None, angle=None)
>>> def boundaries(*segments):
... track = sorted((q for s in segments for q in s), key=lambda q: q.time)
... return [(a.time, b.time) for a, b in _segment_boundaries(segments, track)]
>>> boundaries([p(30), p(31)], [p(0), p(1)], [p(10), p(11)])
[(1, 10), (11, 30)]
>>> boundaries([p(0), p(10)], [p(5), p(15)])
[]
>>> boundaries([p(0), p(1)], [p(1), p(2)], [p(9), p(10)], [p(15), p(20)], [p(18)])
[(2, 9), (10, 15)]
>>> boundaries([p(0), p(1)], [])
[]
"""
if len(segments) < 2:
return []

# The first point of each segment, and the last, the earliest and the
# latest in the track where several points have their time
firsts: dict[int, int] = {}
lasts: list[tuple[int, geo.Point]] = []
for idx, segment in enumerate(segments):
if segment:
firsts[id(min(segment, key=lambda p: p.time))] = idx
lasts.append((idx, max(reversed(segment), key=lambda p: p.time)))

boundaries: list[tuple[geo.Point, geo.Point]] = []
for idx, last in lasts:
pos = _index_in_track(track, last) + 1
if pos < len(track):
after = track[pos]
other = firsts.get(id(after))
if other is not None and other != idx and last.time < after.time:
boundaries.append((last, after))
boundaries.sort(key=lambda boundary: boundary[0].time)
return boundaries


def _index_in_track(track: T.Sequence[geo.Point], point: geo.Point) -> int:
"""The index of a point in a track in time order"""
lo, hi = 0, len(track)
while lo < hi:
mid = (lo + hi) // 2
if track[mid].time < point.time:
lo = mid + 1
else:
hi = mid
while track[lo] is not point:
lo += 1
return lo


def _leave_out_far_side_of_gaps(
points: T.Sequence[geo.Point],
max_gap: float,
end: float | None,
rate: float = 1.0,
between: T.Collection[tuple[geo.Point, geo.Point]] | None = None,
) -> list[geo.Point]:
"""
Leave out of a track, sorted by time, the points on the far side of a gap
of more than **max_gap** GPS seconds (see gps_seconds_apart()) that time 0,
or **end** (None if unknown), falls in
or **end** (None if unknown), falls in; only of a gap **between** one of
these pairs of points, if given

>>> track = [geo.Point(time=t, lat=t, lon=0, alt=None, angle=None) for t in (-9000, 99, 200, 9000)]
>>> [p.time for p in _leave_out_far_side_of_gaps(track, 3600, 300)]
Expand All @@ -1324,8 +1492,11 @@ def _leave_out_far_side_of_gaps(
>>> [p.time for p in _leave_out_far_side_of_gaps(track, 10000, 300)]
[-9000, 99, 200, 9000]
"""
pairs = None if between is None else {(id(b), id(a)) for b, a in between}
start, stop = 0, len(points)
for idx, (before, after) in enumerate(geo.pairwise(points)):
if pairs is not None and (id(before), id(after)) not in pairs:
continue
if gps_seconds_apart(before, after, rate) <= max_gap:
continue
if before.time < 0 < after.time:
Expand Down
Loading
Loading