Files
2nd/10_Wiki/Topics/AI_and_ML/Neural-Style-Transfer.md
T
Antigravity Agent f8b21af4be Wiki cleanup: error-doc removal, dedup merge, link normalization
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>
2026-05-20 23:52:15 +09:00

6.8 KiB
Raw Blame History

id, title, category, status, canonical_id, aliases, duplicate_of, source_trust_level, confidence_score, verification_status, tags, raw_sources, last_reinforced, github_commit, tech_stack
id title category status canonical_id aliases duplicate_of source_trust_level confidence_score verification_status tags raw_sources last_reinforced github_commit tech_stack
wiki-2026-0508-neural-style-transfer Neural Style Transfer 10_Wiki/Topics verified self
NST
Style Transfer
Gatys Style Transfer
AdaIN
none A 0.93 applied
computer-vision
deep-learning
style-transfer
gatys
adain
diffusion
generative-art
2026-05-10 pending
language framework
python 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).
  • 폰트, 음성 스타일 변환.

💻 패턴

# 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"]
# 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)
# 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)))
# 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
# 5. Total variation loss — 노이즈 억제
def tv_loss(img):
    return ((img[:,:,1:,:] - img[:,:,:-1,:])**2).mean() + \
           ((img[:,:,:,1:] - img[:,:,:,:-1])**2).mean()
# 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)
# 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]
# 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]
# 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
# 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

🤖 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 추가.