Krea2 AI图像生成:PID控制、StyleTransfer与JSON批处理实战指南
在 AI 图像生成领域Krea2 近期以其惊人的迭代速度和功能完整性吸引了大量开发者和创作者的目光。从 PID 控制的 4K 成片生成、实时图像编辑、StyleTransfer 风格迁移到 JSON 驱动的多宫格布局和 VAE/GLSL 全链路渲染Krea2 正在重新定义工作流的边界。如果你正在寻找一套能同时满足实验性创作和工业化生产的工具链或者希望理解这些技术模块如何协同工作本文将带你从环境搭建到核心功能实现完整走通 Krea2 的典型使用场景。本文将重点放在可复现的工程实践上包括 PID 控制器在图像超分中的参数调优、StyleTransfer 的权重加载与风格强度控制、JSON 配置的多宫格批量生成以及 VAE 与 GLSL 在渲染管线中的替代方案。每个环节都会提供可运行的代码片段、配置文件示例和参数说明并附上常见问题的排查路径。1. 理解 Krea2 的核心技术栈与工作流Krea2 不是一个单一模型或工具而是一个整合了多种 AI 图像生成与处理技术的生态系统。其核心价值在于将原本需要多步骤、多工具链的任务整合为可配置、可编程的流水线。在深入具体功能前需要先理解几个关键概念是如何在 Krea2 中协同工作的。1.1 PID 控制器在图像生成中的角色PID比例-积分-微分控制器原本是工业控制中用于调节系统输出的算法在 Krea2 中被创新性地用于控制图像生成过程中的噪声调度和细节增强。与传统图像超分算法不同PID 控制器能够根据当前生成状态动态调整下一步的生成强度避免过度平滑或细节失真。在 Krea2 中PID 控制器通常作用于潜在空间latent space的迭代过程通过三个参数的配合控制生成质量比例项P控制当前生成结果与目标之间的误差响应速度值越大对差异越敏感积分项I累积历史误差用于消除稳态误差防止细节丢失微分项D预测误差变化趋势抑制超调避免过度锐化1.2 StyleTransfer 风格迁移的工作机制Krea2 的风格迁移基于预训练的风格转移网络但增加了更细粒度的控制参数。与早期风格迁移只能整体应用风格不同Krea2 允许用户指定风格应用的区域强度并支持多种风格的混合应用。风格迁移在 Krea2 中通常作为后处理步骤可以在基础图像生成完成后应用也可以与生成过程交替进行。关键参数包括风格权重0-1控制风格影响的强度内容保留度确保原始图像内容不被风格完全覆盖风格混合比例当使用多个风格源时的混合权重1.3 JSON 配置驱动的批量生成流程Krea2 的批处理能力很大程度上依赖于 JSON 配置文件的灵活性和可编程性。通过 JSON 文件用户可以定义复杂的生成任务序列包括多组参数、输入输出路径、后处理步骤等。一个典型的 Krea2 JSON 配置包含以下结构层次任务列表多个生成任务的集合每个任务的模型参数、输入源、输出设置预处理和后处理步骤链资源分配和并行设置1.4 VAE 与 GLSL 在渲染管线中的分工VAE变分自编码器负责在潜在空间和像素空间之间进行编码解码而 GLSLOpenGL 着色语言则用于实时的后处理效果渲染。Krea2 的创新之处在于让这两个技术栈协同工作VAE 处理核心的图像生成和重构GLSL 负责实时的色彩调整、滤镜应用和性能优化。在硬件加速支持下GLSL 着色器可以高效处理大量图像的实时后处理这对于需要快速预览和迭代的创作工作流至关重要。2. 环境准备与依赖配置开始使用 Krea2 前需要确保开发环境满足基本要求并正确安装所有必要的依赖包。以下配置已在 Ubuntu 20.04、Windows 10 和 macOS 12 环境下验证。2.1 系统要求与基础环境检查Krea2 对硬件有一定要求特别是需要支持 CUDA 的 NVIDIA GPU 以获得最佳性能。以下是详细的环境要求组件最低要求推荐配置检查命令操作系统Ubuntu 18.04 / Win 10 / macOS 11Ubuntu 20.04 / Win 11 / macOS 12cat /etc/os-release或systeminfoPython3.83.9-3.11python --versionCUDA11.011.7-11.8nvcc --versionGPU 内存8GB16GBnvidia-smi系统内存16GB32GBfree -h或 Task Manager存储空间10GB 空闲50GB 空闲df -h基础环境验证脚本#!/bin/bash echo 环境检查开始 # 检查 Python python --version if [ $? -ne 0 ]; then echo 错误: Python 未安装 exit 1 fi # 检查 pip pip --version if [ $? -ne 0 ]; then echo 错误: pip 未安装 exit 1 fi # 检查 CUDA (如果使用 NVIDIA GPU) if command -v nvcc /dev/null; then nvcc --version else echo 警告: CUDA 未检测到将使用 CPU 模式性能较差 fi echo 环境检查完成 2.2 Python 依赖包安装Krea2 依赖多个 Python 包建议使用虚拟环境隔离安装。创建并激活虚拟环境# 创建虚拟环境 python -m venv krea2_env # 激活虚拟环境 # Linux/macOS source krea2_env/bin/activate # Windows krea2_env\Scripts\activate # 升级 pip pip install --upgrade pip安装核心依赖包# 安装 PyTorch (根据 CUDA 版本选择) # CUDA 11.7 pip install torch torchvision torchaudio --index-url https://download.pytorch.org/whl/cu117 # 或者 CPU 版本 # pip install torch torchvision torchaudio # 安装 Krea2 核心包 pip install diffusers transformers accelerate safetensors # 图像处理相关 pip install pillow opencv-python scikit-image # 科学计算和配置 pip install numpy matplotlib json5 # 可选: 用于 GLSL 集成 pip install PyOpenGL glfw验证安装是否成功# test_installation.py import torch import diffusers import PIL import json print(fPyTorch 版本: {torch.__version__}) print(fCUDA 可用: {torch.cuda.is_available()}) print(fDiffusers 版本: {diffusers.__version__}) if torch.cuda.is_available(): print(fGPU 设备: {torch.cuda.get_device_name(0)}) print(fGPU 内存: {torch.cuda.get_device_properties(0).total_memory / 1e9:.1f} GB)2.3 模型权重下载与配置Krea2 需要下载预训练模型权重。由于模型文件较大建议配置缓存路径并确保网络稳定。设置模型缓存路径避免默认下载到系统盘# Linux/macOS: 添加到 ~/.bashrc 或 ~/.zshrc export HF_HOME/path/to/your/model/cache export DIFFUSERS_CACHE$HF_HOME/diffusers export TRANSFORMERS_CACHE$HF_HOME/transformers # Windows: 系统环境变量 set HF_HOMED:\models\cache set DIFFUSERS_CACHE%HF_HOME%\diffusers set TRANSFORMERS_CACHE%HF_HOME%\transformers下载基础模型权重的 Python 脚本# download_models.py from diffusers import StableDiffusionPipeline, StableDiffusionImg2ImgPipeline from transformers import CLIPTextModel, CLIPTokenizer import os # 创建缓存目录 os.makedirs(os.getenv(DIFFUSERS_CACHE), exist_okTrue) def download_base_models(): 下载基础模型 print(开始下载 Stable Diffusion 模型...) # 文本到图像模型 pipe StableDiffusionPipeline.from_pretrained( runwayml/stable-diffusion-v1-5, cache_diros.getenv(DIFFUSERS_CACHE), local_files_onlyFalse # 允许下载 ) # 图像到图像模型 img2img_pipe StableDiffusionImg2ImgPipeline.from_pretrained( runwayml/stable-diffusion-v1-5, cache_diros.getenv(DIFFUSERS_CACHE) ) print(基础模型下载完成) if __name__ __main__: download_base_models()3. PID 控制的 4K 图像生成实战PID 控制器在 Krea2 中主要用于提升高分辨率图像生成的稳定性和细节质量。传统方法直接生成 4K 图像往往面临内存不足和细节失真问题而 PID 控制通过分阶段优化解决了这一挑战。3.1 PID 参数调优原理在图像生成上下文中PID 参数需要重新理解比例系数Kp控制当前生成步骤对潜在空间误差的响应强度。值过大会导致图像噪声过多值过小则细节增强不足。积分系数Ki累积多步的误差用于补偿系统性偏差。适合处理整体色调或风格的一致性。微分系数Kd抑制生成过程中的突变防止局部过度优化。对避免人工痕迹很重要。经验性的起始参数范围# pid_baseline_params.py PID_BASELINE { low_resolution: {Kp: 0.7, Ki: 0.1, Kd: 0.05}, # 初始低分辨率阶段 mid_resolution: {Kp: 0.5, Ki: 0.2, Kd: 0.1}, # 中等分辨率增强 high_resolution: {Kp: 0.3, Ki: 0.3, Kd: 0.15}, # 高分辨率细化 }3.2 实现 PID 控制的超分流程以下是完整的 PID 控制超分实现# pid_upscaler.py import torch import torch.nn.functional as F from PIL import Image import numpy as np from diffusers import StableDiffusionUpscalePipeline class PIDUpscaler: def __init__(self, model_idstabilityai/stable-diffusion-x4-upscaler): self.pipe StableDiffusionUpscalePipeline.from_pretrained( model_id, torch_dtypetorch.float16 if torch.cuda.is_available() else torch.float32 ) self.pipe self.pipe.to(cuda if torch.cuda.is_available() else cpu) # PID 控制器状态 self.integral_error 0 self.previous_error 0 def pid_control(self, current_output, target_quality, Kp, Ki, Kd, dt1.0): PID 控制算法实现 current_output: 当前生成图像的质量评估 target_quality: 目标质量水平 Kp, Ki, Kd: PID 参数 dt: 时间步长用于离散积分 error target_quality - current_output # 比例项 proportional Kp * error # 积分项带限幅防止积分饱和 self.integral_error error * dt self.integral_error np.clip(self.integral_error, -10, 10) # 限幅 integral Ki * self.integral_error # 微分项 derivative Kd * (error - self.previous_error) / dt if dt 0 else 0 self.previous_error error # 控制输出 control_output proportional integral derivative return control_output, error def assess_image_quality(self, image_tensor): 评估图像质量简化版 # 使用图像梯度评估细节丰富度 dx torch.abs(image_tensor[:, :, 1:, :] - image_tensor[:, :, :-1, :]) dy torch.abs(image_tensor[:, :, :, 1:] - image_tensor[:, :, :, :-1]) gradient_magnitude (dx.mean() dy.mean()).item() # 使用对比度评估图像动态范围 contrast image_tensor.std().item() # 综合质量评分0-1 quality_score min(1.0, gradient_magnitude * 10 contrast * 5) return quality_score def upscale_with_pid(self, input_image, target_size(3840, 2160), prompthigh quality, detailed, num_steps3): 使用 PID 控制的多阶段超分 current_image input_image # 多阶段超分参数 stages [ {scale: 2, Kp: 0.7, Ki: 0.1, Kd: 0.05, steps: 20}, {scale: 1.5, Kp: 0.5, Ki: 0.2, Kd: 0.1, steps: 15}, {scale: 1.33, Kp: 0.3, Ki: 0.3, Kd: 0.15, steps: 10} ] for i, stage in enumerate(stages): print(f阶段 {i1}: 放大 {stage[scale]} 倍) # 计算当前目标尺寸 current_size (int(current_image.size[0] * stage[scale]), int(current_image.size[1] * stage[scale])) # 使用 PID 控制生成 current_image self.controlled_upscale( current_image, current_size, prompt, stage[Kp], stage[Ki], stage[Kd], stage[steps] ) return current_image def controlled_upscale(self, input_image, target_size, prompt, Kp, Ki, Kd, num_steps): 单阶段 PID 控制超分 # 初始生成 upscaled self.pipe( promptprompt, imageinput_image, target_sizetarget_size, num_inference_stepsnum_steps ).images[0] # 评估质量并应用 PID 调整 image_tensor torch.tensor(np.array(upscaled)).float() / 255.0 quality self.assess_image_quality(image_tensor.unsqueeze(0).permute(0, 3, 1, 2)) control_signal, error self.pid_control(quality, 0.8, Kp, Ki, Kd) print(f质量评分: {quality:.3f}, PID 控制信号: {control_signal:.3f}) # 根据控制信号调整生成参数简化处理 if control_signal 0.1: # 需要更多细节进行额外细化 upscaled self.pipe( promptprompt , extremely detailed, sharp focus, imageupscaled, num_inference_stepsmax(5, int(num_steps * (1 control_signal))) ).images[0] return upscaled # 使用示例 if __name__ __main__: upscaler PIDUpscaler() # 加载输入图像 input_img Image.open(input.jpg).convert(RGB) # 4K 超分 result upscaler.upscale_with_pid(input_img, target_size(3840, 2160)) result.save(4k_output.jpg)3.3 PID 超分常见问题排查问题现象可能原因检查方法解决方案生成图像噪声过多Kp 值过大检查 PID 参数设置降低 Kp 值增加 Kd 值细节增强不足Kp 值过小或 Ki 值不当查看质量评估分数提高 Kp 值调整 Ki 值生成时间过长阶段划分过多或步数设置过大检查阶段参数减少阶段数或每步推理步数内存不足单阶段放大倍数过大监控 GPU 内存使用减小单次放大倍数分更多阶段风格不一致提示词在不同阶段变化检查各阶段提示词保持提示词一致性使用更稳定的模型4. StyleTransfer 风格迁移深度集成Krea2 的风格迁移功能超越了简单的滤镜应用实现了基于深度学习的语义感知风格转移。下面将实现一个完整的风格迁移管线支持多层级的风格控制。4.1 风格迁移模型加载与配置# style_transfer.py import torch import torch.nn as nn from torchvision import transforms from PIL import Image import numpy as np class KreaStyleTransfer: def __init__(self, style_model_pathNone): self.device cuda if torch.cuda.is_available() else cpu # 图像预处理 self.preprocess transforms.Compose([ transforms.Resize(512), transforms.CenterCrop(512), transforms.ToTensor(), transforms.Normalize(mean[0.485, 0.456, 0.406], std[0.229, 0.224, 0.225]), ]) self.deprocess transforms.Compose([ transforms.Normalize(mean[-0.485/0.229, -0.456/0.224, -0.406/0.225], std[1/0.229, 1/0.224, 1/0.225]), ]) # 加载风格迁移模型 self.model self.load_style_transfer_model(style_model_path) def load_style_transfer_model(self, model_path): 加载风格迁移模型 if model_path is None: # 使用内置的简化风格迁移网络 class SimpleStyleTransfer(nn.Module): def __init__(self): super().__init__() # 简化的风格迁移网络结构 self.encoder nn.Sequential( nn.Conv2d(3, 64, 9, padding4), nn.ReLU(), nn.Conv2d(64, 128, 3, stride2, padding1), nn.ReLU(), nn.Conv2d(128, 256, 3, stride2, padding1), nn.ReLU(), ) self.residual_blocks nn.Sequential( *[ResidualBlock(256) for _ in range(5)] ) self.decoder nn.Sequential( nn.ConvTranspose2d(256, 128, 3, stride2, padding1, output_padding1), nn.ReLU(), nn.ConvTranspose2d(128, 64, 3, stride2, padding1, output_padding1), nn.ReLU(), nn.Conv2d(64, 3, 9, padding4), nn.Tanh() ) def forward(self, x): x self.encoder(x) x self.residual_blocks(x) x self.decoder(x) return x class ResidualBlock(nn.Module): def __init__(self, channels): super().__init__() self.block nn.Sequential( nn.Conv2d(channels, channels, 3, padding1), nn.InstanceNorm2d(channels), nn.ReLU(), nn.Conv2d(channels, channels, 3, padding1), nn.InstanceNorm2d(channels) ) def forward(self, x): return x self.block(x) model SimpleStyleTransfer() else: # 加载预训练模型 model torch.load(model_path) model model.to(self.device) model.eval() return model def extract_features(self, image_tensor): 提取内容特征用于内容损失计算 features [] x image_tensor # 使用编码器层提取多尺度特征 for layer in list(self.model.encoder.children())[:4]: x layer(x) features.append(x) return features def gram_matrix(self, input): 计算 Gram 矩阵风格特征 batch_size, channels, height, width input.size() features input.view(batch_size * channels, height * width) gram torch.mm(features, features.t()) return gram.div(batch_size * channels * height * width) def style_transfer(self, content_image, style_image, content_weight1, style_weight1e6, steps300, style_scale1.0, region_maskNone): 执行风格迁移 # 预处理图像 content_tensor self.preprocess(content_image).unsqueeze(0).to(self.device) style_tensor self.preprocess(style_image).unsqueeze(0).to(self.device) # 调整风格图像尺寸 if style_scale ! 1.0: new_size (int(style_tensor.shape[2] * style_scale), int(style_tensor.shape[3] * style_scale)) style_tensor F.interpolate(style_tensor, sizenew_size, modebilinear) # 初始化输出图像从内容图像开始 input_tensor content_tensor.clone().requires_grad_(True) optimizer torch.optim.LBFGS([input_tensor]) # 提取风格特征 style_features self.extract_features(style_tensor) style_grams [self.gram_matrix(f) for f in style_features] # 风格迁移迭代 for step in range(steps): def closure(): optimizer.zero_grad() # 前向传播 output self.model(input_tensor) content_features self.extract_features(content_tensor) output_features self.extract_features(output) # 内容损失 content_loss 0 for cnt, out in zip(content_features, output_features): content_loss F.mse_loss(out, cnt) # 风格损失 style_loss 0 output_grams [self.gram_matrix(f) for f in output_features] for stl_gram, out_gram in zip(style_grams, output_grams): style_loss F.mse_loss(out_gram, stl_gram) # 区域掩码处理如果提供 if region_mask is not None: mask_tensor torch.tensor(region_mask).float().to(self.device) content_loss (content_loss * mask_tensor).mean() style_loss (style_loss * mask_tensor).mean() # 总损失 total_loss content_weight * content_loss style_weight * style_loss total_loss.backward() if step % 50 0: print(fStep {step}: Content Loss: {content_loss.item():.4f}, fStyle Loss: {style_loss.item():.4f}) return total_loss optimizer.step(closure) # 后处理并返回图像 with torch.no_grad(): output self.model(input_tensor) output self.deprocess(output.squeeze(0)).clamp(0, 1) output_image transforms.ToPILImage()(output.cpu()) return output_image # 使用示例 def example_style_transfer(): stylizer KreaStyleTransfer() # 加载内容图像和风格图像 content_img Image.open(content.jpg).convert(RGB) style_img Image.open(style.jpg).convert(RGB) # 应用风格迁移 result stylizer.style_transfer( content_img, style_img, content_weight1, style_weight1e6, steps200, style_scale0.8 # 风格图像缩放 ) result.save(styled_output.jpg)4.2 多风格混合与区域控制Krea2 支持更高级的风格混合功能允许在不同图像区域应用不同风格# advanced_style_mixing.py class AdvancedStyleMixing: def __init__(self): self.stylizer KreaStyleTransfer() def create_region_mask(self, image_size, regions): 创建区域掩码 regions: [(x1, y1, x2, y2, style_index), ...] mask np.zeros(image_size, dtypenp.int32) for i, (x1, y1, x2, y2, style_idx) in enumerate(regions): mask[y1:y2, x1:x2] style_idx 1 # 1 因为0表示无风格 return mask def multi_style_transfer(self, content_img, style_images, regions_config): 多风格区域迁移 height, width content_img.size[1], content_img.size[0] region_mask self.create_region_mask((height, width), regions_config) # 为每个风格区域单独处理 result content_img.copy() for i, style_img in enumerate(style_images): # 创建当前风格的二值掩码 style_mask (region_mask (i 1)).astype(np.float32) if np.sum(style_mask) 0: # 确保区域有效 # 应用当前风格到指定区域 styled_region self.stylizer.style_transfer( content_img, style_img, region_maskstyle_mask, content_weight0.8, # 在混合区域降低内容权重 style_weight2e6 ) # 融合结果 result self.blend_images(result, styled_region, style_mask) return result def blend_images(self, base_img, overlay_img, mask): 基于掩码的图像融合 base_arr np.array(base_img).astype(np.float32) overlay_arr np.array(overlay_img).astype(np.float32) mask_3d np.stack([mask] * 3, axis2) # 线性混合 blended base_arr * (1 - mask_3d) overlay_arr * mask_3d return Image.fromarray(blended.astype(np.uint8)) # 使用示例 def example_multi_style(): mixer AdvancedStyleMixing() content Image.open(content.jpg) style1 Image.open(abstract_style.jpg) # 抽象风格 style2 Image.open(oil_painting_style.jpg) # 油画风格 # 定义区域左上角用风格1右下角用风格2 regions [ (0, 0, 400, 300, 0), # 风格1区域 (400, 300, 800, 600, 1) # 风格2区域 ] result mixer.multi_style_transfer(content, [style1, style2], regions) result.save(multi_style_output.jpg)5. JSON 配置的多宫格批量生成Krea2 的批处理系统通过 JSON 配置文件实现复杂的生成流程管理。这种声明式的方法使得重现实验、调整参数和批量生产变得非常高效。5.1 JSON 配置结构设计一个完整的 Krea2 批处理 JSON 配置包含多个层级// batch_config.json { version: 1.0, description: 多风格多尺寸批量生成配置, output_settings: { base_dir: ./output, format: jpg, quality: 95, metadata: true }, global_parameters: { safety_checker: true, guidance_scale: 7.5, num_inference_steps: 30 }, batches: [ { batch_id: landscape_collection, description: 风景图像系列, base_prompt: beautiful landscape, masterpiece, high quality, variations: [ { variation_id: mountain_morning, prompt_suffix: snowy mountains, morning light, peaceful, width: 1024, height: 768, seed: 42, style_preset: photographic }, { variation_id: ocean_sunset, prompt_suffix: ocean view, sunset, golden hour, waves, width: 1024, height: 768, seed: 123, style_preset: artistic } ] }, { batch_id: portrait_study, description: 人像研究系列, base_prompt: portrait of a person, detailed face, professional photography, variations: [ { variation_id: classic_portrait, prompt_suffix: classic lighting, studio background, sharp focus, width: 768, height: 1024, seed: 456, negative_prompt: blurry, distorted, ugly } ] } ], post_processing: { upscale: { enabled: true, method: PID_4K, scale_factor: 2.0 }, style_transfer: { enabled: false, style_image: ./styles/van_gogh.jpg, strength: 0.7 } } }5.2 JSON 配置解析与执行引擎# json_batch_processor.py import json import os from datetime import datetime from pathlib import Path import hashlib class KreaBatchProcessor: def __init__(self, config_path): self.config self.load_config(config_path) self.setup_directories() def load_config(self, config_path): 加载和验证 JSON 配置 with open(config_path, r, encodingutf-8) as f: config json.load(f) # 配置验证 required_sections [output_settings, batches] for section in required_sections: if section not in config: raise ValueError(f缺少必要配置段: {section}) return config def setup_directories(self): 创建输出目录结构 base_dir self.config[output_settings][base_dir] timestamp datetime.now().strftime(%Y%m%d_%H%M%S) self.output_dir Path(base_dir) / timestamp self.output_dir.mkdir(parentsTrue, exist_okTrue) # 保存配置副本 config_copy_path self.output_dir / config_backup.json with open(config_copy_path, w, encodingutf-8) as f: json.dump(self.config, f, indent2, ensure_asciiFalse) def generate_batch_id(self, batch_config, variation_config): 生成唯一的批次ID base_str f{batch_config[batch_id]}_{variation_config[variation_id]} if seed in variation_config: base_str f_{variation_config[seed]} # 添加哈希以确保唯一性 hash_obj hashlib.md5(base_str.encode()) return f{base_str}_{hash_obj.hexdigest()[:8]} def build_prompt(self, batch_config, variation_config): 构建完整提示词 base_prompt batch_config[base_prompt] suffix variation_config.get(prompt_suffix, ) if suffix: return f{base_prompt}, {suffix} return base_prompt def process_batch(self, pipeline): 执行批量生成 results [] for batch_config in self.config[batches]: batch_id batch_config[batch_id] print(f处理批次: {batch_id}) for variation in batch_config[variations]: # 生成唯一ID和完整提示词 variation_id self.generate_batch_id(batch_config, variation) full_prompt self.build_prompt(batch_config, variation) # 准备生成参数 generate_params { prompt: full_prompt, width: variation[width], height: variation[height], num_inference_steps: self.config[global_parameters][num_inference_steps], guidance_scale: self.config[global_parameters][guidance_scale], } # 添加可选参数 if seed in variation: generate_params[seed] variation[seed] if negative_prompt in variation: generate_params[negative_prompt] variation[negative_prompt] # 执行生成 print(f生成: {variation_id}) image pipeline(**generate_params).images[0] # 保存结果 output_path self.save_image(image, variation_id) # 记录元数据 results.append({ batch_id: batch_id, variation_id: variation_id, prompt: full_prompt, parameters: generate_params, output_path: str(output_path), timestamp: datetime.now().isoformat() }) # 保存结果元数据 self.save_metadata(results) return results def save_image(self, image, variation_id): 保存生成的图像 format self.config[output_settings][format] quality self.config[output_settings][quality] filename f{variation_id}.{format} output_path self.output_dir / filename save_params {} if format.lower() jpg: save_params[quality] quality image.save(output_path, **save_params) return output_path def save_metadata(self, results): 保存生成元数据 metadata_path self.output_dir / generation_metadata.json metadata {