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:
@@ -0,0 +1,197 @@
|
||||
---
|
||||
id: wiki-2026-0508-neural-style-transfer
|
||||
title: Neural Style Transfer
|
||||
category: 10_Wiki/Topics
|
||||
status: verified
|
||||
canonical_id: self
|
||||
aliases: [NST, Style Transfer, Gatys Style Transfer, AdaIN]
|
||||
duplicate_of: none
|
||||
source_trust_level: A
|
||||
confidence_score: 0.93
|
||||
verification_status: applied
|
||||
tags: [computer-vision, deep-learning, style-transfer, gatys, adain, diffusion, generative-art]
|
||||
raw_sources: []
|
||||
last_reinforced: 2026-05-10
|
||||
github_commit: pending
|
||||
tech_stack: { language: python, framework: pytorch }
|
||||
---
|
||||
|
||||
## 한 줄
|
||||
|
||||
Neural Style Transfer(NST)는 콘텐츠 이미지의 구조를 유지하면서 스타일 이미지의 텍스처/색감을 합성하기 위해, 사전학습 CNN의 feature와 Gram matrix를 활용해 입력 이미지를 최적화하거나 별도 네트워크로 학습하는 기법군이다.
|
||||
|
||||
## 핵심
|
||||
|
||||
### Gatys et al. 2015 (원형)
|
||||
- 사전학습 VGG-19 사용.
|
||||
- **Content loss**: 특정 layer (예: conv4_2) feature MSE.
|
||||
- **Style loss**: 여러 layer Gram matrix MSE — 채널 간 상관관계가 텍스처를 표현.
|
||||
- 입력 이미지 자체를 최적화 (수십 초~수 분).
|
||||
- 총 손실: `L = α·L_content + β·L_style`.
|
||||
|
||||
### Fast Neural Style (Johnson 2016)
|
||||
- 한 번에 한 스타일을 학습한 transformation network.
|
||||
- 추론 시 단일 forward pass — 실시간.
|
||||
- 손실은 여전히 VGG perceptual + Gram.
|
||||
|
||||
### Arbitrary Style Transfer
|
||||
- **AdaIN** (Huang & Belongie 2017): 콘텐츠 feature의 평균/분산을 스타일에 맞춰 정규화.
|
||||
- **WCT** (Whitening & Coloring Transform).
|
||||
- 임의 스타일 한 번에 처리 (재학습 불필요).
|
||||
|
||||
### 현대(2023-26)
|
||||
- **Diffusion-based**: SDXL + IP-Adapter, ControlNet, Stable Diffusion Style LoRA.
|
||||
- **InstantStyle (2024)**: 단일 참조 이미지로 스타일 추출, content leakage 차단.
|
||||
- **StyleGAN inversion + edit**.
|
||||
- 영상: AnimateDiff + style.
|
||||
|
||||
### 변형 / 응용
|
||||
- Photorealistic style transfer (PhotoWCT, deep photo style transfer).
|
||||
- 비디오 NST — temporal consistency loss.
|
||||
- 3D NST (NeRF + style).
|
||||
- 폰트, 음성 스타일 변환.
|
||||
|
||||
## 💻 패턴
|
||||
|
||||
```python
|
||||
# 1. Gatys NST — VGG19 기반 (PyTorch)
|
||||
import torch, torch.nn as nn, torch.optim as optim
|
||||
from torchvision.models import vgg19
|
||||
|
||||
vgg = vgg19(weights="DEFAULT").features.eval().cuda()
|
||||
for p in vgg.parameters(): p.requires_grad = False
|
||||
|
||||
def gram(x):
|
||||
b,c,h,w = x.shape
|
||||
f = x.view(b,c,h*w)
|
||||
return f @ f.transpose(1,2) / (c*h*w)
|
||||
|
||||
content_layers = ["conv4_2"]
|
||||
style_layers = ["conv1_1","conv2_1","conv3_1","conv4_1","conv5_1"]
|
||||
```
|
||||
|
||||
```python
|
||||
# 2. NST 최적화 루프
|
||||
img = content.clone().requires_grad_(True)
|
||||
opt = optim.LBFGS([img])
|
||||
|
||||
def closure():
|
||||
opt.zero_grad()
|
||||
feats = extract(vgg, img)
|
||||
cl = sum(F.mse_loss(feats[l], target_content[l]) for l in content_layers)
|
||||
sl = sum(F.mse_loss(gram(feats[l]), gram_style[l]) for l in style_layers)
|
||||
loss = 1.0*cl + 1e6*sl
|
||||
loss.backward()
|
||||
return loss
|
||||
|
||||
for _ in range(300): opt.step(closure)
|
||||
```
|
||||
|
||||
```python
|
||||
# 3. Fast Style Transfer — transformer net
|
||||
class TransformerNet(nn.Module):
|
||||
def __init__(self):
|
||||
super().__init__()
|
||||
self.encoder = nn.Sequential(
|
||||
ConvBlock(3,32,9,1), ConvBlock(32,64,3,2), ConvBlock(64,128,3,2),
|
||||
)
|
||||
self.residual = nn.Sequential(*[ResBlock(128) for _ in range(5)])
|
||||
self.decoder = nn.Sequential(
|
||||
UpsampleConv(128,64), UpsampleConv(64,32), nn.Conv2d(32,3,9,padding=4),
|
||||
)
|
||||
def forward(self, x): return self.decoder(self.residual(self.encoder(x)))
|
||||
```
|
||||
|
||||
```python
|
||||
# 4. AdaIN — 임의 스타일
|
||||
def adain(content_feat, style_feat, eps=1e-5):
|
||||
c_mean, c_std = content_feat.mean([2,3], keepdim=True), content_feat.std([2,3], keepdim=True)+eps
|
||||
s_mean, s_std = style_feat.mean([2,3], keepdim=True), style_feat.std([2,3], keepdim=True)+eps
|
||||
return s_std * (content_feat - c_mean) / c_std + s_mean
|
||||
```
|
||||
|
||||
```python
|
||||
# 5. Total variation loss — 노이즈 억제
|
||||
def tv_loss(img):
|
||||
return ((img[:,:,1:,:] - img[:,:,:-1,:])**2).mean() + \
|
||||
((img[:,:,:,1:] - img[:,:,:,:-1])**2).mean()
|
||||
```
|
||||
|
||||
```python
|
||||
# 6. Color preservation — luminance only NST
|
||||
import cv2, numpy as np
|
||||
yuv = cv2.cvtColor(stylized, cv2.COLOR_RGB2YUV)
|
||||
yuv[:,:,1:] = cv2.cvtColor(content_orig, cv2.COLOR_RGB2YUV)[:,:,1:]
|
||||
preserved = cv2.cvtColor(yuv, cv2.COLOR_YUV2RGB)
|
||||
```
|
||||
|
||||
```python
|
||||
# 7. Diffusion + IP-Adapter — 2024 표준
|
||||
from diffusers import StableDiffusionXLPipeline
|
||||
pipe = StableDiffusionXLPipeline.from_pretrained("...").to("cuda")
|
||||
pipe.load_ip_adapter("h94/IP-Adapter", subfolder="sdxl_models",
|
||||
weight_name="ip-adapter_sdxl.safetensors")
|
||||
pipe.set_ip_adapter_scale(0.7)
|
||||
result = pipe(prompt="a cat", ip_adapter_image=style_img).images[0]
|
||||
```
|
||||
|
||||
```python
|
||||
# 8. Style LoRA + Stable Diffusion
|
||||
pipe.load_lora_weights("path/to/style_lora.safetensors")
|
||||
pipe.fuse_lora()
|
||||
img = pipe(prompt="cyberpunk city <lora:style:0.8>").images[0]
|
||||
```
|
||||
|
||||
```python
|
||||
# 9. 비디오 NST — temporal consistency
|
||||
def temporal_loss(stylized_t, stylized_t_prev, flow):
|
||||
warped = warp(stylized_t_prev, flow)
|
||||
return F.mse_loss(stylized_t, warped) * mask
|
||||
```
|
||||
|
||||
```python
|
||||
# 10. InstantStyle — content/style 분리
|
||||
# IP-Adapter blocks 중 style-specific block만 활성화
|
||||
pipe.set_ip_adapter_scale({"down": {"block_2": [0,1]}, "up": {"block_0": [0,1,1]}})
|
||||
```
|
||||
|
||||
## 결정 기준
|
||||
|
||||
| 상황 | 추천 |
|
||||
|---|---|
|
||||
| 단일 결과, 최고 품질 | Gatys NST (LBFGS, VGG19) |
|
||||
| 실시간 / 영상 | Fast NST 또는 AdaIN |
|
||||
| 임의 스타일 | AdaIN, WCT |
|
||||
| 사진 사실성 유지 | PhotoWCT, deep photo style |
|
||||
| 텍스트 프롬프트 함께 | SDXL + IP-Adapter |
|
||||
| 일관된 브랜드 스타일 | Style LoRA fine-tune |
|
||||
| 비디오 | temporal loss + Fast NST 또는 AnimateDiff |
|
||||
| 콘텐츠 누출 차단 | InstantStyle 블록 마스킹 |
|
||||
|
||||
기본값: 일회성 결과는 Gatys, 프로덕션은 SDXL+IP-Adapter.
|
||||
|
||||
## 🔗 Graph
|
||||
- 부모: [[Computer Vision|Computer-Vision]], [[Generative-AI]], [[AI 이미지 생성 (AI Image Generation)|Image-Generation]]
|
||||
- 형제: [[Generative-Adversarial-Networks|GAN]], [[Diffusion-Models]], [[Stable-Diffusion]], [[CycleGAN]]
|
||||
- 자식: [[AdaIN]], [[IP-Adapter]]
|
||||
- 응용: [[Generative-Art]]
|
||||
|
||||
## 🤖 LLM 활용
|
||||
- VLM이 스타일 키워드 추출 ("Van Gogh, post-impressionist, swirling brushstrokes") → SD prompt 자동.
|
||||
- LLM agent가 NST 파라미터(α/β, layer 선택) 자동 튜닝.
|
||||
- 평가: CLIP score로 style 일치도 측정.
|
||||
|
||||
## ❌ 안티패턴
|
||||
- Style/content weight 비율 무튜닝 — 결과 품질 좌우.
|
||||
- VGG 외 backbone에서 동일 layer 가정.
|
||||
- 영상에 frame별 NST만 적용 → 깜빡임.
|
||||
- IP-Adapter scale=1.0 → content 누출.
|
||||
|
||||
## 🧪 검증 / 중복
|
||||
- 정량: SSIM (content), Gram MSE (style), CLIP similarity.
|
||||
- 정성: 사용자 평가.
|
||||
- 중복: [[Style-Transfer]] 별칭 통합.
|
||||
|
||||
## 🕓 Changelog
|
||||
- Phase 1 (2026-05-08): 초기 생성.
|
||||
- Manual cleanup (2026-05-10): canonical 확정, Gatys → AdaIN → 확산 모델까지 흐름 정리, IP-Adapter/InstantStyle 추가.
|
||||
Reference in New Issue
Block a user