迭代优化图像提示词
分析生成的图像,并系统地调整提示词。
迭代优化图像提示词 是 CoddyKit 上的免费 AI Prompt Engineering 课时。 这是第 4 节课,共 4 节。 你可以在下方免费阅读本课时的完整内容 — 然后在浏览器中使用内置代码编辑器和全天候 AI 导师进行实践。 这是 AI Prompt Engineering 学习路径的一部分,你的进度在网页和 CoddyKit 应用中同步。 AI Prompt Engineering 课程共包含 4 节课。
为什么要迭代优化
第一版图像提示词很少能准确生成您想要的结果。迭代优化是一套系统化流程:生成、分析、找出差距、调整提示词,然后重新生成。每一轮循环都会缩小意图与输出之间的差距。
优化循环
迭代优化循环包含四个步骤:生成(根据当前提示词创建图像)、分析(找出错误或缺失之处)、调整(修改提示词以解决问题)以及重新生成。重复这些步骤,直到您满意,或达到预算、时间等限制。
class PromptRefinementSession:
def __init__(self, initial_prompt, negative_prompt=''):
self.history = []
self.current_prompt = initial_prompt
self.current_negative = negative_prompt
self.iteration = 0
def record_iteration(self, issues_found, adjustments_made):
self.history.append({
'iteration': self.iteration,
'prompt': self.current_prompt,
'negative': self.current_negative,
'issues': issues_found,
'adjustments': adjustments_made
})
self.iteration += 1
def update_prompt(self, new_prompt, new_negative=None):
self.current_prompt = new_prompt
if new_negative is not None:
self.current_negative = new_negative
def get_history(self):
return self.history
# Usage
session = PromptRefinementSession(
initial_prompt='a woman walking in a rainy city at night',
negative_prompt='blurry, low quality'
)
print('Refinement session started. Iteration 0.')分析生成图像:问题分类
分析出错原因时,请按类型对问题进行分类。这样可以明确提示词的哪一部分需要调整——增加细节、消除冲突或调整权重。
ISSUE_TAXONOMY = {
'Subject issues': [
'Subject missing or wrong species/gender/age',
'Key detail absent (clothing, expression, props)',
'Pose or action incorrect',
'Background wrong or distracting'
],
'Style issues': [
'Wrong art style (photo when painting expected)',
'Too stylized/not stylized enough',
'Style inconsistency (mixing styles incoherently)'
],
'Lighting issues': [
'Wrong time of day',
'Too dark or too bright',
'Shadows wrong direction',
'Missing dramatic effect'
],
'Composition issues': [
'Wrong framing (too close/far)',
'Subject cropped awkwardly',
'Rule of thirds not applied',
'Cluttered vs. desired clean composition'
],
'Quality issues': [
'Blurry or low detail',
'Anatomical distortion (extra fingers)',
'Watermark or text artifact',
'Overexposed/underexposed areas'
]
}
for category, issues in ISSUE_TAXONOMY.items():
print(f'{category}: {issues[0]}')第 1 轮迭代:修改前后对比
下面是一个具体的修改前后示例,展示如何通过识别问题并调整提示词来改善结果。
# ITERATION 0: Initial prompt (too vague)
prompt_v0 = 'a woman walking in a rainy city at night'
# Issues found:
# - Style unspecified -> model defaulted to generic illustration
# - Lighting unspecified -> flat even light, no mood
# - No detail on clothing or setting
# - No composition direction
# ITERATION 1: Add style, lighting, detail
prompt_v1 = (
'a young woman in a yellow raincoat walking down '
'a rain-soaked Tokyo street at night, '
'neon signs reflected in puddles, steam rising from grates, '
'cinematic photography style, street photography, '
'warm neon glow, wet pavement reflections, '
'medium shot, slightly low angle, bokeh background'
)
negative_v1 = 'blurry, low quality, watermark, extra fingers, cartoon'
# Remaining issues after v1:
# - Raincoat not yellow (model defaulted to dark colors)
# - Woman facing wrong way
print('V0 length:', len(prompt_v0.split()))
print('V1 length:', len(prompt_v1.split()))
print('Iteration adds: style, lighting, composition, specific details')第 2 轮迭代:修复具体元素
第二轮迭代会精确处理剩余问题——不要重写整个提示词,只需解决第 1 轮迭代中发现的具体问题。
# ITERATION 1 issues:
# - Raincoat not yellow (model defaulted to dark)
# - Woman facing wrong way (walking away from camera)
# ITERATION 2: targeted fixes
prompt_v2 = (
'a young woman in a BRIGHT YELLOW raincoat '
'walking TOWARD the camera '
'down a rain-soaked Tokyo street at night, '
'neon signs reflected in puddles, steam rising from grates, '
'face visible, slight smile, carrying groceries, '
'cinematic photography style, street photography, '
'warm neon glow, wet pavement reflections, '
'medium shot, slightly low angle, bokeh background'
)
# Changes made:
# 1. "BRIGHT YELLOW" capitalization + adjective for emphasis
# 2. Added "walking TOWARD the camera" to fix direction
# 3. Added "face visible" to prevent back-to-camera result
# 4. Added specific detail: "carrying groceries, slight smile"
# Best practice: track what you changed and why
changelog = {
'v0_to_v1': 'Added style, lighting, composition, city details',
'v1_to_v2': 'Fixed raincoat color, fixed walking direction, added face constraint'
}
print('Changelog:', changelog)使用固定种子进行比较
比较提示词变体时,请使用固定的随机种子,使唯一的变量是提示词的变化。如果没有固定种子,您无法判断输出变化究竟来自提示词修改,还是来自随机性。
import requests
SD_API_URL = 'http://localhost:7860/sdapi/v1/txt2img'
def compare_prompt_versions(prompts_dict, negative='blurry, low quality',
seed=12345, steps=30):
results = {}
for version, prompt in prompts_dict.items():
payload = {
'prompt': prompt,
'negative_prompt': negative,
'seed': seed, # FIXED SEED for fair comparison
'steps': steps,
'cfg_scale': 7,
'width': 512,
'height': 512
}
response = requests.post(SD_API_URL, json=payload)
results[version] = response.json().get('images', [None])[0]
print(f'{version}: generated with seed {seed}')
return results
promptvariants = {
'v0': 'a woman walking in a rainy city at night',
'v1': 'cinematic, rainy Tokyo night, yellow raincoat, neon reflections',
'v2': 'BRIGHT YELLOW raincoat, facing camera, cinematic Tokyo rain night'
}
# compare_prompt_versions(prompt_variants, seed=42)减法式方法
经过多轮迭代后,提示词有时会变得过于臃肿。减法式方法从详细的提示词开始,逐个删除术语,以观察哪些术语确实发挥了作用,哪些只是在增加噪声。
# Start with a detailed prompt
full_prompt = (
'young woman, yellow raincoat, Tokyo, rain, neon, night, '
'street photography, cinematic, bokeh, wet pavement, '
'medium shot, warm tones, highly detailed, 8K, masterpiece, '
'award winning, beautiful, stunning, gorgeous'
)
# Remove terms and test if output quality degrades
test_removed = [
'masterpiece, award winning, beautiful, stunning, gorgeous', # quality tokens
'8K, highly detailed', # resolution tokens
'wet pavement', # specific detail
'cinematic', # style term
]
# Results typically show:
# - Generic quality tokens (masterpiece, beautiful) have minimal effect
# - Specific scene details (wet pavement, neon) matter most
# - Remove token: if output unchanged, that term is not contributing
print('Subtractive testing: remove terms and observe impact')
print('Terms that do not change output when removed can be discarded')
print('This produces lean, effective prompts')针对特定失败模式进行优化
常见的图像生成失败模式都有已知的解决方法。将这些知识整理成系统化检查清单,可以加快优化过程。
FAILURE_FIXES = {
'Extra or deformed fingers': [
'Add to negative: extra fingers, deformed hands, bad anatomy',
'Add to positive: perfect hands, anatomically correct',
'Use inpainting to fix the specific area'
],
'Text artifacts / watermarks': [
'Add to negative: watermark, text, signature, logo',
'Increase CFG scale slightly',
'Use a different model checkpoint'
],
'Wrong style (cartoonish when photo expected)': [
'Add to negative: cartoon, anime, illustration, painted',
'Add to positive: photorealistic, DSLR, film photography',
'Use a photorealism-focused checkpoint'
],
'Background too busy / distracting': [
'Add to positive: simple background, clean background, blurred background',
'Add: shallow depth of field, bokeh background',
'Add to negative: cluttered background, busy background'
],
'Wrong color (model ignores color spec)': [
'Emphasize color: BRIGHT RED (caps), crimson red, deep scarlet',
'Add color to multiple places in prompt',
'Use img2img with a color reference image'
]
}
for failure, fixes in list(FAILURE_FIXES.items())[:3]:
print(f'\nISSUE: {failure}')
for fix in fixes:
print(f' FIX: {fix}')图像生成的提示词版本管理
请系统地记录提示词版本及其输出结果。这样可以为未来的项目建立参考库,并发现针对特定主题和风格时哪些方法有效。
import json
from datetime import datetime
from pathlib import Path
def save_refinement_session(session_name, iterations, output_dir='prompt_sessions'):
Path(output_dir).mkdir(exist_ok=True)
session_data = {
'name': session_name,
'created': datetime.now().isoformat(),
'iterations': iterations
}
filepath = f'{output_dir}/{session_name}.json'
with open(filepath, 'w') as f:
json.dump(session_data, f, indent=2)
print(f'Session saved: {filepath}')
# Example session record
session = [
{
'version': 'v0',
'prompt': 'a woman walking in a rainy city at night',
'issues': ['too vague', 'no style', 'no lighting'],
'seed': 12345
},
{
'version': 'v1',
'prompt': 'young woman, yellow raincoat, Tokyo night rain, neon, cinematic',
'issues': ['raincoat not yellow', 'facing wrong way'],
'seed': 12345
},
{
'version': 'v2',
'prompt': 'BRIGHT YELLOW raincoat, facing camera, Tokyo rain, neon, cinematic',
'issues': [],
'seed': 12345,
'status': 'accepted'
}
]
save_refinement_session('tokyo_rain_woman', session)优化预算:需要迭代多少轮
优化会产生递减的收益。下面是一套实用框架,帮助您根据使用场景决定投入多少轮迭代:
ITERATION_BUDGET_GUIDE = {
'Quick internal mockup': {
'budget': '2-3 iterations',
'goal': 'Good enough to communicate concept',
'stopping_criteria': 'Main subject correct, rough style established'
},
'Marketing asset': {
'budget': '4-6 iterations',
'goal': 'Professional quality, brand-consistent',
'stopping_criteria': 'Color, style, composition match brief exactly'
},
'Hero image / campaign visual': {
'budget': '8-12 iterations + final manual touchup',
'goal': 'Publication quality, no visible artifacts',
'stopping_criteria': 'Zero artifacts, passes creative director review'
},
'Generative art piece': {
'budget': 'Unlimited — creative exploration',
'goal': 'Discover unexpected aesthetic direction',
'stopping_criteria': 'Emotional resonance with creator\'s intent'
}
}
for use_case, guide in ITERATION_BUDGET_GUIDE.items():
print(f'{use_case}: {guide["budget"]}')
print(f' Stop when: {guide["stopping_criteria"]}')
print()借助大语言模型进行提示词优化
使用文本大语言模型帮助分析图像问题并提出提示词改进建议。这样可以将大语言模型的推理能力与图像生成结合起来,形成元优化循环。
import anthropic
client = anthropic.Anthropic(api_key='YOUR_API_KEY')
REFINEMENT_ADVISOR_PROMPT = '''I am generating an image with this prompt:
Current prompt: {current_prompt}
Negative prompt: {current_negative}
The image has these problems:
{issues}
Suggest specific changes to the prompt that would fix these problems.
Provide:
1. Modified positive prompt (full, ready to use)
2. Modified negative prompt (full, ready to use)
3. Explanation of each change
Keep your changes minimal — only fix the stated issues, do not redesign the image.'''
def get_refinement_suggestion(current_prompt, current_negative, issues):
response = client.messages.create(
model='claude-opus-4-5', max_tokens=1000,
messages=[{'role': 'user', 'content':
REFINEMENT_ADVISOR_PROMPT.format(
current_prompt=current_prompt,
current_negative=current_negative,
issues='\n'.join(f'- {i}' for i in issues)
)}]
)
return response.content[0].text
suggestion = get_refinement_suggestion(
current_prompt='a woman in a raincoat at night',
current_negative='blurry',
issues=['raincoat appears dark not yellow', 'background too busy']
)
print(suggestion[:300], '...')快速检查
您想比较图像提示词的两个版本,以确认修改是否改善了结果。进行公平比较时,必须保持哪些条件不变?
迭代优化总结
迭代式图像提示词优化是一项系统且可以学习的技能:
- 循环:生成 → 分析 → 调整 → 重新生成
- 问题分类:将问题归类为主体、风格、光照、构图或质量问题
- 固定种子:始终使用相同的种子比较提示词版本
- 针对性修改:修复已识别的具体问题,不要重写整个提示词
- 减法式方法:删除术语,以确认哪些术语真正发挥了作用
- 版本跟踪:记录每轮迭代使用的提示词、问题和修改内容
- 预算意识:模型图迭代 2~3 轮,主视觉素材迭代 8~12 轮
用 AI 导师学习 AI Prompt Engineering — 免费
在浏览器中编写并运行真实代码,获得全天候 AI 导师的即时帮助,并在网页或应用中继续学习。
- 课程
- 53
- 课程
- 199
常见问题解答
「迭代优化图像提示词」课时是免费的吗?
是的 — 「迭代优化图像提示词」的完整文本可在网页上免费阅读。要进行交互式练习(内置代码编辑器和全天候 AI 导师)并解锁 AI Prompt Engineering 课程的其余内容,请升级到 CoddyKit PRO。 AI Prompt Engineering 课程共包含 4 节课。
「迭代优化图像提示词」这节课中我会学到什么?
分析生成的图像,并系统地调整提示词。 你通过在浏览器中直接运行的动手代码来练习 AI Prompt Engineering,全天候 AI 导师会在你学习这节课的过程中回答你的问题。
学习 AI Prompt Engineering 需要有经验吗?
无需任何先前经验。CoddyKit 上的 AI Prompt Engineering 课程适合初学者到高级学习者,你可以从这里开始或从头开始,按照自己的节奏学习。 这是第 4 节课,共 4 节。
「迭代优化图像提示词」课时需要多长时间?
大多数 CoddyKit 课程大约需要 5–10 分钟。每节课都很精短且互动,所以你能稳步进步,并在网页和应用中从离开的地方继续。
我能在这节 AI Prompt Engineering 课中编写并运行代码吗?
能。每节 AI Prompt Engineering 课都包含内置代码编辑器,你可以在浏览器中直接编写并运行真实代码,并获得即时 AI 反馈 — 无需本地设置。
此课程中的所有课时
- 图像生成提示词的构成
- 风格与艺术媒介规范
- 负面提示词与排除项
- 迭代优化图像提示词