Files
2nd/10_Wiki/Topics/Domain_General/From_Other/Lucas-Kanade-Method.md
T
Antigravity Agent c24165b8bc refactor(topics): 멀티 에이전트용 지식 재편 — _Common(공통 기본기) + Domain_* 구조
에이전트 8종(대화형/프로그래머 C·S/디자이너/설계자/기획자/QA/PD/PM)에게
[공통 기본 능력 + 롤별 Specialty] 2층으로 지식을 주입하기 위한 재분류.
문서 내용·포맷은 무수정, 폴더 이동만 (6,372개 문서 수 보존 확인).

- Topic_Programming → Domain_Programming (내부 구조 보존)
- Topic_Graphic → Domain_Design
- Topic_Business → Domain_Product
- Topic_General → Domain_General
- _Common 신설: Math(구 Topic_Math_Specialty), Reasoning(구 General/From_Thinking & Reasoning),
  Reasoning_Creativity(구 General/From_창의성), Communication(Poetic_Blog_Writing + From_writing)
- 타 도메인의 From_* 폴더는 유지 (출처 표기일 뿐, 이미 도메인에 맞게 분류된 문서)
- 빈 폴더 정리 (memory/procedures)
- 에이전트→폴더 매핑은 workspace의 .astra/agent-knowledge-map.json (9개 에이전트)

Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>
2026-07-11 11:05:56 +09:00

7.0 KiB

id, title, category, status, canonical_id, aliases, duplicate_of, source_trust_level, confidence_score, verification_status, tags, raw_sources, last_reinforced, github_commit, tech_stack
id title category status canonical_id aliases duplicate_of source_trust_level confidence_score verification_status tags raw_sources last_reinforced github_commit tech_stack
wiki-2026-0508-lucas-kanade-method Lucas-Kanade Method 10_Wiki/Topics verified self
LK Optical Flow
Lucas-Kanade Tracker
KLT Tracker
none A 0.95 applied
computer-vision
optical-flow
tracking
classical-cv
2026-05-10 pending
language framework
python opencv

Lucas-Kanade Method

매 한 줄

"매 small window, 매 brightness constancy, 매 linear least squares 의 motion vector". Lucas-Kanade (LK, 1981) 매 sparse optical flow estimation 매 classical method — 매 each tracked point 의 local 2D velocity 의 linear system 의 solve. 2026 매 deep methods (RAFT, GMA) 매 dominate dense flow, LK 매 still the go-to 매 sparse tracking + low-compute embedded systems.

매 핵심

매 Assumptions

  1. Brightness constancy: I(x, y, t) ≈ I(x+dx, y+dy, t+dt).
  2. Small motion: Taylor expand 매 first-order valid.
  3. Spatial coherence: small window 매 same motion 의 share.

매 The equation

  • 매 I_x · u + I_y · v + I_t = 0 (optical flow constraint, per pixel).
  • 매 underdetermined (2 unknowns, 1 equation) → window aggregation.
  • 매 N pixels in window → over-determined linear system A·d = b.
  • 매 d = (Aᵀ A)⁻¹ Aᵀ b (least squares).

매 Failure modes

  • Aperture problem: window 매 1D structure (edge) → A^T A singular.
  • Large motion: Taylor first-order 매 break — 매 pyramid LK 의 fix.
  • Illumination change: brightness constancy 매 violate.
  • Occlusion: tracked point 매 disappear — 매 forward-backward check.

매 응용

  1. Sparse feature tracking (KLT in SLAM).
  2. Video stabilization (camera motion estimation).
  3. Embedded vision (drone OF sensor).
  4. Initial track for deep refinement.

💻 패턴

Pattern 1: OpenCV calcOpticalFlowPyrLK

import cv2
import numpy as np

cap = cv2.VideoCapture("video.mp4")
ret, prev = cap.read()
prev_gray = cv2.cvtColor(prev, cv2.COLOR_BGR2GRAY)
p0 = cv2.goodFeaturesToTrack(prev_gray, maxCorners=200, qualityLevel=0.01, minDistance=10)

while True:
    ret, frame = cap.read()
    if not ret:
        break
    gray = cv2.cvtColor(frame, cv2.COLOR_BGR2GRAY)
    p1, status, err = cv2.calcOpticalFlowPyrLK(
        prev_gray, gray, p0, None,
        winSize=(21, 21), maxLevel=3,
        criteria=(cv2.TERM_CRITERIA_EPS | cv2.TERM_CRITERIA_COUNT, 30, 0.01),
    )
    good = p1[status.flatten() == 1]
    prev_gray = gray
    p0 = good.reshape(-1, 1, 2)

Pattern 2: Vanilla LK (educational)

import numpy as np

def lucas_kanade(I1, I2, points, window=15):
    """매 each point 의 (u, v) flow vector 의 return."""
    half = window // 2
    Ix = np.gradient(I1, axis=1)
    Iy = np.gradient(I1, axis=0)
    It = I2.astype(float) - I1.astype(float)
    flow = np.zeros((len(points), 2))
    for i, (x, y) in enumerate(points):
        x, y = int(x), int(y)
        Ix_w = Ix[y-half:y+half+1, x-half:x+half+1].flatten()
        Iy_w = Iy[y-half:y+half+1, x-half:x+half+1].flatten()
        It_w = It[y-half:y+half+1, x-half:x+half+1].flatten()
        A = np.stack([Ix_w, Iy_w], axis=1)
        b = -It_w
        if np.linalg.matrix_rank(A.T @ A) < 2:
            continue  # aperture problem
        d, *_ = np.linalg.lstsq(A, b, rcond=None)
        flow[i] = d
    return flow

Pattern 3: Pyramid LK (large motion)

def pyramid_lk(I1, I2, points, levels=4, window=15):
    """매 coarse-to-fine — 매 large motion 의 handle."""
    pyr1 = [I1]
    pyr2 = [I2]
    for _ in range(levels - 1):
        pyr1.append(cv2.pyrDown(pyr1[-1]))
        pyr2.append(cv2.pyrDown(pyr2[-1]))
    flow = np.zeros((len(points), 2))
    pts = points / (2 ** (levels - 1))
    for level in reversed(range(levels)):
        d = lucas_kanade(pyr1[level], pyr2[level], pts, window)
        flow = flow * 2 + d
        if level > 0:
            pts = pts * 2 + d
    return flow

Pattern 4: Forward-backward consistency

def fb_consistency(I1, I2, points, threshold=1.0):
    """매 forward 의 track 매 backward 의 verify — 매 lost point 의 reject."""
    p1 = points
    p2, st_fwd, _ = cv2.calcOpticalFlowPyrLK(I1, I2, p1, None)
    p1_back, st_bwd, _ = cv2.calcOpticalFlowPyrLK(I2, I1, p2, None)
    err = np.linalg.norm(p1 - p1_back, axis=2).flatten()
    valid = (st_fwd.flatten() == 1) & (st_bwd.flatten() == 1) & (err < threshold)
    return p2[valid]

Pattern 5: KLT corner re-seeding

def klt_track_with_reseed(cap, max_corners=200, min_count=50):
    ret, prev = cap.read()
    prev_gray = cv2.cvtColor(prev, cv2.COLOR_BGR2GRAY)
    p0 = cv2.goodFeaturesToTrack(prev_gray, max_corners, 0.01, 10)
    while True:
        ret, frame = cap.read()
        if not ret:
            break
        gray = cv2.cvtColor(frame, cv2.COLOR_BGR2GRAY)
        p1, st, _ = cv2.calcOpticalFlowPyrLK(prev_gray, gray, p0, None)
        good = p1[st.flatten() == 1]
        if len(good) < min_count:
            new_pts = cv2.goodFeaturesToTrack(gray, max_corners, 0.01, 10)
            good = np.concatenate([good, new_pts.reshape(-1, 2)])
        p0 = good.reshape(-1, 1, 2).astype(np.float32)
        prev_gray = gray
        yield good

Pattern 6: LK 의 deep flow init (2026 hybrid)

# 매 deep model (RAFT) 매 dense flow 의 give — 매 LK 의 sub-pixel refine.
def hybrid_flow(I1, I2, raft_model, points):
    dense_flow = raft_model(I1, I2)  # H x W x 2
    coarse = dense_flow[points[:, 1].astype(int), points[:, 0].astype(int)]
    refined = lucas_kanade(I1, I2, points + coarse, window=7)
    return coarse + refined

매 결정 기준

상황 Approach
Sparse feature tracking KLT (LK + good features).
Large motion Pyramid LK.
Dense flow + GPU RAFT / GMA (deep).
Embedded / ms latency LK 의 stick.
Robust tracking LK + forward-backward + RANSAC.

기본값: cv2.calcOpticalFlowPyrLK with window=21, maxLevel=3, FB consistency check, periodic re-seed.

🔗 Graph

🤖 LLM 활용

언제: Code generation for embedded vision, classical CV pipelines, baseline implementation before deep methods. 언제 X: Production dense flow at scale (use RAFT/GMA), occlusion-heavy scenes (use Cotracker).

안티패턴

  • No pyramid for large motion: 매 LK 매 only handle ~1 pixel motion at single scale.
  • Track forever without re-seed: 매 features 매 disappear → tracking dies.
  • Ignore aperture problem: 매 edge-only window → spurious flow.
  • No FB check: 매 lost points 매 silently track 매 noise.

🧪 검증 / 중복

  • Verified: Lucas & Kanade (1981) "An iterative image registration technique", Bouguet (2000) pyramid LK, OpenCV docs.
  • 신뢰도 A.

🕓 Changelog

날짜 변경
2026-05-08 Phase 1
2026-05-10 Manual cleanup — full content with vanilla LK, pyramid LK, FB consistency, deep hybrid 2026