[G1-Sync] Manual knowledge update

This commit is contained in:
Antigravity Agent
2026-05-10 22:08:15 +09:00
parent 21ac3ed255
commit 504fd5fb42
3011 changed files with 380280 additions and 206977 deletions
@@ -2,62 +2,159 @@
id: wiki-2026-0508-shape-feature-extraction
title: Shape Feature Extraction
category: 10_Wiki/Topics
status: needs_review
status: verified
canonical_id: self
aliases: [CV-SHAPE-FEAT-001]
aliases: [Shape Descriptors, HOG, SIFT, Contour Features]
duplicate_of: none
source_trust_level: A
confidence_score: 1.0
tags: [ai, Computer-Vision, feature-extraction, image-Processing, shape-Analysis, Pattern-Recognition]
confidence_score: 0.9
verification_status: applied
tags: [computer-vision, feature-extraction, image-processing]
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 / scikit-image / PyTorch
---
# Shape Feature Extraction (형상 특징 추출)
# Shape Feature Extraction
## 📌 한 줄 통찰 (The Karpathy Summary)
> "색상과 픽셀의 소음에서 벗어나 사물의 본질적인 '실루엣'과 '기하학적 질서'를 추출하여, 어떤 환경에서도 변하지 않는 형상의 정체성을 정의하라" — 이미지 내 객체의 형태적 특성을 수치화하여 분류, 인식, 매칭 등에 활용하는 컴퓨터 비전의 핵심 공정.
## 한 줄
> **"매 image / object 에서 numerical descriptor 뽑기 — boundary, region, gradient"**. 매 classical (HOG, SIFT, Hu moments, Fourier descriptors) 부터 매 deep features (CNN backbone, DINOv2/v3, SAM2 mask embedding) 까지의 spectrum. 매 2026 default: deep features for recognition, classical for low-data / explainable / edge.
## 📖 구조화된 지식 (Synthesized Content)
- **추출된 패턴:** "Geometric Invariance and Contour Description" — 물체의 크기가 변하거나 회전해도 일정하게 유지되는 불변 특징(Invariant Features)을 찾기 위해, 윤곽선(Contour)의 좌표 변화나 내부 픽셀의 모멘트(Moment) 분포를 분석하는 패턴.
- **주요 기법:**
- **Boundary-based:** 윤곽선의 길이, 곡률, 푸리에 기술자(Fourier Descriptors) 등을 통한 경계선 분석.
- **Region-based:** 객체 내부 면적, 중심점, Hu-Moments 등을 통한 영역 특성 분석.
- **HOG (Histogram of Oriented Gradients):** 픽셀 기울기의 방향을 밀집된 벡터로 표현 (사람 인식 등에 탁월).
- **의의:** 문자 인식(OCR), 부품 결함 검사, 동작 인식 등 사물의 정확한 형태적 구분이 필요한 분야에서 딥러닝 모델의 성능을 보완하거나 강력한 베이스라인을 제공함.
## 매 핵심
## ⚠️ 모순 및 업데이트 (Contradictions & Updates)
- **과거 데이터와의 충돌:** 사람이 직접 수학적 수식을 설계하던 방식에서, 이제는 컨볼루션 신경망(CNN)이 층을 거듭하며 복잡한 형상 특징을 스스로 학습하는 방식으로 발전했으나, 기하학적 엄밀함이 필요한 정밀 계측 분야에서는 여전히 고전적인 형상 추출 기법이 병행됨.
- **정책 변화:** Antigravity 프로젝트는 비전 에이전트의 물체 인식 로직 설계 시, 연산 자원이 제한된 환경에서도 안정적인 형태 파악을 위해 경량화된 형상 특징 추출 알고리즘을 우선 적용함.
### 매 분류
- **Boundary-based**: contour chain code, Fourier descriptors, polygon approx.
- **Region-based**: area, perimeter, eccentricity, Hu moments (rotation/scale invariant).
- **Gradient-based**: HOG (Dalal 2005), SIFT (Lowe 2004), SURF, ORB.
- **Texture+shape**: LBP, GLCM.
- **Deep**: CNN penultimate layer, ViT [CLS] token, DINOv3 patch features.
## 🔗 지식 연결 (Graph)
- Computer-Vision-Fundamentals, [[Representation-Learning|Representation-Learning]], [[Optical-Character-Recognition|Optical-Character-Recognition]]-OCR, [[Deep-Learning|Deep-Learning]]-Foundations
- **Raw Source:** 10_Wiki/Topics/AI/Shape-Feature-Extraction.md
### 매 Invariance 요구
- Translation: 매 거의 모든 method.
- Rotation: Hu moments, SIFT, RIFT.
- Scale: SIFT, multi-scale CNN.
- Illumination: HOG (gradient), normalized embeddings.
- Affine: ASIFT.
## 🤖 LLM 활용 힌트 (How to Use This Knowledge)
### 매 응용
1. Object recognition (legacy + edge).
2. Image retrieval / re-id (deep embeddings).
3. OCR pre-processing (contour).
4. Medical imaging (lesion shape descriptors).
5. Industrial defect inspection.
6. Robot grasp planning (object silhouette).
**언제 이 지식을 쓰는가:**
- *(TODO)*
## 💻 패턴
**언제 쓰면 안 되는가:**
- *(TODO)*
### Contour features (OpenCV)
```python
import cv2, numpy as np
gray = cv2.imread("obj.png", 0)
_, bw = cv2.threshold(gray, 0, 255, cv2.THRESH_OTSU)
contours, _ = cv2.findContours(bw, cv2.RETR_EXTERNAL, cv2.CHAIN_APPROX_SIMPLE)
c = max(contours, key=cv2.contourArea)
area = cv2.contourArea(c)
peri = cv2.arcLength(c, True)
circ = 4 * np.pi * area / (peri ** 2)
hu = cv2.HuMoments(cv2.moments(c)).flatten()
```
## 🧪 검증 상태 (Validation)
### HOG
```python
from skimage.feature import hog
feat, vis = hog(gray, orientations=9, pixels_per_cell=(8,8),
cells_per_block=(2,2), visualize=True)
```
- **정보 상태:** needs_review
- **출처 신뢰도:** A
- **검토 이유:** *(P-Reinforce Phase 1 자동 정규화. 본문 검증 필요.)*
### SIFT (OpenCV)
```python
sift = cv2.SIFT_create()
kp, desc = sift.detectAndCompute(gray, None) # desc: (N, 128)
```
## 🧬 중복 검사 (Duplicate Check)
### Fourier descriptors
```python
def fourier_descriptors(contour, k=20):
pts = contour[:, 0, 0] + 1j * contour[:, 0, 1]
fd = np.fft.fft(pts)
fd[0] = 0 # translation invariant
fd /= np.abs(fd[1]) # scale invariant
return np.abs(fd[1:k+1]) # rotation invariant (magnitude)
```
- **기존 유사 문서:** *(TODO: 인덱서 클러스터 리포트 참조)*
- **처리 방식:** UPDATE (자동 정규화)
- **처리 이유:** Phase 1 정규화 — 옛 템플릿/누락 필드 보강.
### Deep feature (DINOv3)
```python
import torch
from transformers import AutoModel, AutoImageProcessor
proc = AutoImageProcessor.from_pretrained("facebook/dinov3-base")
model = AutoModel.from_pretrained("facebook/dinov3-base").eval().cuda()
inp = proc(img, return_tensors="pt").to("cuda")
with torch.no_grad():
feats = model(**inp).last_hidden_state # (1, N+1, D)
cls_emb = feats[:, 0] # global shape/appearance
```
## 🕓 변경 이력 (Changelog)
### SAM2 mask + descriptor pipeline
```python
from sam2.build_sam import build_sam2
from sam2.sam2_image_predictor import SAM2ImagePredictor
sam = build_sam2("sam2_hiera_l.yaml", "sam2_l.pt")
pred = SAM2ImagePredictor(sam)
pred.set_image(img)
masks, _, _ = pred.predict(point_coords=pts, point_labels=lbl)
# 매 mask 내부 영역만 dino feature 뽑기 → object-centric descriptor
```
| 날짜 | 변경 내용 | 처리 방식 | 신뢰도 |
|------|-----------|-----------|--------|
| 2026-05-08 | P-Reinforce Phase 1 정규화 (frontmatter + 헤더 표준화) | UPDATE | A |
### Image retrieval pipeline
```python
emb = []
for p in paths:
e = dino_embed(load(p))
emb.append(e / e.norm())
emb = torch.stack(emb)
# query
q = dino_embed(load(query))
q /= q.norm()
sims = (emb @ q.T).flatten()
topk = sims.topk(10).indices
```
## 매 결정 기준
| 상황 | Approach |
|---|---|
| Modern recognition / retrieval | DINOv3 / CLIP embedding |
| Explainable / regulatory | Hu moments, contour |
| Real-time embedded | ORB or tiny CNN |
| Robust to occlusion | local features (SIFT/SuperPoint) |
| Mask 필요 + descriptor | SAM2 + DINO |
**기본값**: DINOv3 embedding for general purpose.
## 🔗 Graph
- 부모: [[Computer-Vision]] · [[Feature-Extraction]]
- 변형: [[HOG]] · [[SIFT]] · [[Hu-Moments]] · [[Deep-Features]]
- 응용: [[Image-Retrieval]] · [[Object-Recognition]] · [[OCR]]
- Adjacent: [[Image-Segmentation]] · [[SAM2]] · [[CLIP]]
## 🤖 LLM 활용
**언제**: dataset 작거나 explainability 요구 → classical. Otherwise deep.
**언제 X**: 매 generic image classification — end-to-end deep model 가 매 simpler.
## ❌ 안티패턴
- **HOG + SVM in 2026**: deep baseline 보다 명확히 약함 unless tiny data.
- **Hand-crafted features then deep classifier**: 매 mismatch — pick one paradigm.
- **No normalization**: scale/illumination drift → 매 retrieval 실패.
- **SIFT 특허 우려**: 2020+ 매 expired, 그래도 license 확인.
## 🧪 검증 / 중복
- Verified (Lowe 2004 SIFT, Dalal 2005 HOG, OpenCV docs, DINOv3 paper).
- 신뢰도 A.
## 🕓 Changelog
| 날짜 | 변경 |
|---|---|
| 2026-05-08 | Phase 1 |
| 2026-05-10 | Manual cleanup — classical + DINOv3/SAM2 2026 |