docs(10_Wiki): 위키 전체 재구성 — Topic_* 폴더를 4개 카테고리로 통합 + 대규모 중복 제거

Topic_Agent/Topic_Blog/Topics/Topics_Biz/Topics_Meeting/Topics_Rag의 마크다운 지식 문서를
Topic_General/Topic_Programming/Topic_Graphic/Topic_Business 4개 카테고리로 재분류.

- 중복 제거: frontmatter의 status:duplicate/merged + duplicate_of/redirect_to 필드로
  자기 자신을 중복으로 선언한 리다이렉트 stub 1032개 제거, 완전 동일 내용 파일 472개 제거,
  동일 파일명·다른 내용 충돌 시 더 큰(완전한) 버전만 유지(162개 제거) — 총 1639개 중복 제거.
- 분류: 폴더 단위로 명확한 항목(AI_and_ML/Coding/Architecture 등 → Programming,
  Comfyui/Visual_Effects → Graphic, Topics_Biz/Topics_Meeting/사업 등 → Business,
  Poetic_Blog_Writing/창의성/Game_Design 등 → General)은 폴더 우선순위로,
  나머지 혼재 폴더(Topic_Agent/Topic_Blog/Topics 루트/Thinking & Reasoning/Other/UI_UX_Assets)는
  title/tags 키워드 스코어링으로 파일 단위 분류(불명확한 경우 General로 폴백).
  원본 폴더명은 "From_*" 서브폴더로 보존해 추적 가능성 유지.
- 최종 배치: Programming 2784 / General 1608 / Graphic 285 / Business 249 = 4926개 문서.
- 에이전트 운영 상태(.astra/.agent/.obsidian/sessions/memory/_company/docs/lessons/_shared/src)는
  지식 콘텐츠가 아니므로 재분류 대상에서 제외하고 원위치 유지.
- Topics/Topic_email(상위 보호 폴더 Topic_email과 파일명 100% 중복) 삭제 — 보호 폴더 자체는 미변경.
- 완전히 비게 된 Topic_Agent/Topic_Blog/Topics_Biz/Topics_Rag 폴더 제거.
This commit is contained in:
Antigravity Agent
2026-07-05 00:33:48 +09:00
parent 1cfd3bbb56
commit 9148c358d0
6455 changed files with 1 additions and 86875 deletions
@@ -0,0 +1,231 @@
---
id: wiki-2026-0508-image-segmentation
title: Image Segmentation
category: 10_Wiki/Topics
status: verified
canonical_id: self
aliases: [segmentation, semantic segmentation, instance segmentation, panoptic, SAM, Mask R-CNN]
duplicate_of: none
source_trust_level: A
confidence_score: 0.96
verification_status: applied
tags: [computer-vision, segmentation, semantic, instance, panoptic, sam, deeplab]
raw_sources: []
last_reinforced: 2026-05-10
github_commit: pending
tech_stack:
language: Python
framework: PyTorch / Detectron2 / SAM
---
# Image Segmentation
## 매 한 줄
> **"매 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+.
## 매 핵심
### 매 type
- **Semantic**: 매 매 pixel 의 class.
- **Instance**: 매 매 object 의 separate.
- **Panoptic**: 매 semantic + instance.
### 매 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**.
### 매 응용
1. **Medical** (tumor, organ).
2. **Autonomous driving**.
3. **Photo editing** (background remove).
4. **Industrial inspection**.
5. **Satellite / agriculture**.
## 💻 패턴
### 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)
# 매 prompt: point
masks, scores, logits = predictor.predict(
point_coords=np.array([[500, 375]]),
point_labels=np.array([1]), # 매 1 = foreground
multimask_output=True,
)
```
### SAM 2 (video)
```python
from sam2.sam2_video_predictor import SAM2VideoPredictor
predictor = SAM2VideoPredictor.from_pretrained('facebook/sam2-hiera-large').cuda()
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)
```
### U-Net
```python
import torch.nn as nn
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)
```
### Mask R-CNN (Detectron2)
```python
from detectron2.engine import DefaultPredictor
from detectron2.config import get_cfg
from detectron2 import model_zoo
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|Computer-Vision]]
- 변형: [[Semantic-Segmentation]] · [[Instance-Segmentation]]
- 응용: [[SAM]] · [[Mask-R-CNN]]
- 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 |