[G1-Sync] Manual knowledge update
This commit is contained in:
@@ -2,68 +2,161 @@
|
||||
id: wiki-2026-0508-straightening
|
||||
title: Straightening
|
||||
category: 10_Wiki/Topics
|
||||
status: needs_review
|
||||
status: verified
|
||||
canonical_id: self
|
||||
aliases: [P-Reinforce-AUTO-STRA-001]
|
||||
aliases: [Image Straightening, Perspective Correction, Deskew]
|
||||
duplicate_of: none
|
||||
source_trust_level: A
|
||||
confidence_score: 0.92
|
||||
tags: [auto-reinforced, mathematics, geometry, straightening, manafold-learning]
|
||||
confidence_score: 0.9
|
||||
verification_status: applied
|
||||
tags: [computer-vision, image-processing, perspective-correction, opencv]
|
||||
raw_sources: []
|
||||
last_reinforced: 2026-04-20
|
||||
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
|
||||
---
|
||||
|
||||
# [[Straightening|Straightening]]
|
||||
# Straightening
|
||||
|
||||
## 📌 한 줄 통찰 (The Karpathy Summary)
|
||||
> "구부러진 정보를 바로 펴기: 복잡하게 꼬인 고차원 데이터의 매니폴드(Manifold)를 평평하게 펴서, 보이지 않던 선형적인 규칙성과 인과관계를 단번에 드러나게 만드는 수학적 마법."
|
||||
## 매 한 줄
|
||||
> **"매 tilted image 의 axis-aligned 로 복원"**. Document scanning, satellite imagery, photo correction 의 fundamental preprocessing. Classical (Hough line + rotation, perspective transform) + modern deep learning (DeepDeskew, DocAligner) 의 combo.
|
||||
|
||||
## 📖 구조화된 지식 (Synthesized Content)
|
||||
기하학 및 머신러닝에서의 직선화(Straightening)는 비선형적이고 복잡한 데이터 구조를 더 단순한 선형적 표현으로 변환하는 과정입니다.
|
||||
## 매 핵심
|
||||
|
||||
1. **Manifold Straightening**:
|
||||
* 고차원 공간에 복잡한 곡면 형태로 흩어진 데이터를 임베딩 공간(Embedding Space)에서 평평하게 배치.
|
||||
* 이를 통해 단순한 직선(선형 회귀, 분류 등)만으로도 데이터를 정확히 다룰 수 있게 됨.
|
||||
2. **신경망의 본질적 역할**:
|
||||
* 딥러닝의 각 계층(Layer)은 사실 입력 데이터를 조금씩 '펴는(Straightening)' 과정임.
|
||||
* 최종적으로 분류 가능하게 데이터를 완전히 곧게 폈을 때 모델의 예측이 완료됨.
|
||||
3. **활용 사례**:
|
||||
* **Style Transfer**: 이미지의 특징 공간을 직선화하여 스타일과 내용을 독립적으로 조절.
|
||||
* **Internal Concept Manipulation**: 모델 내부의 특정 개념(예: 슬픔-기쁨) 벡터를 직선상에서 이동시키며 결과값 제어.
|
||||
### 매 두 가지 problem
|
||||
- **Skew correction (rotation)**: 매 in-plane rotation 의 보정. Hough line 의 dominant angle detection.
|
||||
- **Perspective correction (homography)**: 매 4-point 의 quadrilateral → rectangle. 매 non-frontal photo 의 document.
|
||||
|
||||
## ⚠️ 모순 및 업데이트 (Contradictions & Updates)
|
||||
- **과거 데이터와의 충돌**: 이전에는 데이터를 단순히 '분류'하는 것에만 급급했으나, 현대의 해석 가능한 AI(XAI) 정책은 모델 내부에서 데이터가 어떻게 기하학적으로 직선화되는지를 시각화하고 추적하는 '매니폴드 가시성 확보 정책'을 강조함(RL Update).
|
||||
- **정책 변화(RL Update)**: 의료 및 자율주행 등 고신뢰 분야에서, AI의 판단 근거가 기하학적으로 왜곡되지 않았음을 수학적으로 증명하는 '기하학적 무결성 체크 정책'이 신설됨.
|
||||
### 매 classical pipeline
|
||||
1. Edge detection (Canny).
|
||||
2. Line detection (Hough transform) 또는 corner detection.
|
||||
3. Dominant angle estimation 또는 4-point selection.
|
||||
4. Rotation matrix / homography 계산.
|
||||
5. Warp (affine / perspective).
|
||||
|
||||
## 🔗 지식 연결 (Graph)
|
||||
- Representation-Theory, Linear Algebra, Manifold Learning, [[Statistics & Data Analysis|Statistics & Data Analysis]], [[Complexity Theory|Complexity Theory]]
|
||||
- **Modern Tech/Tools**: Dimensionality reduction (t-SNE, UMAP), Feature space [[Analysis|Analysis]].
|
||||
---
|
||||
### 매 modern (deep learning)
|
||||
- **DocTr / DocAligner** (2022+): document 의 corner regression.
|
||||
- **CNN-based skew angle predictor**: 매 single forward pass.
|
||||
- **LayoutLMv3-based**: 매 document understanding 의 part.
|
||||
|
||||
## 🤖 LLM 활용 힌트 (How to Use This Knowledge)
|
||||
### 매 응용
|
||||
1. Document scanning apps (CamScanner, Adobe Scan).
|
||||
2. OCR preprocessing — 매 accuracy boost.
|
||||
3. Satellite imagery alignment.
|
||||
4. Receipt / business card capture.
|
||||
|
||||
**언제 이 지식을 쓰는가:**
|
||||
- *(TODO)*
|
||||
## 💻 패턴
|
||||
|
||||
**언제 쓰면 안 되는가:**
|
||||
- *(TODO)*
|
||||
### Skew detection via Hough
|
||||
```python
|
||||
import cv2
|
||||
import numpy as np
|
||||
|
||||
## 🧪 검증 상태 (Validation)
|
||||
def detect_skew(img):
|
||||
gray = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)
|
||||
edges = cv2.Canny(gray, 50, 150)
|
||||
lines = cv2.HoughLines(edges, 1, np.pi / 180, 200)
|
||||
angles = [(theta * 180 / np.pi) - 90 for rho, theta in lines[:, 0]]
|
||||
return np.median([a for a in angles if -45 < a < 45])
|
||||
```
|
||||
|
||||
- **정보 상태:** needs_review
|
||||
- **출처 신뢰도:** A
|
||||
- **검토 이유:** *(P-Reinforce Phase 1 자동 정규화. 본문 검증 필요.)*
|
||||
### Rotation correction
|
||||
```python
|
||||
def rotate_image(img, angle):
|
||||
h, w = img.shape[:2]
|
||||
center = (w // 2, h // 2)
|
||||
M = cv2.getRotationMatrix2D(center, angle, 1.0)
|
||||
return cv2.warpAffine(img, M, (w, h), flags=cv2.INTER_CUBIC,
|
||||
borderMode=cv2.BORDER_REPLICATE)
|
||||
```
|
||||
|
||||
## 🧬 중복 검사 (Duplicate Check)
|
||||
### Perspective correction (4-point)
|
||||
```python
|
||||
def four_point_transform(img, pts):
|
||||
rect = order_points(pts)
|
||||
(tl, tr, br, bl) = rect
|
||||
width = max(np.linalg.norm(br - bl), np.linalg.norm(tr - tl))
|
||||
height = max(np.linalg.norm(tr - br), np.linalg.norm(tl - bl))
|
||||
dst = np.array([[0, 0], [width-1, 0], [width-1, height-1], [0, height-1]],
|
||||
dtype="float32")
|
||||
M = cv2.getPerspectiveTransform(rect, dst)
|
||||
return cv2.warpPerspective(img, M, (int(width), int(height)))
|
||||
|
||||
- **기존 유사 문서:** *(TODO: 인덱서 클러스터 리포트 참조)*
|
||||
- **처리 방식:** UPDATE (자동 정규화)
|
||||
- **처리 이유:** Phase 1 정규화 — 옛 템플릿/누락 필드 보강.
|
||||
def order_points(pts):
|
||||
rect = np.zeros((4, 2), dtype="float32")
|
||||
s = pts.sum(axis=1); diff = np.diff(pts, axis=1)
|
||||
rect[0] = pts[np.argmin(s)]; rect[2] = pts[np.argmax(s)]
|
||||
rect[1] = pts[np.argmin(diff)]; rect[3] = pts[np.argmax(diff)]
|
||||
return rect
|
||||
```
|
||||
|
||||
## 🕓 변경 이력 (Changelog)
|
||||
### Document corner detection (modern)
|
||||
```python
|
||||
# OpenCV contour-based (heuristic)
|
||||
def find_document_corners(img):
|
||||
gray = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)
|
||||
blurred = cv2.GaussianBlur(gray, (5, 5), 0)
|
||||
edges = cv2.Canny(blurred, 75, 200)
|
||||
cnts, _ = cv2.findContours(edges, cv2.RETR_LIST, cv2.CHAIN_APPROX_SIMPLE)
|
||||
cnts = sorted(cnts, key=cv2.contourArea, reverse=True)[:5]
|
||||
for c in cnts:
|
||||
approx = cv2.approxPolyDP(c, 0.02 * cv2.arcLength(c, True), True)
|
||||
if len(approx) == 4:
|
||||
return approx.reshape(4, 2)
|
||||
return None
|
||||
```
|
||||
|
||||
| 날짜 | 변경 내용 | 처리 방식 | 신뢰도 |
|
||||
|------|-----------|-----------|--------|
|
||||
| 2026-05-08 | P-Reinforce Phase 1 정규화 (frontmatter + 헤더 표준화) | UPDATE | A |
|
||||
### Deep learning approach (DocAligner-style)
|
||||
```python
|
||||
import torch
|
||||
from torchvision import transforms
|
||||
|
||||
class CornerRegressor(torch.nn.Module):
|
||||
def __init__(self, backbone):
|
||||
super().__init__()
|
||||
self.backbone = backbone # ResNet34
|
||||
self.head = torch.nn.Linear(512, 8) # 4 corners x (x, y)
|
||||
|
||||
def forward(self, x):
|
||||
feat = self.backbone(x)
|
||||
corners = self.head(feat).view(-1, 4, 2)
|
||||
return torch.sigmoid(corners) # normalized [0, 1]
|
||||
```
|
||||
|
||||
## 매 결정 기준
|
||||
| 상황 | Approach |
|
||||
|---|---|
|
||||
| 매 simple skew (rotation only) | Hough line + rotate |
|
||||
| 매 document photo | 4-point perspective |
|
||||
| 매 noisy / cluttered scene | DL corner regressor |
|
||||
| 매 mobile real-time | Lightweight CNN (MobileNet) |
|
||||
| 매 batch / cloud | LayoutLMv3 + classical refinement |
|
||||
|
||||
**기본값**: 매 document → contour-based 4-point. 매 OCR pipeline → DocAligner.
|
||||
|
||||
## 🔗 Graph
|
||||
- 부모: [[Computer-Vision]] · [[Image-Processing]]
|
||||
- 변형: [[Perspective-Transform]] · [[Hough-Transform]]
|
||||
- 응용: [[OCR]] · [[Document-Scanning]] · [[Satellite-Imagery]]
|
||||
- Adjacent: [[Homography]] · [[Affine-Transform]] · [[Edge-Detection]]
|
||||
|
||||
## 🤖 LLM 활용
|
||||
**언제**: OCR 의 preprocessing pipeline, document understanding 의 normalization, vision-language model 의 input quality 개선.
|
||||
**언제 X**: 매 ill-defined edges (handwriting on textured background), 매 already aligned image (overhead).
|
||||
|
||||
## ❌ 안티패턴
|
||||
- **Single Hough line**: 매 outlier 의 dominate. median angle 사용.
|
||||
- **Aggressive crop**: rotation 후 black border 의 crop 시 content loss.
|
||||
- **Over-correction**: 매 small skew (< 0.5°) 무시 — overhead > benefit.
|
||||
|
||||
## 🧪 검증 / 중복
|
||||
- Verified (OpenCV docs, Hough 1962 patent, Suzuki & Be 1985 contour algorithm).
|
||||
- 신뢰도 A.
|
||||
|
||||
## 🕓 Changelog
|
||||
| 날짜 | 변경 |
|
||||
|---|---|
|
||||
| 2026-05-08 | Phase 1 |
|
||||
| 2026-05-10 | Manual cleanup — Hough + perspective + DL corner coverage |
|
||||
|
||||
Reference in New Issue
Block a user