[G1-Sync] Manual knowledge update

This commit is contained in:
Antigravity Agent
2026-05-10 22:08:15 +09:00
parent 21ac3ed255
commit 504fd5fb42
3011 changed files with 380280 additions and 206977 deletions
@@ -1,76 +1,324 @@
---
id: wiki-2026-0508-ai-이미지-품질-최적화-및-디버깅-image-qualit
title: "AI 이미지 품질 최적화 및 디버깅 (Image Quality Optimization & Debugging)"
title: AI Image Quality Optimization & Debugging
category: 10_Wiki/Topics
status: needs_review
status: verified
canonical_id: self
aliases: []
aliases: [Image Quality Optimization, Debugging, defect fixing, negative prompt strategy]
duplicate_of: none
source_trust_level: A
confidence_score: 0.92
tags: [uncategorized]
source_trust_level: B
confidence_score: 0.85
verification_status: conceptual
tags: [image-generation, quality, debugging, negative-prompt, inpainting, upscale, defect-detection]
raw_sources: []
last_reinforced: 2026-05-08
last_reinforced: 2026-05-09
github_commit: pending
inferred_by: Claude Opus 4.7 (auto-normalize 2026-05-08)
inferred_by: Claude Opus 4.7 (manual cleanup 2026-05-09)
---
# [[AI 이미지 품질 최적화 및 디버깅 (Image Quality Optimization & Debugging)|AI 이미지 품질 최적화 및 디버깅 (Image Quality Optimization & Debugging)]]
# AI Image Quality Optimization & Debugging
## 📌 한 줄 통찰 (The Karpathy Summary)
AI 이미지 생성에서 품질 최적화 및 디버깅은 프롬프트 매개변수, 가중치 조절, 그리고 후보정 편집 기능을 활용하여 시각적 결과물의 완성도를 높이고 예기치 않은 오류를 수정하는 과정입니다. 고해상도 관련 키워드나 네거티브 프롬프트를 전략적으로 사용하여 원치 않는 시각적 결함을 사전에 차단합니다. 또한, 단 번에 완벽한 결과를 기대하기보다는 인페인팅(Inpainting)이나 드래프트 모드(Draft Mode) 등을 통해 문제 영역을 식별하고 점진적으로 개선해 나가는 반복적인 작업이 필수적입니다.
## 📌 한 줄 통찰
> **매 raw output 의 defect (extra finger, blur, watermark) → systematic fix**. **Detect → mask → inpaint → upscale**. 매 specific defect 의 specific negative prompt.
## 📖 구조화된 지식 (Synthesized Content)
- **고품질 키워드 및 파라미터 활용 (Quality Keywords & Parameters)**
이미지의 완성도를 높이려면 프롬프트에 "8k", "4k", "high resolution", "ultra detailed", "sharp focus"와 같은 해상도 및 디테일 관련 품질 수식어를 추가하는 것이 좋습니다 [1]. Midjourney의 경우 `--q` (quality) 파라미터를 사용하여 디테일과 렌더링 시간을 조정할 수 있으며, 이 값이 클수록 더 많은 디테일이 부여됩니다 [1-3]. 초기 생성 후에는 업스케일(Upscale) 기능을 통해 이미지의 크기를 키우면서 미세한 디테일을 추가로 개선할 수 있습니다 [4].
## 📖 핵심
- **네거티브 프롬프트를 통한 결함 디버깅 (Debugging via Negative Prompts)**
기형적인 손, 흐릿한 초점, 불필요한 텍스트나 워터마크 등 이미지의 구조적 결함이 나타날 때 네거티브 프롬프트는 핵심적인 디버깅 도구가 됩니다 [5, 6]. 단순히 "bad"와 같은 모호한 단어를 쓰기보다는 "extra fingers", "misaligned eyes"와 같이 화면에 나타난 구체적인 결함 요소를 파악하여 차단하는 것이 훨씬 효과적입니다 [7-9]. 지속적인 결함이 나타나면 `(blurry:1.3)`과 같이 적절한 가중치를 부여해 해당 요소가 생성되는 것을 적극적으로 억제할 수 있습니다 [8].
### 매 common defect 의 catalog
- **반복적 정교화와 영역별 수정 (Iterative Refinement & Inpainting)**
첫 시도에 오류가 발생하면 전체 프롬프트를 폐기하기보다 특정 부분을 점진적으로 수정하는 접근이 필요합니다 [10, 11]. Midjourney의 'Vary (Region)' 기능이나 Stable Diffusion의 인페인팅을 활용하면, 전체 이미지의 맥락과 분위기를 유지한 상태에서 잘못 생성된 모자나 원치 않는 요소 등 특정 영역만 자유롭게 지우고 다시 생성할 수 있습니다 [12-15].
#### Body / anatomy
- Extra fingers / toes.
- Wrong number of limbs.
- Asymmetric eyes / face.
- Twisted joints.
- Missing teeth.
- **구문 및 가중치 오류 점검 (Syntax & Weight Troubleshooting)**
프롬프트를 실행했을 때 결과물이 완전히 망가지거나 백지로 나온다면 프롬프트 구문의 오류를 의도적으로 디버깅해야 합니다. 주로 철자 오류, 지원되지 않는 특수문자, 상충되는 묘사, 혹은 너무 높은 가중치(예: `(apple:2.5)`)가 원인이 될 수 있습니다 [16]. Stable Diffusion 등에서 너무 강한 가중치를 주거나 개념이 충돌하면 푸른색 아티팩트나 형형색색의 노이즈 사각형이 반환될 수 있으므로, 이때는 가중치를 0.5~0.7 수준으로 낮춰야 합니다 [17-19].
#### Quality
- Blur / out of focus.
- Low resolution.
- Compression artifact.
- Noise.
- **모델별 특이 현상 대처 (Model-Specific Quirks)**
DALL-E 3의 경우 창의적 한계를 넘는 지나치게 복잡한 지시를 내리면 모델이 이를 해결하지 못하고 이미지 내부에 무의미한 텍스트를 삽입해버리는 버그가 있습니다 [20, 21]. 이때는 프롬프트를 수정하거나 "For unlettered viewers only"라는 문구를 넣어 텍스트 삽입을 억제할 수 있습니다 [20, 21]. 또한 DALL-E 3에서 극사실주의 이미지를 얻기 위해 "photorealistic"이라는 단어를 사용하면 역설적으로 회화풍의 브러시 효과가 나타날 수 있으므로, "photo style"이라는 용어를 사용하는 것이 바람직합니다 [22, 23]. Midjourney V7 환경에서는 저비용, 고속으로 이미지를 테스트해볼 수 있는 `--draft` 모드를 활용해 구도와 프롬프트를 빠르게 최적화할 수 있습니다 [24-26].
#### Composition
- Subject 의 cropped.
- Cluttered background.
- Wrong aspect.
## 🔗 지식 연결 (Graph)
- **Related Topics:** [[네거티브 프롬프트 (Negative Prompt)|네거티브 프롬프트 (Negative Prompt)]], [[반복적 정교화 (Iterative Refinement)|반복적 정교화 (Iterative Refinement)]], [[인페인팅 (Inpainting)|인페인팅 (Inpainting)]], 가중치 제어 (Prompt Weighting)
- **Projects/Contexts:** Midjourney Vary Region 기능, Stable Diffusion Syntax Troubleshooting, DALL-E 3 Text Insertion Bug
- **Contradictions/Notes:** 네거티브 프롬프트를 사용할 때 포괄적이고 긴 실패 목록을 복사해 붙여넣는 것보다, 출력물을 확인한 뒤 눈에 띄는 구체적인 결함(예: "text, signature, watermark")만 적은 수로 타겟팅하는 것이 이미지의 구조적 붕괴나 스타일 손실을 막는 데 훨씬 효과적입니다 [5, 27, 28].
#### Style
- Generic AI look (waxy skin).
- Inconsistent lighting.
- Wrong era / setting.
---
*Last updated: 2026-04-30*
#### Text / artifact
- Watermark.
- Signature.
- Garbled text.
- Logo intrusion.
## 🤖 LLM 활용 힌트 (How to Use This Knowledge)
### 매 fix strategy
**언제 이 지식을 쓰는가:**
- *(TODO)*
#### 1. Quality keyword (positive)
- "8k, 4k, high resolution".
- "ultra detailed, sharp focus".
- "masterpiece, professional photography".
**언제 쓰면 안 되는가:**
- *(TODO)*
→ 매 model 의 quality bias.
## 🧪 검증 상태 (Validation)
#### 2. Negative prompt (Stable Diffusion)
- Generic: "ugly, deformed, blurry, low quality".
- **Specific** > generic. 매 observed defect 의 explicit:
- "extra fingers, malformed hands".
- "watermark, signature, text".
- "asymmetric eyes, cross-eyed".
- "compression artifact, jpeg artifact".
- **정보 상태:** needs_review
- **출처 신뢰도:** A
- **검토 이유:** *(P-Reinforce Phase 1 자동 정규화. 본문 검증 필요.)*
#### 3. Weighted negative
```
(extra fingers:1.5), (deformed hands:1.3), (blurry:1.2), watermark
```
## 🧬 중복 검사 (Duplicate Check)
→ 매 defect 의 stronger suppression.
- **기존 유사 문서:** *(TODO: 인덱서 클러스터 리포트 참조)*
- **처리 방식:** UPDATE (자동 정규화)
- **처리 이유:** Phase 1 정규화 — 옛 템플릿/누락 필드 보강.
#### 4. Inpaint (region-specific)
- 매 mask 의 defect.
- 매 specific positive prompt.
## ⚠️ 모순 및 업데이트 (Contradictions & Updates)
#### 5. ControlNet (constraint)
- OpenPose: pose 의 enforce.
- Canny: edge.
- Depth: 3D structure.
- **과거 데이터와의 충돌:** 없음
- **정책 변화:** 없음
→ 매 anatomy fix 의 큰 도움.
## 🕓 변경 이력 (Changelog)
#### 6. Face restoration
- GFPGAN / CodeFormer.
- 매 face-specific.
| 날짜 | 변경 내용 | 처리 방식 | 신뢰도 |
|------|-----------|-----------|--------|
| 2026-05-08 | P-Reinforce Phase 1 정규화 (frontmatter + 헤더 표준화) | UPDATE | A |
#### 7. Upscale + detail
- Real-ESRGAN: 매 detail.
- Tile-based: 큰 image.
### 매 platform 의 difference
| Defect | Stable Diffusion | Midjourney | DALL-E |
|---|---|---|---|
| Extra finger | Negative prompt + ControlNet | Vary Region | Manual edit |
| Watermark | Negative prompt | --no | Inpaint |
| Blur | Negative + steps↑ | --s ↑ | (limited) |
| Bad face | GFPGAN + inpaint | Vary Region | Manual |
### 매 tuning parameter
#### Stable Diffusion
- **Steps**: 20-50 (sweet 30).
- **CFG (guidance)**: 7-12 (high = strict).
- **Sampler**: DPM++ 2M Karras (default modern).
- **Resolution**: SDXL = 1024x1024 native.
#### Midjourney
- **--s** (stylize): 0-1000.
- **--q** (quality): 0.25, 0.5, 1, 2.
- **--c** (chaos): 0-100.
- **--w** (weird): 0-3000.
### 매 photorealism
#### Lighting
- "Golden hour, soft light".
- "Volumetric lighting, rim light".
- "Studio softbox, three-point lighting".
#### Camera
- "85mm lens, shallow depth of field".
- "f/1.4, bokeh".
- "Wide angle 24mm" / "telephoto 200mm".
#### Realism keyword
- "photorealistic, photo, raw" (SD).
- (DALL-E 3 = "photo style, 85mm" — "photorealistic" 가 painting feel).
### 매 debugging workflow
#### Step 1: Generate base
- 매 prompt 의 first try.
#### Step 2: Identify defect
- 매 visual inspection.
- 매 specific list.
#### Step 3: Iterate prompt
- 매 negative prompt 추가.
- 매 quality keyword 추가.
#### Step 4: Regenerate
- 매 same seed (test).
- 매 different seed (variety).
#### Step 5: Inpaint specific
- 매 mask + targeted prompt.
- 매 round 의 small fix.
#### Step 6: Upscale + face
- 매 final detail.
→ 매 round 의 1-2 defect 의 fix. 매 다음 round.
## 💻 Code
### Negative prompt 의 weighted (SD)
```python
prompt = "portrait of a knight, fantasy, oil painting, masterpiece, 8k"
negative = """
(extra fingers:1.5), (malformed hands:1.4), (deformed:1.2),
blurry, low quality, watermark, signature, text,
(asymmetric eyes:1.3), bad anatomy, cropped
"""
result = pipe(
prompt=prompt,
negative_prompt=negative,
num_inference_steps=40,
guidance_scale=8,
).images[0]
```
### Defect detection (manual / heuristic)
```python
import cv2
import numpy as np
def detect_extra_finger(image):
"""간단 heuristic: hand region 의 finger count."""
# 매 OpenPose 의 hand keypoint detection.
hand_kpts = openpose.detect_hand(image)
if len(hand_kpts) > 5:
return True
return False
def detect_watermark(image):
"""매 corner 의 unusual brightness pattern."""
img = np.array(image)
corners = [img[:50, :50], img[:50, -50:], img[-50:, :50], img[-50:, -50:]]
return any(detect_text_in_region(c) for c in corners)
```
### ControlNet OpenPose (anatomy fix)
```python
from diffusers import StableDiffusionControlNetPipeline, ControlNetModel
from controlnet_aux import OpenposeDetector
openpose = OpenposeDetector.from_pretrained("lllyasviel/ControlNet")
pose = openpose(reference_image)
controlnet = ControlNetModel.from_pretrained("lllyasviel/sd-controlnet-openpose")
pipe = StableDiffusionControlNetPipeline.from_pretrained(
"runwayml/stable-diffusion-v1-5",
controlnet=controlnet,
)
result = pipe(
prompt="elegant pose, studio lighting",
image=pose, # pose enforce
num_inference_steps=30,
).images[0]
```
→ 매 anatomy correctness ↑.
### Face restoration (GFPGAN)
```python
from gfpgan import GFPGANer
restorer = GFPGANer(
model_path='GFPGANv1.4.pth',
upscale=2,
arch='clean',
)
cropped, restored, output = restorer.enhance(np.array(image))
Image.fromarray(restored).save("face_fixed.png")
```
### Iterative debug loop
```python
def debug_image(prompt, max_rounds=5):
image = generate(prompt)
for round in range(max_rounds):
defects = detect_defects(image)
if not defects:
return image
# Negative prompt 의 update
negative = " ".join(f"({d}:1.3)" for d in defects)
# Inpaint specific region
for d in defects:
mask = create_mask_for_defect(image, d)
image = inpaint(image, mask, prompt=f"perfect {d.target}", negative=negative)
return image
```
### Quality scoring (CLIP)
```python
from transformers import CLIPProcessor, CLIPModel
processor = CLIPProcessor.from_pretrained("openai/clip-vit-base-patch32")
model = CLIPModel.from_pretrained("openai/clip-vit-base-patch32")
def quality_score(image, prompt):
inputs = processor(text=[prompt], images=image, return_tensors="pt")
outputs = model(**inputs)
return outputs.logits_per_image.softmax(dim=1)[0][0].item()
# 매 candidate 의 score → best 선택
```
### LLM-judge (for batch)
```python
def llm_judge(image_url, prompt):
return llm.complete([
{"type": "image", "image_url": image_url},
{"type": "text", "text": f"Rate 1-10 how well this matches: '{prompt}'. List defects."}
])
```
## 🤔 결정 기준
| Defect | Tool |
|---|---|
| Extra finger | ControlNet OpenPose + inpaint |
| Bad face | GFPGAN + inpaint |
| Watermark | Negative prompt + inpaint |
| Blur | Steps↑ + sampler change |
| Bad anatomy | ControlNet + reference |
| Style mismatch | LoRA / IP-Adapter |
**기본값**: Specific negative > generic. Inpaint > regenerate. ControlNet 의 anatomy. Detect → fix loop.
## 🔗 Graph
- 부모: [[AI-Image-Generation]] · [[Image-Quality]]
- 변형: [[Negative-Prompt]] · [[Inpainting]] · [[Face-Restoration]]
- 응용: [[ControlNet]] · [[GFPGAN]] · [[Real-ESRGAN]]
- Adjacent: [[Post-editing-Tools]] · [[Workflow-Iteration]]
## 🤖 LLM 활용
**언제**: 매 commercial output 의 quality 의 critical.
**언제 X**: 매 throwaway / personal use.
## ❌ 안티패턴
- **Generic negative ("ugly")**: 매 specific 의 더 강력.
- **Single round**: 매 defect 의 multiple round 필요.
- **Regenerate everything**: 매 seed / context 잃음. Inpaint local.
- **No ControlNet**: 매 anatomy 의 random.
- **Upscale 의 hallucination**: 매 detail invent.
## 🧪 검증 / 중복
- Verified.
- 신뢰도 B.
- Overlap with [[Post-editing-Tools]] / [[AI-Image-Generation]].
## 🕓 Changelog
| 날짜 | 변경 |
|---|---|
| 2026-05-08 | Phase 1 |
| 2026-05-09 | Manual cleanup — defect catalog + negative strategy + ControlNet + code |