Momentum
A library for solving nonlinear optimization problems related to human body kinematics
Loading...
Searching...
No Matches
marker_gap_fill.cpp
Go to the documentation of this file.
1/*
2 * Copyright (c) Meta Platforms, Inc. and affiliates.
3 *
4 * This source code is licensed under the MIT license found in the
5 * LICENSE file in the root directory of this source tree.
6 */
7
9
11
12#include <algorithm>
13#include <cmath>
14#include <string>
15#include <unordered_map>
16#include <vector>
17
18namespace momentum {
19
20namespace {
21
34void normalizeMarkerFrames(std::vector<std::vector<Marker>>& markerData) {
35 if (markerData.empty()) {
36 return;
37 }
38
39 // Quick check: if all frames have the same count as frame[0], assume
40 // they are already consistent (the common case).
41 const size_t firstFrameCount = markerData[0].size();
42 bool allSame = true;
43 for (const auto& frame : markerData) {
44 if (frame.size() != firstFrameCount) {
45 allSame = false;
46 break;
47 }
48 }
49 if (allSame) {
50 return;
51 }
52
53 // Build canonical name ordering: frame[0] first, then append new names.
54 std::vector<std::string> canonicalNames;
55 std::unordered_map<std::string, size_t> nameToIndex;
56 canonicalNames.reserve(firstFrameCount + 16);
57
58 for (const auto& frame : markerData) {
59 for (const auto& marker : frame) {
60 if (nameToIndex.find(marker.name) == nameToIndex.end()) {
61 nameToIndex[marker.name] = canonicalNames.size();
62 canonicalNames.push_back(marker.name);
63 }
64 }
65 }
66
67 const size_t totalMarkers = canonicalNames.size();
68
69 // Rebuild each frame in canonical order.
70 for (auto& frame : markerData) {
71 if (frame.size() == totalMarkers) {
72 // Check if already in canonical order.
73 bool inOrder = true;
74 for (size_t i = 0; i < totalMarkers; ++i) {
75 if (frame[i].name != canonicalNames[i]) {
76 inOrder = false;
77 break;
78 }
79 }
80 if (inOrder) {
81 continue;
82 }
83 }
84
85 // Build new frame with occluded placeholders.
86 std::vector<Marker> normalized(totalMarkers);
87 for (size_t i = 0; i < totalMarkers; ++i) {
88 normalized[i].name = canonicalNames[i];
89 normalized[i].occluded = true;
90 normalized[i].confidence = 0.0f;
91 }
92
93 // Fill in markers that exist in this frame.
94 for (auto& marker : frame) {
95 const size_t idx = nameToIndex.at(marker.name);
96 normalized[idx] = std::move(marker);
97 }
98
99 frame = std::move(normalized);
100 }
101}
102
112Vector3d estimateVelocity(
113 const std::vector<std::vector<Marker>>& markerData,
114 size_t markerIdx,
115 size_t anchorFrame,
116 size_t windowSize,
117 bool forward) {
118 // Collect visible frames in the requested direction
119 std::vector<std::pair<size_t, Vector3d>> samples;
120 const auto numFrames = markerData.size();
121
122 if (forward) {
123 for (size_t f = anchorFrame; f < numFrames && samples.size() < windowSize; ++f) {
124 const auto& m = markerData[f][markerIdx];
125 if (!m.occluded) {
126 samples.emplace_back(f, m.pos);
127 }
128 }
129 } else {
130 // Walk backward; use signed arithmetic carefully
131 for (size_t f = anchorFrame + 1; f > 0 && samples.size() < windowSize; --f) {
132 const auto& m = markerData[f - 1][markerIdx];
133 if (!m.occluded) {
134 samples.emplace_back(f - 1, m.pos);
135 }
136 }
137 // Reverse so samples are in chronological order
138 std::reverse(samples.begin(), samples.end());
139 }
140
141 if (samples.size() < 2) {
142 return Vector3d::Zero();
143 }
144
145 // Least-squares linear fit: average finite differences weighted equally
146 Vector3d totalVel = Vector3d::Zero();
147 size_t count = 0;
148 for (size_t i = 1; i < samples.size(); ++i) {
149 const double dt =
150 static_cast<double>(samples[i].first) - static_cast<double>(samples[i - 1].first);
151 if (dt > 0) {
152 totalVel += (samples[i].second - samples[i - 1].second) / dt;
153 ++count;
154 }
155 }
156
157 if (count == 0) {
158 return Vector3d::Zero();
159 }
160 return totalVel / static_cast<double>(count);
161}
162
171hermite(const Vector3d& p0, const Vector3d& v0, const Vector3d& p1, const Vector3d& v1, double t) {
172 const double t2 = t * t;
173 const double t3 = t2 * t;
174 const double h00 = 2.0 * t3 - 3.0 * t2 + 1.0;
175 const double h10 = t3 - 2.0 * t2 + t;
176 const double h01 = -2.0 * t3 + 3.0 * t2;
177 const double h11 = t3 - t2;
178 return h00 * p0 + h10 * v0 + h01 * p1 + h11 * v1;
179}
180
182float cosineBlendWeight(size_t step, size_t totalSteps) {
183 if (totalSteps == 0) {
184 return 0.0f;
185 }
186 const double t = static_cast<double>(step) / static_cast<double>(totalSteps);
187 // Cosine ramp: 1 at t=0, 0 at t=1
188 return static_cast<float>(0.5 * (1.0 + std::cos(t * pi<double>())));
189}
190
192struct OcclusionGap {
193 size_t startFrame; // first occluded frame
194 size_t endFrame; // one past last occluded frame (exclusive)
195 bool hasVisibleBefore; // is there a visible frame before startFrame?
196 bool hasVisibleAfter; // is there a visible frame at or after endFrame?
197};
198
200std::vector<OcclusionGap> findGaps(
201 const std::vector<std::vector<Marker>>& markerData,
202 size_t markerIdx) {
203 const auto numFrames = markerData.size();
204 std::vector<OcclusionGap> gaps;
205
206 size_t f = 0;
207 while (f < numFrames) {
208 // Skip visible frames
209 if (!markerData[f][markerIdx].occluded) {
210 ++f;
211 continue;
212 }
213
214 // Found start of an occluded run
215 const size_t gapStart = f;
216 while (f < numFrames && markerData[f][markerIdx].occluded) {
217 ++f;
218 }
219
220 gaps.push_back({
221 gapStart,
222 f,
223 gapStart > 0 && !markerData[gapStart - 1][markerIdx].occluded,
224 f < numFrames && !markerData[f][markerIdx].occluded,
225 });
226 }
227
228 return gaps;
229}
230
232void fillTemporaryGap(
233 std::vector<std::vector<Marker>>& markerData,
234 size_t markerIdx,
235 const OcclusionGap& gap,
236 const GapFillConfig& config) {
237 const size_t lastVisibleBefore = gap.startFrame - 1;
238 const size_t firstVisibleAfter = gap.endFrame;
239 const size_t gapLen = gap.endFrame - gap.startFrame;
240
241 const auto& mBefore = markerData[lastVisibleBefore][markerIdx];
242 const auto& mAfter = markerData[firstVisibleAfter][markerIdx];
243
244 // Estimate velocity at gap boundaries (in units/frame)
245 const Vector3d velBefore = estimateVelocity(
246 markerData, markerIdx, lastVisibleBefore, config.velocityWindowFrames, false);
247 const Vector3d velAfter =
248 estimateVelocity(markerData, markerIdx, firstVisibleAfter, config.velocityWindowFrames, true);
249
250 // Scale velocities by gap length for Hermite (tangent = velocity * interval)
251 const auto gapLenD = static_cast<double>(gapLen + 1);
252 const Vector3d scaledVelBefore = velBefore * gapLenD;
253 const Vector3d scaledVelAfter = velAfter * gapLenD;
254
255 for (size_t f = gap.startFrame; f < gap.endFrame; ++f) {
256 const double t = static_cast<double>(f - lastVisibleBefore) / gapLenD;
257 auto& m = markerData[f][markerIdx];
258 m.pos = hermite(mBefore.pos, scaledVelBefore, mAfter.pos, scaledVelAfter, t);
259 m.occluded = false;
260 m.confidence = 1.0f;
261 }
262}
263
265void blendOffTrailingDropout(
266 std::vector<std::vector<Marker>>& markerData,
267 size_t markerIdx,
268 const OcclusionGap& gap,
269 const GapFillConfig& config) {
270 const size_t lastVisibleBefore = gap.startFrame - 1;
271 const auto& mBefore = markerData[lastVisibleBefore][markerIdx];
272
273 const Vector3d vel = estimateVelocity(
274 markerData, markerIdx, lastVisibleBefore, config.velocityWindowFrames, false);
275
276 const size_t blendFrames = std::min(config.blendOffFrames, gap.endFrame - gap.startFrame);
277
278 for (size_t i = 0; i < blendFrames; ++i) {
279 const size_t f = gap.startFrame + i;
280 const auto dt = static_cast<double>(f - lastVisibleBefore);
281 auto& m = markerData[f][markerIdx];
282 m.pos = mBefore.pos + vel * dt;
283 m.occluded = false;
284 m.confidence = cosineBlendWeight(i + 1, blendFrames + 1);
285 }
286}
287
289void blendOffLeadingDropout(
290 std::vector<std::vector<Marker>>& markerData,
291 size_t markerIdx,
292 const OcclusionGap& gap,
293 const GapFillConfig& config) {
294 const size_t firstVisibleAfter = gap.endFrame;
295 const auto& mAfter = markerData[firstVisibleAfter][markerIdx];
296
297 const Vector3d vel =
298 estimateVelocity(markerData, markerIdx, firstVisibleAfter, config.velocityWindowFrames, true);
299
300 const size_t gapLen = gap.endFrame - gap.startFrame;
301 const size_t blendFrames = std::min(config.blendOffFrames, gapLen);
302
303 // Fill from end of gap backward
304 for (size_t i = 0; i < blendFrames; ++i) {
305 const size_t f = gap.endFrame - 1 - i;
306 const double dt = static_cast<double>(f) - static_cast<double>(firstVisibleAfter);
307 auto& m = markerData[f][markerIdx];
308 m.pos = mAfter.pos + vel * dt;
309 m.occluded = false;
310 m.confidence = cosineBlendWeight(i + 1, blendFrames + 1);
311 }
312}
313
318size_t computeEffectiveMaxGap(
319 const std::vector<std::vector<Marker>>& markerData,
320 size_t markerIdx,
321 const OcclusionGap& gap,
322 const GapFillConfig& config) {
323 if (gap.hasVisibleBefore && gap.hasVisibleAfter &&
324 config.maxGapFramesStationary > config.maxGapFrames) {
325 const double displacement =
326 (markerData[gap.endFrame][markerIdx].pos - markerData[gap.startFrame - 1][markerIdx].pos)
327 .norm();
328 if (config.maxGapDisplacement > 0.0 && displacement < config.maxGapDisplacement) {
329 const double t = displacement / config.maxGapDisplacement;
330 return static_cast<size_t>(std::round(
331 static_cast<double>(config.maxGapFramesStationary) * (1.0 - t) +
332 static_cast<double>(config.maxGapFrames) * t));
333 }
334 }
335 return config.maxGapFrames;
336}
337
342void suppressShortVisibleSegments(
343 std::vector<std::vector<Marker>>& markerData,
344 size_t markerIdx,
345 size_t minVisibleFrames) {
346 if (minVisibleFrames == 0) {
347 return;
348 }
349 const auto numFrames = markerData.size();
350 size_t f = 0;
351 while (f < numFrames) {
352 if (markerData[f][markerIdx].occluded) {
353 ++f;
354 continue;
355 }
356
357 const size_t visStart = f;
358 while (f < numFrames && !markerData[f][markerIdx].occluded) {
359 ++f;
360 }
361 const size_t visLen = f - visStart;
362
363 // Only suppress if bounded by occluded frames on both sides
364 // (not at sequence start/end).
365 if (visLen < minVisibleFrames && visStart > 0 && f < numFrames) {
366 for (size_t i = visStart; i < f; ++i) {
367 markerData[i][markerIdx].occluded = true;
368 markerData[i][markerIdx].confidence = 0.0f;
369 }
370 }
371 }
372}
373
374} // namespace
375
377 std::vector<std::vector<Marker>>& markerData,
378 const GapFillConfig& config) {
379 if (markerData.empty() || !config.enabled) {
380 return;
381 }
382
383 // Normalize so all frames have the same markers in the same order.
384 // This handles concatenated sequences with different marker sets.
385 normalizeMarkerFrames(markerData);
386
387 const size_t numMarkers = markerData[0].size();
388 if (numMarkers == 0) {
389 return;
390 }
391
392 for (size_t mi = 0; mi < numMarkers; ++mi) {
393 const auto gaps = findGaps(markerData, mi);
394
395 for (const auto& gap : gaps) {
396 const size_t gapLen = gap.endFrame - gap.startFrame;
397 const size_t effectiveMaxGap = computeEffectiveMaxGap(markerData, mi, gap, config);
398
399 if (gap.hasVisibleBefore && gap.hasVisibleAfter && gapLen <= effectiveMaxGap) {
400 // Temporary gap: interpolate with cubic Hermite
401 fillTemporaryGap(markerData, mi, gap, config);
402 } else if (gap.hasVisibleBefore && gap.hasVisibleAfter) {
403 // Long gap with visible frames on both sides: blend off from each side.
404 // This prevents a hard pop when the marker reappears.
405 if (config.blendOffFrames > 0) {
406 blendOffTrailingDropout(markerData, mi, gap, config);
407 blendOffLeadingDropout(markerData, mi, gap, config);
408 }
409 } else if (gap.hasVisibleBefore && config.blendOffFrames > 0) {
410 // Trailing dropout: extrapolate forward and blend off
411 blendOffTrailingDropout(markerData, mi, gap, config);
412 } else if (gap.hasVisibleAfter && config.blendOffFrames > 0) {
413 // Leading dropout: extrapolate backward and blend off
414 blendOffLeadingDropout(markerData, mi, gap, config);
415 }
416 // else: both-sided permanent dropout or disabled — leave as-is
417 }
418
419 // Second pass: suppress short visible segments that remain after
420 // gap filling. These are brief appearances that are unreliable.
421 suppressShortVisibleSegments(markerData, mi, config.minVisibleFrames);
422 }
423}
424
425} // namespace momentum
Vector3< double > Vector3d
Definition types.h:261
constexpr T pi() noexcept
Returns the mathematical constant pi.
Definition constants.h:50
void preprocessMarkerGaps(std::vector< std::vector< Marker > > &markerData, const GapFillConfig &config)
Pre-process marker data to fill temporary gaps and blend off permanent dropouts.
Configuration for marker gap filling and blend-off.
size_t minVisibleFrames
Minimum number of visible frames for a segment to be considered reliable.
size_t blendOffFrames
Number of frames over which to blend off permanently dropped markers.
bool enabled
Master switch.