f8b21af4be
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>
232 lines
7.2 KiB
Markdown
232 lines
7.2 KiB
Markdown
---
|
|
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 |
|