gs-frames: overlap-aware frame extraction from video for 3DGS/SfM

オープン
#7 コメント 0 件 リアクション 0 件 担当者 0 名 GitHub で見る

まだ誰も着手していません。

評価

難易度
5/5
見積もり時間
1週間以上
初心者へのやさしさ
25/100
issue の種類
機能追加
明瞭さ
おおむね明確
活発さ
活発
技術スタック
python

調査の方向性

Start with the package layout under src/gs_frames/, especially types.py, decode.py, and select.py, then review the mirrored tests and the real iPhone fixture under tests/. Run the planned CLI and test suite to understand the phase boundaries. Done means the documented extraction modes, orientation and HEVC handling, manifests, analysis CSV, exports, progress reporting, and regression coverage are implemented.

索引モデルが issue の本文から書いたものです。

説明

ready-for-agent

Problem Statement

3D Gaussian Splatting / SfM pipelines (COLMAP, gsplat, Postshot) need a folder of sharp still images with consistent neighbor-to-neighbor overlap as input. Pulling those stills from a handheld video today is manual: scrubbing for non-blurry frames, guessing spacing so consecutive shots aren't near-duplicates (too much overlap) or missing coverage (too little overlap), and re-orienting/re-exporting anything the phone stored sideways. For the primary source material — iPhone-recorded HEVC .mov clips, usually portrait, usually variable frame rate — naive frame dumping tools (ffmpeg -r N) silently produce sideways frames, timestamp-misaligned sampling, and no sharpness or overlap awareness at all.

Solution

A CLI, gs-frames, that decodes a video once, scores every analyzed frame for sharpness, estimates image-plane overlap between candidate neighbors, and greedily (or via beam search) selects a sequence of frames whose overlap stays inside a user-specified target range (e.g. 70–80%), preferring the sharpest candidate at each step. Only winning frames are written at full resolution; a CSV of all analyzed frames and a JSON manifest of the selection are always written. iPhone-specific decode concerns (container rotation metadata, HEVC codec support, variable frame rate) are handled as a first-class, non-optional part of the decode layer, verified against a real iPhone fixture, not assumed to work because a synthetic test video passes.

User Stories

  1. As a 3DGS/COLMAP user, I want to point gs-frames at a raw video and get back a folder of sharp stills, so that I don't have to manually scrub the footage for keyframes.
  2. As a 3DGS/COLMAP user, I want consecutive selected frames to overlap within a range I choose (e.g. --overlap 70-80), so that my SfM solve has enough covisibility to register frames without wasting frames on near-duplicates.
  3. As a user shooting with an iPhone, I want my portrait HEVC .mov clips to decode and export right-side-up automatically, so that I don't have to manually rotate hundreds of output images.
  4. As a user shooting in low light, I want frame timing to reflect the video's actual (variable) frame rate rather than an assumed constant rate, so that time-windowed sampling and motion-triggered sampling aren't skewed by VFR artifacts.
  5. As a user iterating on capture settings, I want a fast --preview mode that writes only the analysis CSV and selection manifest (no images), so that I can tune --overlap/--sharpness/--mode without paying the cost of re-exporting full-resolution images each time.
  6. As a user with a very long clip, I want analysis to run on downscaled grayscale frames, so that scoring thousands of frames doesn't require decoding and processing at full 4K resolution.
  7. As a user who wants the simplest possible selection, I want a time-windowed mode (--mode time) that just picks the sharpest frame every N seconds or N frames, so that I have quick, predictable output before tuning anything overlap-related.
  8. As a user filming a scene with uneven camera motion (pauses, fast pans), I want a motion-adaptive mode (--mode flow) that samples more frequently during motion and less during stillness, so that static segments don't produce redundant near-identical frames.
  9. As a user who wants true overlap-constrained selection, I want --mode overlap-greedy (the default product mode) to pick, at each step, the sharpest candidate whose estimated overlap with the last-kept frame falls in [overlap_min, overlap_max], so that my dataset has consistent, tunable covisibility.
  10. As a user whose scene has no candidate in-range at some point (e.g. a big camera jump), I want the selector to fall back to the candidate closest to the target overlap rather than skip that segment silently, so that coverage doesn't have unexplained gaps.
  11. As a user who suspects greedy selection locked onto a bad early choice, I want an opt-in beam-search mode (--mode overlap-beam) that explores multiple candidate sequences, so that I can get a better global selection when greedy performs poorly.
  12. As a user with a hard cap on dataset size (e.g. Postshot import limits), I want --max-frames N to cap the number of selected frames across any mode, so that my dataset stays within tool limits.
  13. As a user choosing an overlap estimation method, I want to pick between orb (fast feature-match ratio, default) and homography (geometric IoU of warped frame bounds, more expensive but more accurate), so that I can trade speed for accuracy.
  14. As a user reviewing results, I want manifest.json to record, per selected frame, its sharpness score, overlap with the previous frame, the overlap metric used, and the reason it was picked (seed, in-range, fallback-closest, time-window, flow-window, max-frames), so that I can audit why any given frame was or wasn't selected.
  15. As a user reviewing results, I want analysis.csv with one row per analyzed frame (sharpness components, flow, selected flag), so that I can plot or post-process the full population of candidate frames, not just the winners.
  16. As a user re-running the tool with different flags, I want analysis.csv and manifest.json to be overwritten on rerun, but exported images to be protected from accidental overwrite unless I pass --force, so that I don't silently lose a prior full-resolution export.
  17. As a user cropping to a sub-range of a longer recording, I want --start-seconds/--end-seconds or --start-frame/--end-frame, so that I can exclude setup/teardown footage from analysis and selection.
  18. As a user filtering obviously-bad frames, I want a --min-sharpness threshold (or an automatic percentile-based one), so that motion-blurred frames never become seed frames or window winners.
  19. As a user working with footage whose rotation wasn't detected correctly, I want --rotate auto|none|90|180|270 to override automatic rotation detection, so that I have a manual escape hatch.
  20. As a user auditing orientation handling, I want the applied rotation and its source (container_meta, ffprobe, user_override, none_detected) logged at startup and recorded in manifest.json, so that I can confirm the tool actually detected my clip's orientation correctly rather than guessing.
  21. As a user on a machine where OpenCV's bundled FFmpeg can't decode HEVC, I want the tool to fall back to a system ffmpeg subprocess decoder automatically (if ffmpeg is on PATH), so that HEVC .mov input still works without me manually pre-transcoding.
  22. As a user watching a long-running extraction, I want rich progress bars for analyze/select/export phases and a final summary (frames analyzed, frames selected, in-range count, fallback count, output path), so that I have visibility into progress and outcome without reading logs.
  23. As a user debugging a run, I want a gs-frames.log file in the output directory plus INFO-level logging of fps/size/frame count, detected rotation, resolved overlap range, and seed index, so that unexpected selections are diagnosable after the fact.
  24. As a user choosing output format, I want --format jpg|png and --quality N for JPEG, so that I can control output size/fidelity per downstream tool's needs.
  25. As a user reviewing a completed extraction, I want plots (sharpness.png, overlap.png, timeline.png) and a terminal overlap histogram (in-range/too-high/too-low/failed), so that I can visually sanity-check the selection without opening every image.
  26. As a developer of this tool, I want selection logic (select_* functions) to take plain in-memory data (score lists, an injected overlap_fn callback) rather than OpenCV captures, so that selection behavior is unit-testable without decoding real video.
  27. As a developer of this tool, I want the iPhone-specific decode risks (rotation, HEVC support, VFR timestamps) covered by a real iPhone test fixture, not only synthetic CFR/unrotated video, so that a decode regression on the primary target input is caught in CI rather than by a user.

Implementation Decisions

  • Language/CLI: Python 3.11+, Typer-based CLI (gs-frames extract VIDEO OUTPUT_DIR [flags], gs-frames version), also invocable as python -m gs_frames.
  • Package layout: src/gs_frames/ with cli.py, types.py, decode.py, sharpness.py, motion.py, overlap.py, select.py, export.py, plot.py. Tests mirror these modules under tests/, plus tests/fixtures/ holding a real short iPhone HEVC portrait clip.
  • Shared types (types.py): FrameScore, Selection, and ExtractConfig dataclasses as specified in the build doc, including all default values, Literal type aliases (SharpnessMethod, OverlapMetric, SelectMode, ImageFormat, RotationMode), and validation rules (overlap bounds, analysis scale range, JPEG quality range, start<end, video path exists).
  • Decode boundary (decode.py) is the single seam separating all OpenCV/video I/O from the rest of the system: it yields (index, timestamp_s, bgr_frame) for analysis, already resized and rotated, and streams rather than buffering all full-res frames. Winner export re-opens the video and seeks per selected index, falling back to sequential read if seeks land inaccurately.
  • iPhone handling (non-optional, blocks phase 1 completion): rotation detected via CAP_PROP_ORIENTATION_META first, ffprobe side-data/rotate tag as fallback, --rotate as manual override, none_detected with a warning as last resort; rotation applied via cv2.rotate to every decoded frame (analysis and full-res) before any scoring; effective width/height updated post-rotation. HEVC decode reliability verified against a real fixture before phase 1 is done; if opencv-python's bundled FFmpeg can't open it, an ffmpeg-subprocess pipe-to-NumPy fallback is implemented behind the same decode.py interface, documented in the README. Timestamps read per-frame via CAP_PROP_POS_MSEC by default (VFR-safe); fall back to index/fps with a logged warning if POS_MSEC is zero/non-monotonic; --no-container-timestamps forces the fallback for debugging.
  • Sharpness (sharpness.py): Tenengrad (mean of Sobel gradient squared magnitude) and Laplacian variance, combined via per-video z-score blend (0.6 * z_tenengrad + 0.4 * z_laplacian); optional (default-on) center-weighting via a 2D Hann window before scoring.
  • Motion (motion.py, phase 3): DIS optical flow (DISOPTICAL_FLOW_PRESET_FAST) between consecutive analysis-resolution grayscale frames, cell-based magnitude with median aggregation (flow_median); frame-index/flow-driven (not timestamp-driven) accumulation, so VFR does not affect this mode's correctness.
  • Overlap metrics (overlap.py, phase 4): orb (default; ORB features + BFMatcher/Hamming + Lowe ratio; overlap = good matches / min(nA, nB)), homography (same matches, RANSAC homography with a fixed A/B direction convention — H maps candidate frame B into last-kept frame A's coordinate space; overlap = IoU of B's warped corners vs A's rectangle; falls back to ORB ratio on homography failure), flow (fallback-only proxy from accumulated flow, never default), none (skip geometric overlap; behaves like phase 2/3 modes). ORB descriptors cached per candidate for the duration of one selection pass.
  • Selection (select.py): pure functions taking FrameScore lists, ExtractConfig, and an injected overlap_fn(i, j) -> Optional[float] callback — no OpenCV objects in signatures. overlap-greedy (phase 4 default mode): seed = first frame at/above sharpness threshold; from the last-kept frame, build a bounded candidate pool (index distance ≤ search_expand_frames OR flow-accum ≤ 3 * flow_trigger, early-stopping after 8 consecutive measured frames below overlap_min - 0.15); prefer sharpest in-range candidate, else candidate closest to target_overlap (tie-break: higher sharpness), else sharpest in pool if all overlap measurements failed. overlap-beam (phase 5, opt-in): beam of beam_width partial sequences scored by average (not summed) per-step score = normalized sharpness minus overlap_penalty_lambda * penalty, where penalty is distance outside [overlap_min, overlap_max] plus a small pull toward target_overlap; --max-frames caps sequence length across all modes.
  • Modes: time (phase 2, default before phase 4 lands) — sharpest frame per --chunk-frames or --every-seconds window using per-frame timestamps; flow (phase 3) — sharpest frame after accumulated motion crosses flow_trigger; overlap-greedy (phase 4, eventual default); overlap-beam (phase 5, opt-in).
  • Output artifacts: analysis.csv (all analyzed frames), manifest.json (video metadata including applied rotation/source, resolved config, stats, per-selected-frame records), images/frame_XXXXXX.jpg|png (winners only, original frame index zero-padded to 6), selection.csv. analysis.csv/manifest.json always overwrite on rerun; image export requires --force to overwrite existing files. --preview suppresses image export only, in every phase from phase 1 onward.
  • CLI flags: exact flag set and defaults as enumerated in the build doc's flag table (kept stable from phase 1 so later phases don't change earlier call sites); --overlap 70-80/0.7-0.8 parsed to fractional min/max, with explicit --overlap-min/--overlap-max taking precedence and a warning if both forms are given.
  • Exit codes: 0 success, 1 user/input error, 2 processing error.
  • Dependencies: opencv-python, numpy, typer, rich, pytest from phase 1; pyarrow optional later for parquet (CSV is the phase-1-through-5 format); matplotlib added in phase 6 for plots. No torch, LightGlue, or COLMAP wrapper in v1.
  • Build order: six phases, each version-bumped (0.1.0→0.6.0) and each left in a runnable, tested state before the next starts, per the phase breakdown in the build doc (sharpness+CSV → time-window export → optical-flow windows → ORB/homography overlap-greedy → beam search → manifest polish/plots). Phase order is not to be reshuffled or compressed.

Testing Decisions

  • Tests exercise external behavior at two seams: (1) decode.py's output (frames/timestamps/rotation as observed by callers), never internal OpenCV call sequences; (2) select_* functions in select.py, driven by hand-built FrameScore lists and fake overlap_fn callbacks, with zero real video I/O — this is the primary unit-test seam and should carry the bulk of selection-logic coverage (greedy in-range vs fallback-closest choice, beam search beating greedy on a constructed trap case, --max-frames enforcement).
  • sharpness.py and overlap.py are tested as pure functions on synthetic/in-memory images (sharp vs. Gaussian-blurred checkerboard; identical/shifted/noise image pairs for overlap; an asymmetric-shift case specifically to catch a reversed homography A/B direction) — generous bounds, not exact-equality assertions, since ORB matching has run-to-run variance.
  • motion.py is tested against a synthetic pan (increasing translation) and a static (identical-frame) sequence, asserting flow-mode selects more frames during motion and only the seed when static.
  • test_cli.py is the one integration seam exercising the full pipeline end-to-end against generated synthetic video fixtures (checkerboard frames, sharp/blurred halves) plus the real iPhone fixture, covering: CSV row counts, --preview writing zero images, non-preview image count matching selection count, exit codes, and orientation/dimension spot-checks on exported iPhone-fixture images.
  • test_decode_iphone.py is the dedicated seam for the three iPhone-specific risks (rotation, HEVC decode, VFR) against tests/fixtures/iphone_sample_portrait_hevc.mov: asserts cap.isOpened(), a minimum frame count, portrait dimensions (width < height) as proof rotation was actually applied, and non-decreasing/non-uniform timestamps (or a documented note if the fixture happens to be CFR, making this a smoke test rather than a VFR-specific assertion). If no real fixture can be committed, the test must explicitly skip with a stated reason rather than pass on synthetic CFR/unrotated/H.264 video alone, since that substitutes zero real coverage.
  • Synthetic video fixtures are generated in-test via OpenCV VideoWriter (30 frames, 320×240, half sharp/half Gaussian-blurred, 10 fps); tests that depend on writer codec availability are skipif-guarded per platform, with selection logic still tested against in-memory frame lists when video I/O is unavailable.
  • No prior test suite exists in this repo (greenfield); pytest is the only test framework, no additional fixtures/mocking libraries beyond what's needed for the fake overlap_fn callback pattern.

Out of Scope

  • Running COLMAP, gsplat, Postshot, or any 3DGS/NeRF trainer.
  • Undistortion, person masking, or 360/equirectangular footage conversion.
  • A GUI.
  • Requiring a GPU.
  • Claiming the overlap metric represents true 3D covisibility — it is explicitly a 2D proxy used before poses exist.
  • De-flickering or auto-exposure/white-balance correction (iPhone auto-exposure hunting); documented as a known limitation instead.
  • Any feature beyond the six phases (no plugin system, no additional overlap metrics, no additional selection modes) until all six phases pass their defined acceptance criteria.

Further Notes

  • Section 8a of the source build document (iPhone rotation/HEVC/VFR handling) is treated as a hard gate on phase 1, not deferrable polish — a decode or orientation bug there silently corrupts every later phase's output, so it must be resolved (including the FFmpeg-subprocess fallback decision, if needed) before sharpness/selection code is written.
  • The repo is currently empty (only README.md and CLAUDE.md under version control); no CONTEXT.md/ADRs exist yet, so this spec does not reference or contradict any existing domain documentation.
  • Reference implementations/papers for behavioral parity (not for vendoring, except small MIT-licensed snippets with attribution): cansik/sharp-frame-extractor, Kotohibi/Extract_sharpest_frame, Reflct/sharp-frames-python (sharpness/time-window prior art); morishuz/adaptive-frame-extractor, morishuz/frame-extractor, AliceVision Meshroom keyframeSelection (motion-window prior art); Asif Sijan, Robust 3D content generation with acquisition aware frame selection for Gaussian Splatting (UMN, 2025) as the primary algorithm reference for the overlap-guided greedy/fallback selection logic.
主要言語
Python
スター
0
フォーク
0
PR マージ指標
30日以内にマージされた PR はありません

環境構築

このプロジェクトには開発コンテナ、Dockerfile、コントリビューションガイドがありません。まず README を読み、一般的な手順ははじめてのコントリビューションガイドを参照してください。

はじめの一歩

  1. issue を最後まで読み、次にプロジェクトのコントリビューションガイドを読みます。
  2. 着手することを issue にコメントします — 二人が同じ作業をするのを防げます。
  3. リポジトリをフォークし、ブランチを切って変更します。
  4. issue 番号を参照したプルリクエストを送ります。

bmaltais/gs-frames のほかの issue

bmaltais/gs-frames の issue をすべて見る

似ている issue

Python の issue をもっと見る

新しい issue をメールで受け取る

初心者向けの GitHub issue を短くまとめたダイジェスト。