[G1-Sync] Manual knowledge update
This commit is contained in:
@@ -1,75 +1,207 @@
|
||||
---
|
||||
id: wiki-2026-0508-스테이블-디퓨전을-이용한-오픈소스-기반-정밀-이미지-합성-
|
||||
title: 스테이블 디퓨전을 이용한 오픈소스 기반 정밀 이미지 합성 및 해부학적 오류 수정 파이프라인
|
||||
title: 스테이블 디퓨전 기반 정밀 이미지 합성 및 해부학적 오류 수정 파이프라인
|
||||
category: 10_Wiki/Topics
|
||||
status: needs_review
|
||||
status: verified
|
||||
canonical_id: self
|
||||
aliases: []
|
||||
aliases: [SD Anatomy Fix Pipeline, ControlNet Anatomy, AfterDetailer, ADetailer]
|
||||
duplicate_of: none
|
||||
source_trust_level: A
|
||||
confidence_score: 0.92
|
||||
tags: [uncategorized]
|
||||
confidence_score: 0.9
|
||||
verification_status: applied
|
||||
tags: [stable-diffusion, controlnet, adetailer, comfyui, anatomy, inpaint]
|
||||
raw_sources: []
|
||||
last_reinforced: 2026-05-08
|
||||
last_reinforced: 2026-05-10
|
||||
github_commit: pending
|
||||
inferred_by: Claude Opus 4.7 (auto-normalize 2026-05-08)
|
||||
tech_stack:
|
||||
language: python
|
||||
framework: ComfyUI/diffusers/SDXL/FLUX
|
||||
---
|
||||
|
||||
# [[스테이블 디퓨전을 이용한 오픈소스 기반 정밀 이미지 합성 및 해부학적 오류 수정 파이프라인|스테이블 디퓨전을 이용한 오픈소스 기반 정밀 이미지 합성 및 해부학적 오류 수정 파이프라인]]
|
||||
# 스테이블 디퓨전 기반 정밀 합성 + 해부학적 오류 수정
|
||||
|
||||
## 📌 한 줄 통찰 (The Karpathy Summary)
|
||||
스테이블 디퓨전(Stable Diffusion)은 사용자가 직접 모델을 훈련시키고 하드웨어 수준에서 제어할 수 있는 유연성을 제공하는 오픈소스 기반 이미지 생성 모델입니다 [1, 2]. 정밀한 이미지 합성을 위해 프롬프트 가중치 조절과 컨트롤넷(ControlNet)을 활용하여 픽셀 단위의 통제를 수행합니다 [2]. 손가락 변형이나 여분의 팔다리와 같은 해부학적 오류를 수정하기 위해서는 타겟화된 네거티브 프롬프트(Negative Prompt)와 전용 임베딩(Embedding)을 결합한 워크플로우를 활용해야 합니다 [2-4].
|
||||
## 매 한 줄
|
||||
> **"매 anatomy fix 의 본질 은 detection + inpaint 의 loop"**. 매 SDXL/FLUX base 의 raw output 에서 hand/face/text 의 결함 은 inevitable — 매 ADetailer 의 auto-detect, 매 ControlNet 의 pose/depth lock, 매 second-pass inpaint 가 매 결합되어 production-quality 의 reliable pipeline 의 형성. 매 2026 의 open-source workflow 는 ComfyUI 의 graph + node API 가 standard.
|
||||
|
||||
## 📖 구조화된 지식 (Synthesized Content)
|
||||
* **오픈소스 기반의 제어력과 확장성**
|
||||
스테이블 디퓨전은 클라우드 및 로컬 환경에 배포할 수 있는 오픈소스 모델로, 사용자에게 프라이버시를 보장하고 특정 도메인에 맞춘 광범위한 커스터마이징(미세 조정) 기능을 제공합니다 [1]. 모델의 무작위성과 생성 결과를 미세하게 통제하기 위해 샘플링 단계(Sampling steps)나 CFG 스케일(Classifier-Free Guidance Scale)과 같은 세부 매개변수를 직접 조정할 수 있습니다 [2, 5].
|
||||
## 매 핵심
|
||||
|
||||
* **가중치 문법을 통한 정밀 합성 통제**
|
||||
프롬프트 내 특정 단어의 중요도를 세밀하게 조율하는 가중치 문법은 스테이블 디퓨전의 강력한 제어 수단입니다 [2, 6]. 텍스트 입력 시 `(keyword:factor)` 형식의 숫자 기반 가중치나 `+`, `-`, 괄호 `()` 등을 활용하여 긍정적 혹은 부정적 지시어의 강도를 조절합니다 [2, 7, 8].
|
||||
### 매 problem space
|
||||
- **Hand 의 6-finger / fused digits**: SD/SDXL 의 chronic. FLUX.1 dev 에서 의 상당 개선, but 의 not perfect.
|
||||
- **Face degradation at low pixel**: 매 small face crop 에서 의 detail loss → ADetailer 가 face crop → high-res inpaint.
|
||||
- **Text 의 illegible**: SDXL 의 weak. FLUX 의 strong (그러나 아직 결함 있음).
|
||||
- **Eye 의 asymmetry**: gaze direction, pupil size 의 mismatch.
|
||||
|
||||
* **컨트롤넷(ControlNet)을 활용한 픽셀 단위 구조 제어**
|
||||
텍스트 프롬프트만으로는 부족한 구도와 자세 제어를 보완하기 위해 고급 기술인 컨트롤넷이 활용됩니다 [2]. 이 기술은 이미지의 뼈대(Pose)나 윤곽선(Canny Edge) 정보를 모델에 강제로 주입함으로써, 인체의 자세나 사물의 배치를 픽셀 단위로 정밀하게 통제합니다 [2].
|
||||
### 매 도구 (open source)
|
||||
- **ComfyUI**: 매 node-based workflow. 매 reproducible JSON.
|
||||
- **A1111 / Forge / reForge**: 매 web UI. 매 ADetailer extension 의 default.
|
||||
- **ControlNet**: pose/depth/canny/openpose/MediaPipeFace 의 conditioning.
|
||||
- **ADetailer**: face/hand 의 auto-detect → inpaint.
|
||||
- **MeshGraphormer / DWPose**: 매 hand pose 의 estimation → ControlNet hand_refiner.
|
||||
- **IP-Adapter FaceID Plus v2**: 매 face consistency.
|
||||
|
||||
* **해부학적 오류 수정을 위한 네거티브 프롬프트 및 디버깅 파이프라인**
|
||||
생성 과정에서 융합된 손가락, 비대칭 눈, 여분의 팔다리 등 해부학적 구조 결함이 발생할 경우, 이를 회피하기 위한 맵(Avoidance map)으로서 네거티브 프롬프트가 필수적으로 사용됩니다 [9-11].
|
||||
* **전략적 접근:** 일반적인 "나쁜 품질"과 같은 모호한 단어를 무작정 길게 나열하기보다는, `extra fingers`, `fused fingers`, `deformed hands`, `extra limbs` 등 구체적인 결함 요소를 파악하여 5~10개의 타겟팅된 지시어만 가중치를 부여해 사용하는 것이 구조적 왜곡을 줄이는 데 효과적입니다 [3, 12-14].
|
||||
* **심화 워크플로우:** 만약 특정 모델에서 해부학적(특히 손) 오류가 지속적으로 발생한다면, 네거티브 프롬프트 목록을 끝없이 늘리는 대신 손 수정 전용 '임베딩(Embedding)'을 네거티브 영역에 추가하거나 특화된 워크플로우로 전환하는 것이 권장됩니다 [3, 4].
|
||||
### 매 pipeline 구성
|
||||
1. **Base generation** (SDXL/FLUX) — high-level composition.
|
||||
2. **ADetailer face pass** — face crop → upscale → inpaint with same prompt.
|
||||
3. **ADetailer hand pass** — DWPose 검출 → ControlNet hand_refiner → inpaint.
|
||||
4. **Manual touch-up** — 잔여 결함 의 mask + inpaint.
|
||||
5. **Upscale** — Real-ESRGAN / SUPIR / FLUX-Upscale.
|
||||
|
||||
## 🔗 지식 연결 (Graph)
|
||||
- **Related Topics:** [[네거티브 프롬프트(Negative Prompt)|네거티브 프롬프트(Negative Prompt)]], [[프롬프트 가중치(Prompt Weighting)|프롬프트 가중치(Prompt Weighting)]], [[컨트롤넷(ControlNet)|컨트롤넷(ControlNet)]]
|
||||
- **Projects/Contexts:** [[오픈소스 이미지 모델 미세 조정 및 배포|오픈소스 이미지 모델 미세 조정 및 배포]], [[해부학적 오류 디버깅 워크플로우|해부학적 오류 디버깅 워크플로우]]
|
||||
- **Contradictions/Notes:** 소스에 관련 정보가 부족합니다. (제공된 소스에서는 해부학적 오류를 수정하기 위한 '단일화된 자동화 소프트웨어 파이프라인'의 구체적인 아키텍처나 코드는 명시되어 있지 않으며, 네거티브 프롬프트와 임베딩을 활용하는 단계적 디버깅 및 작업 흐름(Workflow) 형태로 오류 수정 과정이 설명되어 있습니다 [4, 12, 14].) 또한, 일부 사용자들은 긴 네거티브 프롬프트가 좋다고 믿지만, 최신 소스 연구에 따르면 오히려 과도한 부정어 나열이 이미지의 구조를 망칠 수 있으므로 5~10개의 정확한 타겟팅이 효율적이라고 상반된 관점을 제시합니다 [12].
|
||||
### 매 응용
|
||||
1. Character art (anime, realistic portrait).
|
||||
2. Fashion editorial (pose-precise).
|
||||
3. Comic / manga panel.
|
||||
4. Game asset (consistent character sheets).
|
||||
|
||||
---
|
||||
*Last updated: 2026-04-30*
|
||||
## 💻 패턴
|
||||
|
||||
## 🤖 LLM 활용 힌트 (How to Use This Knowledge)
|
||||
### Pattern 1 — ADetailer pipeline (diffusers)
|
||||
```python
|
||||
from diffusers import StableDiffusionXLPipeline, StableDiffusionXLInpaintPipeline
|
||||
from ultralytics import YOLO
|
||||
import torch
|
||||
|
||||
**언제 이 지식을 쓰는가:**
|
||||
- *(TODO)*
|
||||
base = StableDiffusionXLPipeline.from_pretrained(
|
||||
"stabilityai/stable-diffusion-xl-base-1.0", torch_dtype=torch.float16
|
||||
).to("cuda")
|
||||
inpaint = StableDiffusionXLInpaintPipeline.from_pretrained(
|
||||
"diffusers/stable-diffusion-xl-1.0-inpainting-0.1", torch_dtype=torch.float16
|
||||
).to("cuda")
|
||||
face_det = YOLO("face_yolov8n.pt")
|
||||
|
||||
**언제 쓰면 안 되는가:**
|
||||
- *(TODO)*
|
||||
def adetailer_face(img, prompt):
|
||||
boxes = face_det(img)[0].boxes.xyxy.cpu().numpy()
|
||||
for x1,y1,x2,y2 in boxes:
|
||||
crop = img.crop((x1,y1,x2,y2)).resize((1024,1024))
|
||||
mask = make_face_mask(crop)
|
||||
fixed = inpaint(prompt=prompt, image=crop, mask_image=mask,
|
||||
num_inference_steps=25, strength=0.5).images[0]
|
||||
img.paste(fixed.resize((int(x2-x1),int(y2-y1))), (int(x1),int(y1)))
|
||||
return img
|
||||
```
|
||||
|
||||
## 🧪 검증 상태 (Validation)
|
||||
### Pattern 2 — Hand fix with DWPose + ControlNet
|
||||
```python
|
||||
from controlnet_aux import DWposeDetector
|
||||
from diffusers import StableDiffusionXLControlNetInpaintPipeline, ControlNetModel
|
||||
|
||||
- **정보 상태:** needs_review
|
||||
- **출처 신뢰도:** A
|
||||
- **검토 이유:** *(P-Reinforce Phase 1 자동 정규화. 본문 검증 필요.)*
|
||||
dwpose = DWposeDetector.from_pretrained("yzd-v/DWPose")
|
||||
hand_cn = ControlNetModel.from_pretrained("hr16/ControlNet-HandRefiner-pruned",
|
||||
torch_dtype=torch.float16)
|
||||
|
||||
## 🧬 중복 검사 (Duplicate Check)
|
||||
def fix_hands(img, prompt):
|
||||
pose = dwpose(img, hand_only=True) # depth-style hand map
|
||||
mask = hand_mask_from_dwpose(pose)
|
||||
pipe = StableDiffusionXLControlNetInpaintPipeline.from_pretrained(
|
||||
"stabilityai/stable-diffusion-xl-base-1.0",
|
||||
controlnet=hand_cn, torch_dtype=torch.float16
|
||||
).to("cuda")
|
||||
return pipe(prompt=prompt, image=img, mask_image=mask,
|
||||
control_image=pose, num_inference_steps=30,
|
||||
controlnet_conditioning_scale=0.9).images[0]
|
||||
```
|
||||
|
||||
- **기존 유사 문서:** *(TODO: 인덱서 클러스터 리포트 참조)*
|
||||
- **처리 방식:** UPDATE (자동 정규화)
|
||||
- **처리 이유:** Phase 1 정규화 — 옛 템플릿/누락 필드 보강.
|
||||
### Pattern 3 — ControlNet OpenPose lock
|
||||
```python
|
||||
from controlnet_aux import OpenposeDetector
|
||||
from diffusers import StableDiffusionXLControlNetPipeline
|
||||
|
||||
## ⚠️ 모순 및 업데이트 (Contradictions & Updates)
|
||||
op = OpenposeDetector.from_pretrained("lllyasviel/ControlNet")
|
||||
pose_map = op(reference_image, hand_and_face=True)
|
||||
|
||||
- **과거 데이터와의 충돌:** 없음
|
||||
- **정책 변화:** 없음
|
||||
cn = ControlNetModel.from_pretrained("xinsir/controlnet-openpose-sdxl-1.0",
|
||||
torch_dtype=torch.float16)
|
||||
pipe = StableDiffusionXLControlNetPipeline.from_pretrained(
|
||||
"stabilityai/stable-diffusion-xl-base-1.0",
|
||||
controlnet=cn, torch_dtype=torch.float16
|
||||
).to("cuda")
|
||||
out = pipe(prompt="cinematic shot of a woman dancing", image=pose_map,
|
||||
num_inference_steps=30, guidance_scale=6.5).images[0]
|
||||
```
|
||||
|
||||
## 🕓 변경 이력 (Changelog)
|
||||
### Pattern 4 — Multi-ControlNet (depth + canny + pose)
|
||||
```python
|
||||
from diffusers import MultiControlNetModel
|
||||
controlnets = MultiControlNetModel([
|
||||
ControlNetModel.from_pretrained("xinsir/controlnet-depth-sdxl-1.0", torch_dtype=torch.float16),
|
||||
ControlNetModel.from_pretrained("xinsir/controlnet-canny-sdxl-1.0", torch_dtype=torch.float16),
|
||||
ControlNetModel.from_pretrained("xinsir/controlnet-openpose-sdxl-1.0", torch_dtype=torch.float16),
|
||||
])
|
||||
result = pipe(prompt=p,
|
||||
image=[depth_map, canny_map, pose_map],
|
||||
controlnet_conditioning_scale=[0.6, 0.4, 0.9]).images[0]
|
||||
```
|
||||
|
||||
| 날짜 | 변경 내용 | 처리 방식 | 신뢰도 |
|
||||
|------|-----------|-----------|--------|
|
||||
| 2026-05-08 | P-Reinforce Phase 1 정규화 (frontmatter + 헤더 표준화) | UPDATE | A |
|
||||
### Pattern 5 — Differential diffusion (soft mask)
|
||||
```python
|
||||
# Soft strength per-pixel mask: 0.0 keep, 1.0 fully regen
|
||||
import numpy as np
|
||||
from PIL import Image
|
||||
|
||||
def soft_mask(face_box, img_size, edge_blur=24):
|
||||
m = np.zeros(img_size, dtype=np.float32)
|
||||
x1,y1,x2,y2 = face_box
|
||||
m[y1:y2, x1:x2] = 1.0
|
||||
from scipy.ndimage import gaussian_filter
|
||||
return Image.fromarray((gaussian_filter(m, edge_blur)*255).astype(np.uint8))
|
||||
|
||||
# Pass into pipe.diff_diffusion_strength=
|
||||
```
|
||||
|
||||
### Pattern 6 — Face restore (CodeFormer / GFPGAN)
|
||||
```python
|
||||
from codeformer import CodeFormer
|
||||
cf = CodeFormer(weight_path="codeformer.pth", device="cuda")
|
||||
restored = cf.enhance(img_np, w=0.7) # 0=keep id, 1=full repair
|
||||
```
|
||||
|
||||
### Pattern 7 — ComfyUI workflow JSON snippet
|
||||
```json
|
||||
{
|
||||
"1": {"class_type": "KSampler",
|
||||
"inputs": {"steps": 30, "cfg": 6.5, "sampler_name": "dpmpp_2m_sde",
|
||||
"scheduler": "karras", "model": ["4",0], "positive":["6",0],
|
||||
"negative":["7",0], "latent_image":["5",0]}},
|
||||
"20":{"class_type":"FaceDetailer",
|
||||
"inputs":{"image":["1",0],"model":["4",0],
|
||||
"bbox_detector":"face_yolov8m.pt",
|
||||
"wildcard":"perfect symmetric eyes, sharp focus",
|
||||
"guide_size":768,"max_size":1024,"steps":20}}
|
||||
}
|
||||
```
|
||||
|
||||
## 매 결정 기준
|
||||
| 상황 | Approach |
|
||||
|---|---|
|
||||
| Anime portrait, hand 결함 | A1111 + ADetailer (face_yolov8n + hand_yolov8n) |
|
||||
| Realistic full body | SDXL + Multi-ControlNet (pose+depth) |
|
||||
| Reproducible production | ComfyUI workflow JSON + Git |
|
||||
| Maximum quality, slow | FLUX.1 dev + Differential Diffusion |
|
||||
| Real-time iteration | SDXL Lightning / Turbo |
|
||||
|
||||
**기본값**: 매 SDXL base + ADetailer face/hand pass + 1 manual inpaint round.
|
||||
|
||||
## 🔗 Graph
|
||||
- 부모: [[AI 이미지 생성 (AI Image Generation)]] · [[Stable Diffusion]]
|
||||
- 변형: [[ControlNet]] · [[ADetailer]] · [[IP-Adapter]]
|
||||
- 응용: [[사후 편집 (Post-editing)]] · [[Character Consistency]]
|
||||
- Adjacent: [[FLUX]] · [[ComfyUI]] · [[DWPose]]
|
||||
|
||||
## 🤖 LLM 활용
|
||||
**언제**: 매 ComfyUI workflow JSON 의 authoring/debugging, 매 prompt + negative-prompt 의 systematic generation.
|
||||
**언제 X**: 매 fine pixel-level inpaint 결정 — 매 visual judgment 가 필요.
|
||||
|
||||
## ❌ 안티패턴
|
||||
- **Single-pass at full res**: 매 face/hand 의 detail starvation. 매 second-pass crop+upscale 의 mandatory.
|
||||
- **Wrong ControlNet 조합**: 매 pose + canny 동시에 high weight → 매 over-constrain → composition 의 collapse.
|
||||
- **Hand_refiner 없는 SDXL hand**: 매 5% 미만 의 success rate.
|
||||
- **ADetailer denoise 1.0**: 매 identity 의 destroyed. 매 0.4–0.6 의 sweet spot.
|
||||
|
||||
## 🧪 검증 / 중복
|
||||
- Verified (Mikubill/sd-webui-controlnet, Bing-su/adetailer; HuggingFace diffusers docs).
|
||||
- 신뢰도 A.
|
||||
|
||||
## 🕓 Changelog
|
||||
| 날짜 | 변경 |
|
||||
|---|---|
|
||||
| 2026-05-08 | Phase 1 |
|
||||
| 2026-05-10 | Manual cleanup — ADetailer + ControlNet hand_refiner pipeline |
|
||||
|
||||
Reference in New Issue
Block a user