LiuJuan Z-Image Generator代码实例:批量生成不同分辨率人像的脚本示例

LiuJuan Z-Image Generator代码实例:批量生成不同分辨率人像的脚本示例 LiuJuan Z-Image Generator代码实例批量生成不同分辨率人像的脚本示例1. 引言从单张生成到批量创作的跨越如果你已经体验过LiuJuan Z-Image Generator的Web界面用它生成过几张惊艳的人像那么接下来可能会遇到一个很实际的需求如何一次性生成多张不同尺寸的图片想象一下这些场景你需要为同一个角色生成一套社交媒体头像包括正方形、横幅、竖版等多种尺寸电商产品需要不同分辨率的展示图用于网站、App和宣传物料游戏角色设计需要测试在不同画布比例下的视觉效果手动在界面上一次次调整参数、点击生成不仅效率低下还容易出错。今天我就带你深入LiuJuan Z-Image Generator的代码层编写一个批量生成不同分辨率人像的Python脚本让你真正掌握这个工具的核心能力。2. 理解脚本化的核心价值2.1 为什么需要脚本化生成在开始写代码之前我们先明确脚本化带来的几个核心优势效率提升一次配置批量生成无需重复操作界面支持夜间无人值守运行充分利用计算资源减少人为操作错误确保生成参数的一致性灵活定制自由组合提示词、分辨率、采样参数实现复杂的生成逻辑如参数扫描、A/B测试轻松集成到自动化工作流中专业需求满足满足特定行业的标准分辨率要求为不同平台移动端、PC端、印刷生成适配图片进行系统的风格测试和质量评估2.2 脚本与Web界面的关系很多人会问既然有Web界面为什么还要写脚本其实它们是互补关系使用场景Web界面优势脚本优势探索测试实时调整即时预览批量执行参数系统化单次生成操作直观无需代码重复任务自动化处理交互体验可视化反馈用户友好后台运行资源专注复杂流程步骤清晰适合新手逻辑灵活适合专家我们的脚本不是要替代Web界面而是扩展它的能力边界让你在需要的时候能够更高效地工作。3. 环境准备与核心代码解析3.1 确保环境就绪在开始编写脚本之前确保你的环境已经正确配置# 检查关键依赖 python -c import torch; print(fPyTorch版本: {torch.__version__}) python -c import torch; print(fCUDA可用: {torch.cuda.is_available()}) python -c import torch; print(f当前设备: {torch.cuda.get_device_name(0) if torch.cuda.is_available() else \CPU\}) # 检查BF16支持对LiuJuan Z-Image很重要 python -c import torch; print(fBF16支持: {torch.cuda.is_bf16_supported()})如果BF16不支持你可能需要调整脚本中的精度设置或者考虑升级驱动和CUDA版本。3.2 核心生成函数解析让我们先看看LiuJuan Z-Image Generator的核心生成逻辑。虽然完整的代码库比较复杂但我们可以提取出最关键的部分import torch from diffusers import StableDiffusionPipeline import safetensors.torch class LiuJuanImageGenerator: def __init__(self, model_pathpath/to/liujuan/z-image, weight_pathpath/to/liujuan/weights.safetensors): 初始化LiuJuan Z-Image生成器 参数说明 - model_path: Z-Image基础模型路径 - weight_path: LiuJuan自定义权重文件路径 # 1. 设置BF16精度关键优化 self.dtype torch.bfloat16 if torch.cuda.is_bf16_supported() else torch.float16 # 2. 加载基础模型 print(正在加载Z-Image基础模型...) self.pipe StableDiffusionPipeline.from_pretrained( model_path, torch_dtypeself.dtype, safety_checkerNone, # 禁用安全检查器以提升速度 requires_safety_checkerFalse ) # 3. 加载并注入LiuJuan自定义权重 print(正在加载LiuJuan自定义权重...) self._load_custom_weights(weight_path) # 4. 应用显存优化 self._apply_memory_optimizations() # 5. 移动到GPU self.pipe.to(cuda) print(模型加载完成准备生成图片) def _load_custom_weights(self, weight_path): 智能加载并清洗自定义权重 # 加载safetensors文件 custom_weights safetensors.torch.load_file(weight_path) # 权重键名清洗关键步骤 cleaned_weights {} for key, value in custom_weights.items(): # 移除常见的前缀确保与基础模型匹配 cleaned_key key.replace(transformer., ).replace(model., ) cleaned_weights[cleaned_key] value # 宽松模式加载权重 missing_keys, unexpected_keys self.pipe.unet.load_state_dict( cleaned_weights, strictFalse ) if missing_keys: print(f警告有{len(missing_keys)}个键未匹配使用基础模型参数) if unexpected_keys: print(f注意有{len(unexpected_keys)}个额外键被忽略) def _apply_memory_optimizations(self): 应用显存优化策略 # 设置显存碎片治理 if hasattr(torch.cuda, empty_cache): torch.cuda.empty_cache() # 配置max_split_size_mb减少碎片 torch.cuda.set_per_process_memory_fraction(0.9) # 保留10%显存余量 torch.backends.cuda.max_split_size_mb 128 # 关键参数 # 启用CPU卸载显存紧张时特别有用 self.pipe.enable_model_cpu_offload() def generate_image(self, prompt, negative_prompt, height512, width512, steps12, guidance_scale2.0): 生成单张图片 参数说明 - prompt: 正面提示词 - negative_prompt: 负面提示词 - height: 图片高度 - width: 图片宽度 - steps: 采样步数Z-Image推荐10-15 - guidance_scale: 引导系数Z-Image推荐2.0 # 设置随机种子确保可重复性 generator torch.Generator(devicecuda).manual_seed(42) # 生成图片 image self.pipe( promptprompt, negative_promptnegative_prompt, heightheight, widthwidth, num_inference_stepssteps, guidance_scaleguidance_scale, generatorgenerator ).images[0] return image这个类封装了LiuJuan Z-Image Generator的核心功能特别是BF16精度优化确保在支持BF16的显卡上获得最佳性能权重智能清洗自动处理LiuJuan权重与基础模型的兼容性问题显存优化通过碎片治理和CPU卸载降低显存压力4. 批量生成脚本实战现在让我们基于上面的核心类编写完整的批量生成脚本。4.1 完整批量生成脚本#!/usr/bin/env python3 LiuJuan Z-Image批量生成脚本 功能批量生成不同分辨率的人像图片 作者基于LiuJuan Z-Image Generator定制 import os import time from datetime import datetime from pathlib import Path from typing import List, Dict, Tuple import argparse # 导入我们之前定义的生成器 # 假设上面的LiuJuanImageGenerator类保存在liujuan_generator.py中 from liujuan_generator import LiuJuanImageGenerator class BatchImageGenerator: def __init__(self, output_dir./output): 初始化批量生成器 参数 - output_dir: 输出目录路径 self.output_dir Path(output_dir) self.output_dir.mkdir(parentsTrue, exist_okTrue) # 初始化LiuJuan生成器 print(初始化LiuJuan Z-Image生成器...) self.generator LiuJuanImageGenerator( model_path./models/z-image-base, # 根据实际路径调整 weight_path./models/liujuan-weights.safetensors # 根据实际路径调整 ) print(生成器初始化完成) def define_resolution_presets(self) - Dict[str, Tuple[int, int]]: 定义常用的分辨率预设 返回字典键为预设名称值为(宽度, 高度)元组 presets { # 社交媒体尺寸 instagram_square: (1080, 1080), # Instagram正方形 instagram_portrait: (1080, 1350), # Instagram竖版 instagram_landscape: (1080, 566), # Instagram横版 # 电商平台尺寸 taobao_main: (800, 800), # 淘宝主图 taobao_detail: (750, 1000), # 淘宝详情 jd_product: (800, 800), # 京东商品 # 网站与UI设计 web_banner: (1920, 600), # 网页横幅 hero_image: (1920, 1080), # 首页大图 card_image: (400, 300), # 卡片图片 # 移动端适配 mobile_wallpaper: (1080, 1920), # 手机壁纸 app_icon: (512, 512), # App图标 app_banner: (1200, 628), # App推广图 # 打印与专业用途 a4_print: (2480, 3508), # A4打印300DPI poster: (2550, 3300), # 海报尺寸 business_card: (1050, 600), # 名片背景 } return presets def generate_batch(self, prompts: List[str], resolutions: List[Tuple[int, int]] None, resolution_presets: List[str] None, negative_prompt: str , steps: int 12, guidance_scale: float 2.0, seed: int None): 批量生成图片 参数 - prompts: 提示词列表每个提示词生成一组图片 - resolutions: 自定义分辨率列表格式为[(宽1,高1), (宽2,高2), ...] - resolution_presets: 使用预设分辨率如[instagram_square, web_banner] - negative_prompt: 负面提示词 - steps: 采样步数 - guidance_scale: 引导系数 - seed: 随机种子None表示随机 # 确定要生成的分辨率 if resolutions is None and resolution_presets is None: # 默认使用几个常用分辨率 resolutions [(512, 512), (768, 768), (1024, 1024)] elif resolution_presets is not None: presets self.define_resolution_presets() resolutions [presets[name] for name in resolution_presets if name in presets] print(f开始批量生成...) print(f提示词数量: {len(prompts)}) print(f分辨率数量: {len(resolutions)}) print(f总计生成图片: {len(prompts) * len(resolutions)}张) # 创建本次生成的子目录 timestamp datetime.now().strftime(%Y%m%d_%H%M%S) batch_dir self.output_dir / fbatch_{timestamp} batch_dir.mkdir(exist_okTrue) # 保存生成参数 self._save_generation_params(batch_dir, prompts, resolutions, negative_prompt, steps, guidance_scale) # 开始批量生成 total_images 0 start_time time.time() for prompt_idx, prompt in enumerate(prompts): print(f\n处理提示词 {prompt_idx1}/{len(prompts)}: {prompt[:50]}...) # 为每个提示词创建子目录 prompt_safe self._sanitize_filename(prompt[:30]) prompt_dir batch_dir / fprompt_{prompt_idx1:02d}_{prompt_safe} prompt_dir.mkdir(exist_okTrue) for res_idx, (width, height) in enumerate(resolutions): print(f 生成分辨率 {res_idx1}/{len(resolutions)}: {width}x{height}) try: # 设置随机种子可选 current_seed seed if seed is not None else torch.randint(0, 2**32, (1,)).item() torch.manual_seed(current_seed) # 生成图片 image self.generator.generate_image( promptprompt, negative_promptnegative_prompt, heightheight, widthwidth, stepssteps, guidance_scaleguidance_scale ) # 保存图片 filename f{prompt_safe}_{width}x{height}_seed{current_seed}.png filepath prompt_dir / filename image.save(filepath) # 保存生成信息 self._save_image_info(filepath, prompt, negative_prompt, width, height, steps, guidance_scale, current_seed) total_images 1 print(f 已保存: {filename}) except Exception as e: print(f 生成失败 ({width}x{height}): {str(e)}) # 保存错误信息 error_file prompt_dir / ferror_{width}x{height}.txt with open(error_file, w) as f: f.write(f提示词: {prompt}\n) f.write(f分辨率: {width}x{height}\n) f.write(f错误: {str(e)}\n) # 生成完成统计 elapsed_time time.time() - start_time print(f\n批量生成完成!) print(f总计生成: {total_images}张图片) print(f耗时: {elapsed_time:.2f}秒) print(f平均每张: {elapsed_time/max(1, total_images):.2f}秒) print(f输出目录: {batch_dir.absolute()}) # 生成汇总报告 self._generate_summary_report(batch_dir, total_images, elapsed_time) return batch_dir def _sanitize_filename(self, text: str) - str: 清理文件名中的非法字符 import re # 移除特殊字符只保留字母、数字、中文、下划线和空格 text re.sub(r[:/\\|?*], , text) # 替换多个空格为单个下划线 text re.sub(r\s, _, text.strip()) # 限制长度 return text[:50] def _save_generation_params(self, batch_dir, prompts, resolutions, negative_prompt, steps, guidance_scale): 保存生成参数到文件 params_file batch_dir / generation_params.txt with open(params_file, w, encodingutf-8) as f: f.write( 批量生成参数 \n\n) f.write(f生成时间: {datetime.now().strftime(%Y-%m-%d %H:%M:%S)}\n) f.write(f模型: LiuJuan Z-Image Generator\n) f.write(f负面提示词: {negative_prompt}\n) f.write(f采样步数: {steps}\n) f.write(f引导系数: {guidance_scale}\n\n) f.write(提示词列表:\n) for i, prompt in enumerate(prompts): f.write(f{i1}. {prompt}\n) f.write(\n分辨率列表:\n) for i, (w, h) in enumerate(resolutions): f.write(f{i1}. {w}x{h}\n) def _save_image_info(self, filepath, prompt, negative_prompt, width, height, steps, guidance_scale, seed): 保存单张图片的生成信息 info_file filepath.with_suffix(.txt) with open(info_file, w, encodingutf-8) as f: f.write( 图片生成信息 \n\n) f.write(f文件名: {filepath.name}\n) f.write(f生成时间: {datetime.now().strftime(%Y-%m-%d %H:%M:%S)}\n) f.write(f提示词: {prompt}\n) f.write(f负面提示词: {negative_prompt}\n) f.write(f分辨率: {width}x{height}\n) f.write(f采样步数: {steps}\n) f.write(f引导系数: {guidance_scale}\n) f.write(f随机种子: {seed}\n) def _generate_summary_report(self, batch_dir, total_images, elapsed_time): 生成汇总报告 report_file batch_dir / summary_report.md # 统计各目录的图片数量 prompt_dirs [d for d in batch_dir.iterdir() if d.is_dir() and d.name.startswith(prompt_)] with open(report_file, w, encodingutf-8) as f: f.write(# 批量生成汇总报告\n\n) f.write(f**生成时间**: {datetime.now().strftime(%Y-%m-%d %H:%M:%S)}\n) f.write(f**总计图片**: {total_images}张\n) f.write(f**总耗时**: {elapsed_time:.2f}秒\n) f.write(f**平均每张**: {elapsed_time/max(1, total_images):.2f}秒\n\n) f.write(## 生成详情\n\n) for prompt_dir in prompt_dirs: images list(prompt_dir.glob(*.png)) if images: f.write(f### {prompt_dir.name}\n) f.write(f- 图片数量: {len(images)}张\n) f.write(f- 示例提示词: {images[0].stem.split(_)[0]}\n) f.write(\n) def main(): 主函数解析命令行参数并执行批量生成 parser argparse.ArgumentParser(descriptionLiuJuan Z-Image批量生成脚本) parser.add_argument(--prompts, typestr, nargs, help提示词列表用空格分隔) parser.add_argument(--prompt-file, typestr, help包含提示词的文件路径每行一个提示词) parser.add_argument(--presets, typestr, nargs, default[instagram_square, instagram_portrait, web_banner], help分辨率预设名称列表) parser.add_argument(--negative, typestr, default, help负面提示词) parser.add_argument(--steps, typeint, default12, help采样步数默认12) parser.add_argument(--guidance, typefloat, default2.0, help引导系数默认2.0) parser.add_argument(--seed, typeint, defaultNone, help随机种子默认随机) parser.add_argument(--output, typestr, default./output, help输出目录默认./output) args parser.parse_args() # 准备提示词列表 prompts [] if args.prompts: prompts.extend(args.prompts) if args.prompt_file and os.path.exists(args.prompt_file): with open(args.prompt_file, r, encodingutf-8) as f: file_prompts [line.strip() for line in f if line.strip()] prompts.extend(file_prompts) if not prompts: # 如果没有提供提示词使用示例提示词 prompts [ photograph of a beautiful girl, close up, natural skin texture, soft lighting, 8k, masterpiece, portrait of a handsome man, professional photography, detailed eyes, cinematic lighting, anime style girl, colorful hair, detailed face, fantasy background, digital art ] print(使用示例提示词) print(f将使用 {len(prompts)} 个提示词进行生成) # 创建批量生成器并执行 generator BatchImageGenerator(output_dirargs.output) # 执行批量生成 generator.generate_batch( promptsprompts, resolution_presetsargs.presets, negative_promptargs.negative, stepsargs.steps, guidance_scaleargs.guidance, seedargs.seed ) if __name__ __main__: main()4.2 脚本使用示例保存上面的代码为batch_generator.py然后可以通过多种方式使用方式1直接运行使用默认参数python batch_generator.py这会使用内置的3个示例提示词和3个预设分辨率生成9张图片。方式2指定提示词python batch_generator.py --prompts a cute cat wearing glasses a futuristic city at night a beautiful sunset over mountains方式3从文件读取提示词# 创建提示词文件 prompts.txt echo photograph of a beautiful girl, close up, natural skin texture prompts.txt echo portrait of an old wise man, detailed wrinkles, dramatic lighting prompts.txt # 使用文件中的提示词 python batch_generator.py --prompt-file prompts.txt方式4自定义分辨率预设python batch_generator.py --presets instagram_square web_banner mobile_wallpaper方式5完整参数配置python batch_generator.py \ --prompts a fantasy elf with glowing eyes \ --presets instagram_square instagram_portrait taobao_main \ --negative nsfw, low quality, blurry, text \ --steps 15 \ --guidance 2.5 \ --seed 12345 \ --output ./my_batch_output5. 高级功能与定制技巧5.1 动态参数生成如果你想要更灵活的参数组合可以修改脚本支持参数扫描def generate_with_parameter_sweep(self, base_prompt, parameter_ranges): 参数扫描生成测试不同参数组合的效果 参数 - base_prompt: 基础提示词 - parameter_ranges: 参数字典如 { steps: [10, 12, 15, 20], guidance_scale: [1.5, 2.0, 2.5, 3.0], seed: [42, 123, 456, 789] } all_combinations [] # 生成所有参数组合 import itertools param_names list(parameter_ranges.keys()) param_values list(parameter_ranges.values()) for combination in itertools.product(*param_values): params dict(zip(param_names, combination)) all_combinations.append(params) print(f将生成 {len(all_combinations)} 种参数组合) # 为每种组合生成图片 for i, params in enumerate(all_combinations): print(f\n生成组合 {i1}/{len(all_combinations)}) print(f参数: {params}) # 构建文件名 param_str _.join([f{k}{v} for k, v in params.items()]) filename fparam_test_{param_str}.png # 生成图片 image self.generator.generate_image( promptbase_prompt, negative_prompt, height512, width512, **params # 解包参数 ) # 保存图片和参数 image.save(f./param_test/{filename}) # 保存参数记录 with open(f./param_test/{filename}.txt, w) as f: for key, value in params.items(): f.write(f{key}: {value}\n)5.2 智能提示词增强为提升生成质量可以添加提示词增强功能class PromptEnhancer: 提示词增强器自动优化输入提示词 staticmethod def enhance_portrait_prompt(base_prompt, stylephotorealistic): 增强人像提示词 style_templates { photorealistic: 8k, masterpiece, best quality, ultra detailed, photorealistic, anime: anime style, vibrant colors, detailed eyes, beautiful detailed face, digital_art: digital art, concept art, trending on artstation, detailed, cinematic: cinematic, dramatic lighting, film grain, depth of field, painting: oil painting, brush strokes, artistic, masterpiece painting } style_suffix style_templates.get(style, style_templates[photorealistic]) # 基础质量词 quality_words high resolution, detailed, sharp focus # 组合提示词 enhanced_prompt f{base_prompt}, {style_suffix}, {quality_words} return enhanced_prompt staticmethod def get_negative_prompt(stylegeneral): 获取风格化负面提示词 negative_prompts { general: nsfw, low quality, worst quality, jpeg artifacts, blurry, portrait: bad anatomy, deformed, disfigured, poorly drawn face, mutation, artistic: watermark, signature, text, username, error, extra digit, realistic: 3d, cartoon, anime, painting, drawing, illustration } return negative_prompts.get(style, negative_prompts[general])5.3 批量后处理与整理生成大量图片后可能需要自动整理import shutil from PIL import Image class BatchPostProcessor: 批量后处理器 staticmethod def organize_by_resolution(output_dir): 按分辨率整理图片 output_path Path(output_dir) # 找出所有图片 image_files list(output_path.rglob(*.png)) # 按分辨率分组 resolution_groups {} for img_file in image_files: try: with Image.open(img_file) as img: width, height img.size resolution f{width}x{height} if resolution not in resolution_groups: resolution_groups[resolution] [] resolution_groups[resolution].append(img_file) except Exception as e: print(f无法读取 {img_file}: {e}) # 创建分辨率目录并移动文件 for resolution, files in resolution_groups.items(): res_dir output_path / fresolution_{resolution} res_dir.mkdir(exist_okTrue) for file in files: shutil.move(str(file), str(res_dir / file.name)) print(f已按分辨率整理 {len(image_files)} 张图片) staticmethod def create_contact_sheet(images, output_path, cols4, thumb_size(256, 256)): 创建联系表缩略图网格 rows (len(images) cols - 1) // cols sheet_width cols * thumb_size[0] sheet_height rows * thumb_size[1] contact_sheet Image.new(RGB, (sheet_width, sheet_height), white) for i, img_path in enumerate(images): row i // cols col i % cols try: img Image.open(img_path) img.thumbnail(thumb_size, Image.Resampling.LANCZOS) x_offset col * thumb_size[0] y_offset row * thumb_size[1] # 居中放置缩略图 x_center x_offset (thumb_size[0] - img.width) // 2 y_center y_offset (thumb_size[1] - img.height) // 2 contact_sheet.paste(img, (x_center, y_center)) except Exception as e: print(f无法处理 {img_path}: {e}) contact_sheet.save(output_path) print(f联系表已保存至 {output_path})6. 实际应用案例6.1 电商产品图批量生成假设你是一个电商卖家需要为新产品生成不同平台的展示图# 电商产品图批量生成配置 ecommerce_config { prompts: [ professional product photography of a wireless headphone, studio lighting, clean background, 8k, lifestyle photo of person wearing wireless headphones in cafe, natural lighting, bokeh background, product detail shot of wireless headphone ear cushion, macro photography, texture detail ], resolutions: [ (800, 800), # 淘宝/京东主图 (750, 1000), # 淘宝详情长图 (1200, 628), # 社交媒体分享图 (1920, 1080), # 网站横幅 (1080, 1080), # Instagram正方形 (1080, 1350), # Instagram竖版 ], negative_prompt: nsfw, low quality, blurry, watermark, text, logo, people, steps: 15, guidance_scale: 2.0 } # 执行生成 generator BatchImageGenerator(output_dir./ecommerce_products) generator.generate_batch(**ecommerce_config)6.2 游戏角色多尺寸头像游戏开发中需要为角色生成不同尺寸的头像# 游戏角色头像批量生成 game_character_config { prompts: [ fantasy elf warrior character portrait, detailed armor, glowing eyes, epic fantasy art, digital painting, cyberpunk hacker character, neon lighting, futuristic city background, detailed face, concept art, cute anime cat girl, magical girl transformation, sparkling effects, vibrant colors, anime style ], resolution_presets: [ instagram_square, # 社交媒体 instagram_portrait, # 竖版展示 app_icon, # App图标 mobile_wallpaper, # 手机壁纸 web_banner, # 网站横幅 ], negative_prompt: bad anatomy, deformed, disfigured, poorly drawn face, extra limbs, steps: 20, # 角色设计需要更多细节 guidance_scale: 2.5 } generator BatchImageGenerator(output_dir./game_characters) generator.generate_batch(**game_character_config)6.3 A/B测试不同参数效果测试不同参数对生成质量的影响# 参数A/B测试 test_prompt portrait of a wise old wizard, detailed face, magical aura, fantasy art # 测试不同步数 for steps in [10, 15, 20, 25, 30]: image generator.generate_image( prompttest_prompt, height512, width512, stepssteps, guidance_scale2.0 ) image.save(f./ab_test/steps_{steps}.png) # 测试不同引导系数 for guidance in [1.5, 2.0, 2.5, 3.0, 3.5, 4.0]: image generator.generate_image( prompttest_prompt, height512, width512, steps15, guidance_scaleguidance ) image.save(f./ab_test/guidance_{guidance}.png)7. 性能优化与问题排查7.1 显存管理技巧批量生成时显存管理尤为重要class MemoryOptimizedGenerator(LiuJuanImageGenerator): 显存优化版生成器 def __init__(self, *args, **kwargs): super().__init__(*args, **kwargs) self._setup_memory_monitor() def _setup_memory_monitor(self): 设置显存监控 import threading import time def monitor_memory(): while getattr(self, monitoring, True): torch.cuda.synchronize() allocated torch.cuda.memory_allocated() / 1024**3 # GB reserved torch.cuda.memory_reserved() / 1024**3 # GB print(f[显存监控] 已分配: {allocated:.2f}GB, 已保留: {reserved:.2f}GB) time.sleep(5) # 启动监控线程 self.monitor_thread threading.Thread(targetmonitor_memory, daemonTrue) self.monitoring True self.monitor_thread.start() def generate_with_memory_clear(self, *args, **kwargs): 生成后清理显存 try: result self.generate_image(*args, **kwargs) return result finally: # 强制清理显存 torch.cuda.empty_cache() torch.cuda.synchronize() def cleanup(self): 清理资源 self.monitoring False if hasattr(self, monitor_thread): self.monitor_thread.join(timeout1) # 清理模型 del self.pipe torch.cuda.empty_cache()7.2 常见问题与解决方案问题1显存不足OOM# 解决方案启用CPU卸载和降低批次大小 generator.pipe.enable_model_cpu_offload() # CPU卸载 generator.pipe.enable_attention_slicing() # 注意力切片 # 或者降低分辨率 smaller_image generator.generate_image(prompt, height384, width384)问题2生成速度慢# 解决方案调整优化设置 # 1. 使用更少的采样步数10-15步通常足够 # 2. 启用xformers加速如果可用 if hasattr(generator.pipe, enable_xformers_memory_efficient_attention): generator.pipe.enable_xformers_memory_efficient_attention() # 3. 使用更小的模型变体如果有问题3生成质量不稳定# 解决方案优化提示词和参数 # 1. 使用更详细的提示词 detailed_prompt photograph of a beautiful girl, close up, natural skin texture, soft lighting, 8k, masterpiece, best quality # 2. 调整CFG ScaleZ-Image推荐2.0左右 # 3. 使用固定的随机种子确保可重复性 generator torch.Generator(devicecuda).manual_seed(12345) # 4. 尝试不同的采样器 from diffusers import EulerDiscreteScheduler generator.pipe.scheduler EulerDiscreteScheduler.from_config(generator.pipe.scheduler.config)7.3 批量生成的最佳实践预热模型在正式批量生成前先生成1-2张图片预热模型渐进式生成先小批量测试再大规模生成保存检查点长时间运行时定期保存进度错误处理捕获并记录生成错误不影响其他图片生成资源监控监控显存和GPU使用情况避免资源耗尽def safe_batch_generate(generator, prompts, max_retries3): 安全的批量生成带重试机制 results [] for i, prompt in enumerate(prompts): for attempt in range(max_retries): try: print(f生成 {i1}/{len(prompts)}: {prompt[:50]}... (尝试 {attempt1})) image generator.generate_with_memory_clear(promptprompt) results.append((prompt, image)) break # 成功则跳出重试循环 except torch.cuda.OutOfMemoryError: print(f 显存不足尝试清理...) torch.cuda.empty_cache() time.sleep(2) # 等待显存释放 except Exception as e: print(f 生成失败: {e}) if attempt max_retries - 1: print(f 跳过该提示词: {prompt}) results.append((prompt, None)) # 记录失败 time.sleep(1) return results8. 总结通过本文的脚本示例你已经掌握了使用LiuJuan Z-Image Generator进行批量图片生成的核心技能。让我们回顾一下关键要点8.1 核心收获脚本化思维将重复的手动操作转化为自动化流程大幅提升工作效率灵活配置通过参数化设计支持多种分辨率预设和自定义组合错误处理完善的异常捕获和重试机制确保批量任务稳定运行资源管理显存优化和监控避免资源耗尽导致任务中断结果组织自动化的文件命名和目录结构方便后续查找和使用8.2 实际应用价值这个批量生成脚本在实际工作中能帮你节省时间一次性生成所有需要的尺寸无需手动重复操作保证一致性相同的提示词和参数确保生成风格统一便于测试快速测试不同参数组合找到最佳配置规模化生产支持大规模图片生成需求适合商业应用结果可追溯详细的生成记录方便问题排查和效果分析8.3 下一步建议如果你已经掌握了基础批量生成可以进一步探索集成到工作流将脚本集成到你的设计或开发流程中自定义模型训练自己的LiuJuan风格权重实现更个性化的生成质量评估添加自动化的质量评估和筛选机制云端部署将脚本部署到云端服务器实现24小时不间断生成API封装将生成功能封装为API供其他系统调用批量生成只是开始LiuJuan Z-Image Generator的真正威力在于它的灵活性和可定制性。通过深入理解其工作原理和代码结构你可以根据自己的需求进行各种定制和扩展打造真正适合自己的AI图片生成工作流。记住最好的工具是那个最能解决你实际问题的工具。现在拿起这个脚本开始你的批量创作之旅吧获取更多AI镜像想探索更多AI镜像和应用场景访问 CSDN星图镜像广场提供丰富的预置镜像覆盖大模型推理、图像生成、视频生成、模型微调等多个领域支持一键部署。