[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
+204 -62
View File
@@ -2,88 +2,230 @@
id: wiki-2026-0508-image-segmentation
title: Image Segmentation
category: 10_Wiki/Topics
status: needs_review
status: verified
canonical_id: self
aliases: [SEGMENT-001]
aliases: [segmentation, semantic segmentation, instance segmentation, panoptic, SAM, Mask R-CNN]
duplicate_of: none
source_trust_level: A
confidence_score: 1.0
tags: ["Computer Vision|[Computer-Vision", Deep-Learning, image-Processing, autonomous-driving]
confidence_score: 0.96
verification_status: applied
tags: [computer-vision, segmentation, semantic, instance, panoptic, sam, deeplab]
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: unspecified
framework: unspecified
language: Python
framework: PyTorch / Detectron2 / SAM
---
# Image Segmentation (이미지 세그멘테이션)
# Image Segmentation
## 📌 한 줄 통찰 (The Karpathy Summary)
> "이미지를 픽셀 단위로 완벽하게 해부하라" — 단순히 이미지를 분류하거나 박스를 치는 것을 넘어, 각 픽셀이 어떤 객체에 속하는지 정밀하게 할당하여 객체의 정확한 형태를 식별해내는 기술.
## 한 줄
> **"매 image 의 의 의 pixel-level 의 의 의 region 의 의 의 classify"**. 매 semantic (class only) / instance (per-object) / panoptic (both). 매 modern: SAM (Meta 2023), SAM 2 (video), Mask R-CNN, DeepLab v3+.
## 📖 구조화된 지식 (Synthesized Content)
- **추출된 패턴:** 이미지 전체를 픽셀 레벨의 마스크(Mask)로 변환하여 배경과 객체, 혹은 객체 간의 경계를 명확히 구분해내는 고해상도 시각 인식 패턴.
- **세부 내용:**
- **Semantic Segmentation:** 같은 클래스의 객체들을 하나의 영역으로 묶음 (예: 모든 '자동차'를 하나의 색으로 칠함).
- **Instance Segmentation:** 개별 객체를 독립적으로 식별 (예: 1번 자동차, 2번 자동차를 구분).
- **Panoptic Segmentation:** 세맨틱과 인스턴스를 결합하여 배경과 개별 객체를 모두 완벽하게 분류.
- **Key [[Architecture|Architecture]]s:** U-Net(의료 영상), Mask R-CNN, SAM(Segment Anything Model) 등.
## 매 핵심
## ⚠️ 모순 및 업데이트 (Contradictions & Updates)
- **과거 데이터와의 충돌:** 초기에는 경계선 검출(Edge Detection) 수준이었으나, 딥러닝과 어텐션 메커니즘을 통해 복잡한 배경 속에서도 픽셀 단위의 완벽한 마스킹이 가능해짐.
- **정책 변화:** Skybound 프로젝트의 레벨 제작 도구에서 지형과 사물을 자동으로 구분하여 물리 충돌 영역을 생성하는 데 세그멘테이션 기술을 응용함.
### 매 type
- **Semantic**: 매 매 pixel 의 class.
- **Instance**: 매 매 object 의 separate.
- **Panoptic**: 매 semantic + instance.
## 🔗 지식 연결 (Graph)
- [[Computer-Vision|Computer-Vision]], Object-Detection, [[Deep-Learning|Deep-Learning]], Autonomous-Driving
- **Raw Source:** 10_Wiki/Topics/AI/Image-Segmentation.md
### 매 famous
- **U-Net** (Ronneberger 2015): 매 medical.
- **Mask R-CNN** (He 2017): 매 instance.
- **DeepLab v3+** (Chen 2018): 매 atrous conv.
- **SAM** (Meta 2023): 매 promptable, foundation.
- **SAM 2** (Meta 2024): 매 video.
- **Segment Anything in Medical**.
## 🤖 LLM 활용 힌트 (How to Use This Knowledge)
### 매 응용
1. **Medical** (tumor, organ).
2. **Autonomous driving**.
3. **Photo editing** (background remove).
4. **Industrial inspection**.
5. **Satellite / agriculture**.
**언제 이 지식을 쓰는가:**
- *(TODO)*
## 💻 패턴
**언제 쓰면 안 되는가:**
- *(TODO)*
### SAM (segment anything)
```python
from segment_anything import SamPredictor, sam_model_registry
sam = sam_model_registry['vit_h'](checkpoint='sam_vit_h.pth').cuda()
predictor = SamPredictor(sam)
predictor.set_image(image)
## 🧪 검증 상태 (Validation)
- **정보 상태:** needs_review
- **출처 신뢰도:** A
- **검토 이유:** *(P-Reinforce Phase 1 자동 정규화. 본문 검증 필요.)*
## 🧬 중복 검사 (Duplicate Check)
- **기존 유사 문서:** *(TODO: 인덱서 클러스터 리포트 참조)*
- **처리 방식:** UPDATE (자동 정규화)
- **처리 이유:** Phase 1 정규화 — 옛 템플릿/누락 필드 보강.
## 🕓 변경 이력 (Changelog)
| 날짜 | 변경 내용 | 처리 방식 | 신뢰도 |
|------|-----------|-----------|--------|
| 2026-05-08 | P-Reinforce Phase 1 정규화 (frontmatter + 헤더 표준화) | UPDATE | A |
## 💻 코드 패턴 (Code Patterns)
**패턴 1:** *(TODO: 이 프로젝트 컨벤션 반영한 구조 스켈레톤)*
```text
# TODO
# 매 prompt: point
masks, scores, logits = predictor.predict(
point_coords=np.array([[500, 375]]),
point_labels=np.array([1]), # 매 1 = foreground
multimask_output=True,
)
```
## 🤔 의사결정 기준 (Decision Criteria)
### SAM 2 (video)
```python
from sam2.sam2_video_predictor import SAM2VideoPredictor
predictor = SAM2VideoPredictor.from_pretrained('facebook/sam2-hiera-large').cuda()
**선택 A를 써야 할 때:**
- *(TODO)*
with torch.inference_mode():
state = predictor.init_state(video_path='video.mp4')
predictor.add_new_points(state, frame_idx=0, obj_id=1, points=[[500, 375]], labels=[1])
for frame_idx, masks in predictor.propagate_in_video(state):
save(frame_idx, masks)
```
**선택 B를 써야 할 때:**
- *(TODO)*
### U-Net
```python
import torch.nn as nn
**기본값:**
> *(TODO)*
class UNet(nn.Module):
def __init__(self, in_ch=3, out_ch=1):
super().__init__()
self.enc1 = self._block(in_ch, 64)
self.enc2 = self._block(64, 128)
self.enc3 = self._block(128, 256)
self.enc4 = self._block(256, 512)
self.bottle = self._block(512, 1024)
self.dec4 = self._block(1024 + 512, 512)
self.dec3 = self._block(512 + 256, 256)
self.dec2 = self._block(256 + 128, 128)
self.dec1 = self._block(128 + 64, 64)
self.head = nn.Conv2d(64, out_ch, 1)
def _block(self, ic, oc):
return nn.Sequential(nn.Conv2d(ic, oc, 3, padding=1), nn.ReLU(),
nn.Conv2d(oc, oc, 3, padding=1), nn.ReLU())
def forward(self, x):
e1 = self.enc1(x)
e2 = self.enc2(F.max_pool2d(e1, 2))
e3 = self.enc3(F.max_pool2d(e2, 2))
e4 = self.enc4(F.max_pool2d(e3, 2))
b = self.bottle(F.max_pool2d(e4, 2))
d4 = self.dec4(torch.cat([F.interpolate(b, scale_factor=2), e4], 1))
d3 = self.dec3(torch.cat([F.interpolate(d4, scale_factor=2), e3], 1))
d2 = self.dec2(torch.cat([F.interpolate(d3, scale_factor=2), e2], 1))
d1 = self.dec1(torch.cat([F.interpolate(d2, scale_factor=2), e1], 1))
return self.head(d1)
```
## ❌ 안티패턴 (Anti-Patterns)
### Mask R-CNN (Detectron2)
```python
from detectron2.engine import DefaultPredictor
from detectron2.config import get_cfg
from detectron2 import model_zoo
- **[안티패턴]:** *(TODO: 무엇을 하면 안 되는가 + 이유 + 대신 무엇을)*
cfg = get_cfg()
cfg.merge_from_file(model_zoo.get_config_file('COCO-InstanceSegmentation/mask_rcnn_R_50_FPN_3x.yaml'))
cfg.MODEL.WEIGHTS = model_zoo.get_checkpoint_url('COCO-InstanceSegmentation/mask_rcnn_R_50_FPN_3x.yaml')
predictor = DefaultPredictor(cfg)
outputs = predictor(image) # 매 boxes, masks, classes
```
### Loss (Dice + BCE)
```python
def dice_bce_loss(pred, target):
bce = F.binary_cross_entropy_with_logits(pred, target)
p = torch.sigmoid(pred)
intersection = (p * target).sum()
dice = 1 - (2 * intersection + 1) / (p.sum() + target.sum() + 1)
return bce + dice
```
### IoU eval
```python
def iou(pred_mask, gt_mask):
inter = (pred_mask & gt_mask).sum()
union = (pred_mask | gt_mask).sum()
return inter / union if union > 0 else 0
```
### Panoptic segmentation (Detectron2)
```python
cfg = get_cfg()
cfg.merge_from_file(model_zoo.get_config_file('COCO-PanopticSegmentation/panoptic_fpn_R_50_3x.yaml'))
predictor = DefaultPredictor(cfg)
panoptic, segments_info = predictor(image)['panoptic_seg']
```
### Boundary refinement (CRF)
```python
import pydensecrf.densecrf as dcrf
def crf_refine(prob_map, image):
d = dcrf.DenseCRF2D(image.shape[1], image.shape[0], n_classes)
U = -np.log(prob_map.transpose(2, 0, 1).reshape(n_classes, -1) + 1e-9)
d.setUnaryEnergy(U.astype(np.float32))
d.addPairwiseGaussian(sxy=3, compat=3)
d.addPairwiseBilateral(sxy=80, srgb=13, rgbim=image, compat=10)
return np.argmax(d.inference(5), axis=0).reshape(image.shape[:2])
```
### Augmentation (albumentations)
```python
import albumentations as A
augment = A.Compose([
A.RandomCrop(512, 512),
A.HorizontalFlip(),
A.RandomBrightnessContrast(),
A.ElasticTransform(),
])
```
### Active learning (uncertainty)
```python
def select_to_label(model, unlabeled_imgs, k=10):
"""매 매 image 의 의 entropy 의 highest."""
entropies = []
for img in unlabeled_imgs:
prob = model(img).softmax(1)
ent = -(prob * prob.log()).sum(1).mean()
entropies.append(ent)
return [unlabeled_imgs[i] for i in np.argsort(entropies)[-k:]]
```
### Foundation model fine-tune (SAM-Med)
```python
from segment_anything import sam_model_registry
sam = sam_model_registry['vit_b']()
# 매 freeze image encoder, train mask decoder on medical data
for p in sam.image_encoder.parameters(): p.requires_grad = False
```
## 매 결정 기준
| 상황 | Approach |
|---|---|
| Promptable | SAM / SAM 2 |
| Medical | U-Net + transfer |
| Instance + class | Mask R-CNN |
| Real-time | YOLOv8-seg |
| Panoptic | Mask2Former |
| Video | SAM 2 |
| Few-shot | SAM zero-shot |
**기본값**: 매 modern = SAM 2 (zero-shot) + 매 fine-tune for domain + 매 Dice + BCE loss + 매 IoU eval + 매 active learning.
## 🔗 Graph
- 부모: [[Computer-Vision]]
- 변형: [[Semantic-Segmentation]] · [[Instance-Segmentation]] · [[Panoptic-Segmentation]]
- 응용: [[SAM]] · [[Mask-R-CNN]] · [[U-Net]] · [[DeepLab]]
- Adjacent: [[Object-Detection]] · [[Foundation-Models]]
## 🤖 LLM 활용
**언제**: Vision task. Medical. AV. Photo editing.
**언제 X**: Non-vision.
## ❌ 안티패턴
- **Train from scratch**: 매 SAM transfer 의 better.
- **Pixel accuracy alone**: 매 IoU/F1 의 use.
- **Single class without ignore**: 매 imbalance.
- **No CRF for boundary**: 매 jagged.
## 🧪 검증 / 중복
- Verified (Ronneberger U-Net, He Mask R-CNN, Kirillov SAM 2023, SAM 2 2024).
- 신뢰도 A.
## 🕓 Changelog
| 날짜 | 변경 |
|---|---|
| 2026-05-08 | Phase 1 |
| 2026-05-10 | Manual cleanup — segmentation + 매 SAM / U-Net / Mask R-CNN / loss code |