[G1-Sync] Manual knowledge update
This commit is contained in:
@@ -1,63 +1,200 @@
|
||||
---
|
||||
id: wiki-2026-0508-lucas-kanade-method
|
||||
title: Lucas Kanade Method
|
||||
title: Lucas-Kanade Method
|
||||
category: 10_Wiki/Topics
|
||||
status: needs_review
|
||||
status: verified
|
||||
canonical_id: self
|
||||
aliases: [CV-LUCAS-001]
|
||||
aliases: [LK Optical Flow, Lucas-Kanade Tracker, KLT Tracker]
|
||||
duplicate_of: none
|
||||
source_trust_level: A
|
||||
confidence_score: 1.0
|
||||
tags: ["Computer Vision|[Computer-Vision", optical-flow, lucas-kanade, image-Processing, feature-tracking]
|
||||
confidence_score: 0.95
|
||||
verification_status: applied
|
||||
tags: [computer-vision, optical-flow, tracking, classical-cv]
|
||||
raw_sources: []
|
||||
last_reinforced: 2026-04-26
|
||||
last_reinforced: 2026-05-10
|
||||
github_commit: pending
|
||||
inferred_by: Claude Opus 4.7 (auto-normalize 2026-05-08)
|
||||
tech_stack:
|
||||
language: python
|
||||
framework: opencv
|
||||
---
|
||||
|
||||
# Lucas-Kanade Method (루카스-카나데 방법)
|
||||
# Lucas-Kanade Method
|
||||
|
||||
## 📌 한 줄 통찰 (The Karpathy Summary)
|
||||
> "주변 픽셀들은 함께 움직인다는 가정하에, 찰나의 변화 속에서 물체의 흐름(Flow)을 포착하라" — 인접한 픽셀들이 유사한 움직임을 가진다는 국소적 일관성(Local Coherence)을 가정한 후, 최소제곱법을 통해 두 프레임 사이의 픽셀 이동량을 추정하는 옵티컬 플로우(Optical Flow) 알고리즘.
|
||||
## 매 한 줄
|
||||
> **"매 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.
|
||||
|
||||
## 📖 구조화된 지식 (Synthesized Content)
|
||||
- **추출된 패턴:** "Spatial Consistency and Gradient Descent" — 영상의 밝기가 일정하게 유지된다고 가정(Brightness Constancy)하고, 이미지의 기울기(Gradient) 정보를 활용하여 오차를 최소화하는 방향으로 물체의 이동 궤적을 추적하는 패턴.
|
||||
- **핵심 가정:**
|
||||
- **Brightness Constancy:** 물체의 밝기는 움직여도 변하지 않음.
|
||||
- **Temporal Persistence:** 프레임 간 이동량이 매우 작음.
|
||||
- **Spatial Coherence:** 특정 픽셀의 이웃들은 같은 방향으로 이동함.
|
||||
- **의의:** 영상 내 특징점 추적, 비디오 안정화, 자율주행차의 장애물 감지 등 실시간 컴퓨터 비전 시스템의 움직임 분석을 위한 가장 기초적이고 효율적인 도구.
|
||||
## 매 핵심
|
||||
|
||||
## ⚠️ 모순 및 업데이트 (Contradictions & Updates)
|
||||
- **과거 데이터와의 충돌:** 이동량이 큰 경우에는 오차가 심하다는 한계가 있으나, 피라미드 구조(Image Pyramid)를 통해 이미지를 축소하며 단계적으로 추적하는 방식으로 현대적 한계를 극복함.
|
||||
- **정책 변화:** Skybound 프로젝트의 적 기체 추적 및 VFX 효과 구현 시, 프레임 간의 자연스러운 움직임 보간을 위해 루카스-카나데 기반의 옵티컬 플로우 원리를 활용함.
|
||||
### 매 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.
|
||||
|
||||
## 🔗 지식 연결 (Graph)
|
||||
- [[Least-Squares-Methods|Least-Squares-Methods]], [[Pattern-Recognition|Pattern-Recognition]]-Foundations, Kalman-Filter-and-State-Tracking, [[Robotics-Foundations|Robotics-Foundations]]
|
||||
- **Raw Source:** 10_Wiki/Topics/AI/Lucas-Kanade-Method.md
|
||||
### 매 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).
|
||||
|
||||
## 🤖 LLM 활용 힌트 (How to Use This Knowledge)
|
||||
### 매 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.
|
||||
|
||||
**언제 이 지식을 쓰는가:**
|
||||
- *(TODO)*
|
||||
### 매 응용
|
||||
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.
|
||||
|
||||
**언제 쓰면 안 되는가:**
|
||||
- *(TODO)*
|
||||
## 💻 패턴
|
||||
|
||||
## 🧪 검증 상태 (Validation)
|
||||
### Pattern 1: OpenCV calcOpticalFlowPyrLK
|
||||
```python
|
||||
import cv2
|
||||
import numpy as np
|
||||
|
||||
- **정보 상태:** needs_review
|
||||
- **출처 신뢰도:** A
|
||||
- **검토 이유:** *(P-Reinforce Phase 1 자동 정규화. 본문 검증 필요.)*
|
||||
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)
|
||||
|
||||
## 🧬 중복 검사 (Duplicate Check)
|
||||
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)
|
||||
```
|
||||
|
||||
- **기존 유사 문서:** *(TODO: 인덱서 클러스터 리포트 참조)*
|
||||
- **처리 방식:** UPDATE (자동 정규화)
|
||||
- **처리 이유:** Phase 1 정규화 — 옛 템플릿/누락 필드 보강.
|
||||
### Pattern 2: Vanilla LK (educational)
|
||||
```python
|
||||
import numpy as np
|
||||
|
||||
## 🕓 변경 이력 (Changelog)
|
||||
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
|
||||
```
|
||||
|
||||
| 날짜 | 변경 내용 | 처리 방식 | 신뢰도 |
|
||||
|------|-----------|-----------|--------|
|
||||
| 2026-05-08 | P-Reinforce Phase 1 정규화 (frontmatter + 헤더 표준화) | UPDATE | A |
|
||||
### Pattern 3: Pyramid LK (large motion)
|
||||
```python
|
||||
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
|
||||
```python
|
||||
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
|
||||
```python
|
||||
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)
|
||||
```python
|
||||
# 매 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
|
||||
- 부모: [[Optical-Flow]] · [[Computer-Vision]]
|
||||
- 변형: [[Pyramid-LK]] · [[Affine-LK]] · [[Inverse-Compositional-LK]]
|
||||
- 응용: [[KLT-Tracker]] · [[Visual-SLAM]] · [[Video-Stabilization]]
|
||||
- Adjacent: [[Horn-Schunck]] · [[RAFT]] · [[GMA]] · [[Good-Features-To-Track]]
|
||||
|
||||
## 🤖 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 |
|
||||
|
||||
Reference in New Issue
Block a user