Files
2nd/10_Wiki/Topics/Other/Lucas-Kanade-Method.md
T
Antigravity Agent f8b21af4be Wiki cleanup: error-doc removal, dedup merge, link normalization
10_Wiki/Topics 대규모 정리:
- 오류 캡처/미완성 stub 문서 227개 제거
- 교차폴더 중복 43클러스터 병합 (63파일 → redirect)
- 링크명 정규화: 깨진 링크 수정·redirect 직결·개념 매핑 ~2,400건
- 카테고리 MOC 6개 신규 생성
- Graph 섹션 미해결 related-keyword 링크 10,058건 제거

Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
2026-05-20 23:52:15 +09:00

200 lines
7.0 KiB
Markdown

---
id: wiki-2026-0508-lucas-kanade-method
title: Lucas-Kanade Method
category: 10_Wiki/Topics
status: verified
canonical_id: self
aliases: [LK Optical Flow, Lucas-Kanade Tracker, KLT Tracker]
duplicate_of: none
source_trust_level: A
confidence_score: 0.95
verification_status: applied
tags: [computer-vision, optical-flow, tracking, classical-cv]
raw_sources: []
last_reinforced: 2026-05-10
github_commit: pending
tech_stack:
language: python
framework: 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
```python
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)
```python
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)
```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
- 부모: [[Computer Vision|Computer-Vision]]
- 응용: [[KLT-Tracker]]
- Adjacent: [[RAFT]]
## 🤖 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 |