gs-frames: overlap-aware frame extraction from video for 3DGS/SfM
まだ誰も着手していません。
評価
- 難易度
- 5/5
- 見積もり時間
- 1週間以上
- 初心者へのやさしさ
- 25/100
- issue の種類
- 機能追加
- 明瞭さ
- おおむね明確
- 活発さ
- 活発
- 技術スタック
- python
- 領域
- cli, computer-vision
調査の方向性
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 の本文から書いたものです。
説明
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
- As a 3DGS/COLMAP user, I want to point
gs-framesat a raw video and get back a folder of sharp stills, so that I don't have to manually scrub the footage for keyframes. - 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. - As a user shooting with an iPhone, I want my portrait HEVC
.movclips to decode and export right-side-up automatically, so that I don't have to manually rotate hundreds of output images. - 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.
- As a user iterating on capture settings, I want a fast
--previewmode that writes only the analysis CSV and selection manifest (no images), so that I can tune--overlap/--sharpness/--modewithout paying the cost of re-exporting full-resolution images each time. - 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.
- 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. - 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. - 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. - 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.
- 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. - As a user with a hard cap on dataset size (e.g. Postshot import limits), I want
--max-frames Nto cap the number of selected frames across any mode, so that my dataset stays within tool limits. - As a user choosing an overlap estimation method, I want to pick between
orb(fast feature-match ratio, default) andhomography(geometric IoU of warped frame bounds, more expensive but more accurate), so that I can trade speed for accuracy. - As a user reviewing results, I want
manifest.jsonto 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. - As a user reviewing results, I want
analysis.csvwith 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. - As a user re-running the tool with different flags, I want
analysis.csvandmanifest.jsonto 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. - As a user cropping to a sub-range of a longer recording, I want
--start-seconds/--end-secondsor--start-frame/--end-frame, so that I can exclude setup/teardown footage from analysis and selection. - As a user filtering obviously-bad frames, I want a
--min-sharpnessthreshold (or an automatic percentile-based one), so that motion-blurred frames never become seed frames or window winners. - As a user working with footage whose rotation wasn't detected correctly, I want
--rotate auto|none|90|180|270to override automatic rotation detection, so that I have a manual escape hatch. - 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 inmanifest.json, so that I can confirm the tool actually detected my clip's orientation correctly rather than guessing. - 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
ffmpegsubprocess decoder automatically (ifffmpegis on PATH), so that HEVC.movinput still works without me manually pre-transcoding. - As a user watching a long-running extraction, I want
richprogress 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. - As a user debugging a run, I want a
gs-frames.logfile 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. - As a user choosing output format, I want
--format jpg|pngand--quality Nfor JPEG, so that I can control output size/fidelity per downstream tool's needs. - 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. - As a developer of this tool, I want selection logic (
select_*functions) to take plain in-memory data (score lists, an injectedoverlap_fncallback) rather than OpenCV captures, so that selection behavior is unit-testable without decoding real video. - 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 aspython -m gs_frames. - Package layout:
src/gs_frames/withcli.py,types.py,decode.py,sharpness.py,motion.py,overlap.py,select.py,export.py,plot.py. Tests mirror these modules undertests/, plustests/fixtures/holding a real short iPhone HEVC portrait clip. - Shared types (
types.py):FrameScore,Selection, andExtractConfigdataclasses as specified in the build doc, including all default values,Literaltype 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_METAfirst,ffprobeside-data/rotatetag as fallback,--rotateas manual override,none_detectedwith a warning as last resort; rotation applied viacv2.rotateto 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; ifopencv-python's bundled FFmpeg can't open it, anffmpeg-subprocess pipe-to-NumPy fallback is implemented behind the samedecode.pyinterface, documented in the README. Timestamps read per-frame viaCAP_PROP_POS_MSECby default (VFR-safe); fall back toindex/fpswith a logged warning ifPOS_MSECis zero/non-monotonic;--no-container-timestampsforces 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 takingFrameScorelists,ExtractConfig, and an injectedoverlap_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_framesOR flow-accum ≤3 * flow_trigger, early-stopping after 8 consecutive measured frames belowoverlap_min - 0.15); prefer sharpest in-range candidate, else candidate closest totarget_overlap(tie-break: higher sharpness), else sharpest in pool if all overlap measurements failed.overlap-beam(phase 5, opt-in): beam ofbeam_widthpartial sequences scored by average (not summed) per-step score = normalized sharpness minusoverlap_penalty_lambda * penalty, where penalty is distance outside[overlap_min, overlap_max]plus a small pull towardtarget_overlap;--max-framescaps sequence length across all modes. - Modes:
time(phase 2, default before phase 4 lands) — sharpest frame per--chunk-framesor--every-secondswindow using per-frame timestamps;flow(phase 3) — sharpest frame after accumulated motion crossesflow_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.jsonalways overwrite on rerun; image export requires--forceto overwrite existing files.--previewsuppresses 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.8parsed to fractional min/max, with explicit--overlap-min/--overlap-maxtaking precedence and a warning if both forms are given. - Exit codes:
0success,1user/input error,2processing error. - Dependencies:
opencv-python,numpy,typer,rich,pytestfrom phase 1;pyarrowoptional later for parquet (CSV is the phase-1-through-5 format);matplotlibadded 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 inselect.py, driven by hand-builtFrameScorelists and fakeoverlap_fncallbacks, 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-framesenforcement). sharpness.pyandoverlap.pyare 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.pyis 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.pyis 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,--previewwriting zero images, non-preview image count matching selection count, exit codes, and orientation/dimension spot-checks on exported iPhone-fixture images.test_decode_iphone.pyis the dedicated seam for the three iPhone-specific risks (rotation, HEVC decode, VFR) againsttests/fixtures/iphone_sample_portrait_hevc.mov: assertscap.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 explicitlyskipwith 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 areskipif-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);
pytestis the only test framework, no additional fixtures/mocking libraries beyond what's needed for the fakeoverlap_fncallback 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.mdandCLAUDE.mdunder version control); noCONTEXT.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 を読み、一般的な手順ははじめてのコントリビューションガイドを参照してください。
はじめの一歩
- issue を最後まで読み、次にプロジェクトのコントリビューションガイドを読みます。
- 着手することを issue にコメントします — 二人が同じ作業をするのを防げます。
- リポジトリをフォークし、ブランチを切って変更します。
- issue 番号を参照したプルリクエストを送ります。
bmaltais/gs-frames のほかの issue
-
ready-for-agent
難易度 5/5 1週間以上 初心者へのやさしさ 35/100
-
ready-for-agent
難易度 4/5 3〜5日 初心者へのやさしさ 48/100
-
ready-for-agent
難易度 5/5 1週間以上 初心者へのやさしさ 35/100
bmaltais/gs-frames の issue をすべて見る
似ている issue
-
難易度 2/5 1〜3時間 初心者へのやさしさ 76/100
TigreGotico/orthography2ipa#2950 ·
メンテナーはふだん 1 日以内に返信
-
難易度 2/5 1〜3時間 初心者へのやさしさ 78/100
-
難易度 2/5 1〜3時間 初心者へのやさしさ 78/100
Unstructured-IO/unstructured#4876 ·
メンテナーはふだん 6 日以内に返信
-
難易度 2/5 1〜3時間 初心者へのやさしさ 82/100
openfoodfacts/openfoodfacts-python#579 ·
メンテナーはふだん 1 日以内に返信
-
難易度 2/5 1〜3時間 初心者へのやさしさ 90/100
fairagro/m4.2_sql_to_arc#388 ·
メンテナーはふだん 1 日以内に返信