news 2026/8/29 5:19:13

LiuJuan20260223Zimage自动化生成教程:Python脚本实现国风图片批量创作

作者头像

张小明

前端开发工程师

1.2k 24
文章封面图
LiuJuan20260223Zimage自动化生成教程:Python脚本实现国风图片批量创作

LiuJuan20260223Zimage自动化生成教程:Python脚本实现国风图片批量创作

1. 引言:告别手动点击,拥抱自动化创作

如果你已经体验过LiuJuan20260223Zimage模型的Web界面,可能会发现一个问题:每次生成图片都需要打开浏览器、输入提示词、调整参数、点击按钮。生成一两张图还好,但如果需要批量创作几十甚至上百张国风图片,这种手动操作方式就显得效率低下了。

想象一下,你正在为一个国风游戏设计角色立绘,或者为文创产品批量生成宣传素材,手动操作不仅耗时耗力,还容易出错。这时候,自动化脚本就成了你的得力助手。

本文将带你从零开始,编写一个Python脚本,实现LiuJuan20260223Zimage模型的自动化调用。无论你是想批量生成图片素材,还是想把AI绘画功能集成到自己的应用中,这个方法都能帮你节省大量时间,让创作过程更加高效流畅。

2. 环境准备:搭建你的自动化工作台

在开始编写脚本之前,我们需要确保环境已经准备就绪。这个过程很简单,只需要几个步骤。

2.1 确认模型服务状态

首先,确保你的LiuJuan20260223Zimage模型服务已经正常启动。根据镜像文档,模型提供了两个访问端口:

  • WebUI界面:通过7860端口访问,适合手动操作和测试
  • API接口:通过8000端口访问,适合程序化调用

你可以通过以下命令检查服务状态:

# 检查FastAPI服务(API接口) curl http://localhost:8000/docs # 或者检查Gradio服务(Web界面) curl http://localhost:7860

如果看到正常的响应,说明服务已经启动成功。

2.2 安装必要的Python库

我们需要安装几个Python库来编写自动化脚本。打开终端,执行以下命令:

pip install requests pillow

简单解释一下这两个库的作用:

  • requests:用于发送HTTP请求,调用模型的API接口
  • Pillow:Python的图像处理库,用于保存和处理生成的图片

如果你还没有安装Python,建议使用Python 3.8或更高版本。安装完成后,可以通过以下命令验证:

import requests from PIL import Image print("库安装成功!")

3. 基础脚本:实现单张图片生成

让我们从一个最简单的脚本开始,了解API调用的基本流程。这个脚本会生成一张国风图片并保存到本地。

3.1 理解API接口

LiuJuan20260223Zimage的API接口遵循RESTful风格,我们可以通过发送HTTP POST请求来生成图片。根据文档,API地址是:

http://localhost:8000/generate

请求需要包含以下参数:

  • prompt:正面提示词,描述你想要生成的画面
  • negative_prompt:负面提示词,排除不想要的内容
  • width/height:图片尺寸
  • num_inference_steps:推理步数
  • guidance_scale:引导系数
  • lora_version:LoRA模型版本

3.2 编写第一个自动化脚本

创建一个新文件,命名为generate_single.py,然后输入以下代码:

import requests import json import base64 from io import BytesIO from PIL import Image import time def generate_single_image(): """ 生成单张国风图片 """ # 1. 设置API地址 api_url = "http://localhost:8000/generate" # 2. 准备请求参数 # 这些参数对应Web界面上的设置 payload = { "prompt": "oriental beauty, elegant Chinese woman, flowing hanfu dress, soft lighting, ink wash painting style", "negative_prompt": "western features, blonde hair, blue eyes, low quality, blurry, distorted", "width": 768, "height": 768, "num_inference_steps": 20, "guidance_scale": 7.5, "lora_version": "LiuJuan20260223Zimage_25" # 使用第25轮训练的LoRA版本 } # 3. 设置请求头 headers = { "Content-Type": "application/json", "Accept": "application/json" } print("开始生成图片...") print(f"提示词: {payload['prompt']}") print(f"使用模型: {payload['lora_version']}") try: # 4. 发送请求 start_time = time.time() response = requests.post(api_url, json=payload, headers=headers, timeout=60) end_time = time.time() # 5. 检查响应状态 if response.status_code == 200: print(f"生成成功!耗时: {end_time - start_time:.2f}秒") # 6. 解析响应数据 result = response.json() # 7. 获取base64编码的图片数据 if "image" in result: # 图片数据是base64编码的字符串 image_data_base64 = result["image"] # 解码base64数据 image_data = base64.b64decode(image_data_base64) # 8. 创建图片对象 image = Image.open(BytesIO(image_data)) # 9. 保存图片 timestamp = int(time.time()) filename = f"liujuan_generated_{timestamp}.png" image.save(filename) print(f"图片已保存: {filename}") # 10. 显示图片信息 print(f"图片尺寸: {image.size}") print(f"图片格式: {image.format}") # 可选:显示图片 # image.show() return filename else: print("响应中没有找到图片数据") return None else: print(f"生成失败,状态码: {response.status_code}") print(f"错误信息: {response.text}") return None except requests.exceptions.Timeout: print("请求超时,请检查服务是否正常运行") return None except requests.exceptions.ConnectionError: print("连接失败,请检查API地址是否正确") return None except Exception as e: print(f"生成过程中发生错误: {e}") return None if __name__ == "__main__": # 执行生成 result_file = generate_single_image() if result_file: print(f"图片生成完成,文件保存在: {result_file}") else: print("图片生成失败,请检查以上错误信息")

3.3 运行脚本并查看结果

保存文件后,在终端中运行:

python generate_single.py

如果一切正常,你会看到类似下面的输出:

开始生成图片... 提示词: oriental beauty, elegant Chinese woman, flowing hanfu dress, soft lighting, ink wash painting style 使用模型: LiuJuan20260223Zimage_25 生成成功!耗时: 8.45秒 图片已保存: liujuan_generated_1700000000.png 图片尺寸: (768, 768) 图片格式: PNG 图片生成完成,文件保存在: liujuan_generated_1700000000.png

打开生成的图片文件,你应该能看到一张精美的国风人物图片。

4. 进阶脚本:封装成可复用的类

单个脚本虽然能用,但不够灵活。让我们把它封装成一个类,方便在不同的项目中复用。

4.1 创建图片生成器类

新建一个文件liujuan_generator.py,编写以下代码:

import requests import json import base64 import time from io import BytesIO from PIL import Image from typing import List, Optional, Dict, Any import os class LiuJuanImageGenerator: """ LiuJuan20260223Zimage图片生成器 这个类封装了与LiuJuan模型API的交互,提供了简单易用的接口 用于生成国风风格的图片。 """ def __init__(self, base_url: str = "http://localhost:8000"): """ 初始化图片生成器 Args: base_url: API服务的基础地址,默认是本地服务的8000端口 """ self.base_url = base_url self.generation_url = f"{base_url}/generate" # 默认参数配置 self.default_params = { "width": 768, "height": 768, "num_inference_steps": 20, "guidance_scale": 7.5, "lora_version": "LiuJuan20260223Zimage_25" } # 创建输出目录 self.output_dir = "generated_images" os.makedirs(self.output_dir, exist_ok=True) print(f"LiuJuan图片生成器初始化完成") print(f"API地址: {self.generation_url}") print(f"输出目录: {self.output_dir}") def generate(self, prompt: str, negative_prompt: str = "", width: int = None, height: int = None, num_inference_steps: int = None, guidance_scale: float = None, lora_version: str = None, save: bool = True, filename: str = None) -> Optional[Image.Image]: """ 生成单张图片 Args: prompt: 正面提示词,描述想要生成的画面 negative_prompt: 负面提示词,排除不想要的内容 width: 图片宽度,默认768 height: 图片高度,默认768 num_inference_steps: 推理步数,默认20 guidance_scale: 引导系数,默认7.5 lora_version: LoRA版本,默认LiuJuan20260223Zimage_25 save: 是否保存到文件,默认True filename: 保存的文件名,不指定则自动生成 Returns: PIL.Image对象,如果生成失败则返回None """ # 1. 准备请求参数 params = self.default_params.copy() # 更新用户指定的参数 if width is not None: params["width"] = width if height is not None: params["height"] = height if num_inference_steps is not None: params["num_inference_steps"] = num_inference_steps if guidance_scale is not None: params["guidance_scale"] = guidance_scale if lora_version is not None: params["lora_version"] = lora_version params["prompt"] = prompt params["negative_prompt"] = negative_prompt # 2. 记录开始时间 start_time = time.time() try: # 3. 发送生成请求 print(f"正在生成图片: {prompt[:50]}...") response = requests.post( self.generation_url, json=params, headers={"Content-Type": "application/json"}, timeout=60 ) # 4. 检查响应 if response.status_code != 200: print(f"生成失败,状态码: {response.status_code}") print(f"错误信息: {response.text}") return None # 5. 解析响应数据 result = response.json() if "image" not in result: print("响应中没有找到图片数据") return None # 6. 解码图片数据 image_data = base64.b64decode(result["image"]) image = Image.open(BytesIO(image_data)) # 7. 计算耗时 elapsed_time = time.time() - start_time # 8. 保存图片 if save: if filename is None: # 自动生成文件名 timestamp = int(time.time()) # 清理提示词中的特殊字符 safe_prompt = "".join(c for c in prompt[:30] if c.isalnum() or c in (' ', '_', '-')).strip() safe_prompt = safe_prompt.replace(' ', '_') filename = f"{safe_prompt}_{timestamp}.png" # 确保文件名在输出目录中 filepath = os.path.join(self.output_dir, filename) image.save(filepath) print(f"图片已保存: {filepath}") print(f"生成成功!尺寸: {image.size}, 耗时: {elapsed_time:.2f}秒") return image except requests.exceptions.Timeout: print("请求超时,请检查服务是否正常运行") return None except requests.exceptions.ConnectionError: print(f"连接失败,请检查服务地址: {self.generation_url}") return None except json.JSONDecodeError: print("响应数据格式错误") return None except Exception as e: print(f"生成过程中发生错误: {e}") return None def batch_generate(self, prompts: List[str], negative_prompts: List[str] = None, **kwargs) -> List[Optional[Image.Image]]: """ 批量生成图片 Args: prompts: 提示词列表 negative_prompts: 负面提示词列表,如果不指定则使用空字符串 **kwargs: 其他生成参数,会传递给generate方法 Returns: 生成的图片列表,失败的项目为None """ results = [] if negative_prompts is None: negative_prompts = [""] * len(prompts) print(f"开始批量生成 {len(prompts)} 张图片...") for i, (prompt, negative_prompt) in enumerate(zip(prompts, negative_prompts)): print(f"\n[{i+1}/{len(prompts)}] 生成中: {prompt[:50]}...") image = self.generate( prompt=prompt, negative_prompt=negative_prompt, **kwargs ) results.append(image) # 添加延迟,避免请求过于频繁 if i < len(prompts) - 1: time.sleep(1) success_count = sum(1 for img in results if img is not None) print(f"\n批量生成完成,成功 {success_count}/{len(prompts)} 张") return results def test_connection(self) -> bool: """ 测试与API服务的连接 Returns: 连接是否成功 """ try: # 尝试访问API文档页面 docs_url = f"{self.base_url}/docs" response = requests.get(docs_url, timeout=5) return response.status_code == 200 except: return False def get_available_lora_versions(self) -> List[str]: """ 获取可用的LoRA版本列表 注意:这个方法需要API支持版本查询功能 如果API不支持,可以手动指定版本列表 Returns: LoRA版本列表 """ # 根据文档,LiuJuan模型有25个版本 return [f"LiuJuan20260223Zimage_{i}" for i in range(1, 26)] def generate_with_style(self, base_prompt: str, style: str, **kwargs) -> Optional[Image.Image]: """ 生成指定风格的图片 Args: base_prompt: 基础提示词 style: 风格描述(如:水墨风格、工笔风格等) **kwargs: 其他生成参数 Returns: 生成的图片 """ full_prompt = f"{base_prompt}, {style}" return self.generate(prompt=full_prompt, **kwargs)

4.2 使用生成器类

现在我们可以使用这个类来生成图片了。创建一个新的脚本use_generator.py

from liujuan_generator import LiuJuanImageGenerator import time def main(): # 1. 创建生成器实例 generator = LiuJuanImageGenerator() # 2. 测试连接 if not generator.test_connection(): print("无法连接到LiuJuan模型服务,请检查服务是否启动") print(f"尝试访问: {generator.base_url}/docs") return print("连接成功!") # 3. 生成单张图片 print("\n=== 生成单张图片 ===") image = generator.generate( prompt="一位穿着汉服的女子,站在江南水乡的桥上,细雨蒙蒙,水墨画风格", negative_prompt="西方面孔,金发,现代服装,照片风格", width=768, height=768, lora_version="LiuJuan20260223Zimage_25" ) if image: print("单张图片生成成功!") # 4. 批量生成图片 print("\n=== 批量生成图片 ===") prompts = [ "唐代宫廷仕女,华丽服饰,工笔重彩风格", "竹林七贤,文人雅士,水墨写意风格", "武侠剑客,月下独酌,武侠漫画风格", "江南园林,亭台楼阁,青绿山水风格" ] negative_prompts = [ "现代建筑,西方人物,照片风格", "彩色照片,写实风格,低质量", "卡通风格,儿童画,简笔画", "西方油画,抽象画,模糊" ] images = generator.batch_generate( prompts=prompts, negative_prompts=negative_prompts, width=512, # 使用小尺寸加快生成速度 height=512 ) # 5. 尝试不同LoRA版本 print("\n=== 尝试不同LoRA版本 ===") # 获取可用的版本 versions = generator.get_available_lora_versions() print(f"可用版本: {versions[-5:]}") # 显示最后5个版本 # 使用不同版本生成同一主题的图片 test_prompt = "古典美人,执扇而立,庭院深深" for version in versions[20:23]: # 尝试21-23版本 print(f"\n使用版本: {version}") image = generator.generate( prompt=test_prompt, lora_version=version, filename=f"version_test_{version}.png" ) time.sleep(2) # 版本切换需要时间 print("\n所有任务完成!") if __name__ == "__main__": main()

运行这个脚本,你会看到生成器依次执行单张生成、批量生成和版本测试任务。

5. 实战应用:创建完整的图片生成流水线

现在我们已经有了基础的生成功能,让我们创建一个更完整的应用场景:为电商产品批量生成国风宣传图。

5.1 电商图片生成脚本

创建一个新文件ecommerce_generator.py

from liujuan_generator import LiuJuanImageGenerator import pandas as pd from datetime import datetime import os class EcommerceImageGenerator: """ 电商图片生成器 专门为电商场景设计的图片生成工具, 可以批量生成商品宣传图、场景图等。 """ def __init__(self): self.generator = LiuJuanImageGenerator() self.template_dir = "templates" self.output_dir = "ecommerce_output" # 创建目录 os.makedirs(self.template_dir, exist_ok=True) os.makedirs(self.output_dir, exist_ok=True) # 预定义的风格模板 self.style_templates = { "水墨风格": "水墨画风格,淡雅清新,留白意境", "工笔风格": "工笔画风格,细腻精致,色彩鲜艳", "年画风格": "传统年画风格,喜庆吉祥,色彩对比强烈", "青绿山水": "青绿山水风格,色彩明丽,层次丰富", "文人画": "文人画风格,简约雅致,诗书画印" } # 预定义的场景模板 self.scene_templates = { "产品展示": "产品摆放在古典桌案上,背景是屏风或窗棂", "使用场景": "人物正在使用产品,场景是古典庭院或室内", "意境表达": "产品与自然元素结合,如梅花、竹子、山水", "文化符号": "产品与传统纹样、书法、印章结合" } def generate_product_images(self, product_name, product_type, num_images=4): """ 为单个产品生成多张宣传图 Args: product_name: 产品名称 product_type: 产品类型(如:茶叶、瓷器、服饰等) num_images: 生成图片数量 Returns: 生成的图片文件路径列表 """ print(f"\n开始为产品生成图片: {product_name} ({product_type})") # 根据产品类型选择不同的提示词模板 prompt_templates = self._get_prompt_templates(product_type) generated_files = [] for i in range(min(num_images, len(prompt_templates))): # 构建提示词 base_prompt = prompt_templates[i] full_prompt = f"{product_name},{base_prompt}" # 选择风格 style_key = list(self.style_templates.keys())[i % len(self.style_templates)] style_desc = self.style_templates[style_key] final_prompt = f"{full_prompt},{style_desc}" print(f"\n生成第 {i+1}/{num_images} 张") print(f"提示词: {final_prompt}") # 生成文件名 timestamp = datetime.now().strftime("%Y%m%d_%H%M%S") filename = f"{product_name}_{style_key}_{timestamp}_{i+1}.png" filepath = os.path.join(self.output_dir, filename) # 生成图片 image = self.generator.generate( prompt=final_prompt, negative_prompt="现代元素,西方风格,低质量,模糊", width=1024, height=768, # 适合电商横幅的比例 filename=filename ) if image: generated_files.append(filepath) print(f"已生成: {filename}") return generated_files def _get_prompt_templates(self, product_type): """ 根据产品类型获取提示词模板 Args: product_type: 产品类型 Returns: 提示词模板列表 """ # 不同产品类型的提示词模板 templates = { "茶叶": [ "茶叶在青瓷茶具中,热气袅袅,茶汤清澈", "茶艺师正在泡茶,动作优雅,环境清幽", "茶园景色,云雾缭绕,采茶姑娘在劳作", "茶与古典诗词结合,文人品茶场景" ], "瓷器": [ "青花瓷瓶,花纹精致,光线柔和", "瓷器摆放在博古架上,背景是水墨山水", "制作瓷器的工匠,专注拉坯,传统工艺", "瓷器细节特写,釉色温润,质感细腻" ], "服饰": [ "模特穿着汉服,姿态优雅,背景是古典建筑", "服饰细节展示,刺绣精美,布料质感", "穿着场景,参加传统节日或仪式", "与传统配饰搭配,如发簪、团扇、玉佩" ], "文房四宝": [ "笔墨纸砚摆放整齐,书卷气息浓厚", "书法家正在挥毫,墨迹淋漓", "文房用品细节,雕刻精致,材质优良", "与古典书房环境结合,书架、窗棂、盆景" ] } # 如果产品类型不在预设中,使用通用模板 if product_type not in templates: return [ "产品展示,古典美学,传统元素", "使用场景,文化氛围,意境表达", "细节特写,工艺精湛,质感表现", "与传统文化的结合,故事性画面" ] return templates[product_type] def batch_generate_from_csv(self, csv_file): """ 从CSV文件批量生成产品图片 Args: csv_file: CSV文件路径,包含产品信息 Returns: 生成统计信息 """ try: # 读取CSV文件 df = pd.read_csv(csv_file) print(f"从 {csv_file} 读取了 {len(df)} 个产品") results = [] for _, row in df.iterrows(): product_name = row.get('product_name', '未知产品') product_type = row.get('product_type', '其他') num_images = row.get('num_images', 4) print(f"\n处理产品: {product_name}") # 生成图片 files = self.generate_product_images(product_name, product_type, num_images) results.append({ 'product_name': product_name, 'product_type': product_type, 'generated_files': files, 'success_count': len(files) }) # 生成统计报告 self._generate_report(results) return results except Exception as e: print(f"处理CSV文件时出错: {e}") return [] def _generate_report(self, results): """生成统计报告""" total_products = len(results) total_images = sum(len(r['generated_files']) for r in results) print("\n" + "="*50) print("生成统计报告") print("="*50) print(f"总产品数: {total_products}") print(f"总图片数: {total_images}") # 按产品类型统计 type_stats = {} for result in results: product_type = result['product_type'] if product_type not in type_stats: type_stats[product_type] = 0 type_stats[product_type] += result['success_count'] print("\n按产品类型统计:") for product_type, count in type_stats.items(): print(f" {product_type}: {count} 张") # 保存报告到文件 report_file = os.path.join(self.output_dir, "generation_report.txt") with open(report_file, 'w', encoding='utf-8') as f: f.write(f"生成时间: {datetime.now().strftime('%Y-%m-%d %H:%M:%S')}\n") f.write(f"总产品数: {total_products}\n") f.write(f"总图片数: {total_images}\n\n") f.write("详细信息:\n") for result in results: f.write(f"\n产品: {result['product_name']} ({result['product_type']})\n") f.write(f"生成图片数: {result['success_count']}\n") for file in result['generated_files']: f.write(f" - {os.path.basename(file)}\n") print(f"\n详细报告已保存: {report_file}") # 使用示例 def main(): # 创建生成器 ecommerce_gen = EcommerceImageGenerator() # 检查连接 if not ecommerce_gen.generator.test_connection(): print("无法连接到模型服务") return # 示例1:为单个产品生成图片 print("示例1:为单个产品生成图片") files = ecommerce_gen.generate_product_images( product_name="西湖龙井", product_type="茶叶", num_images=3 ) print(f"\n生成完成,文件列表:") for file in files: print(f" - {file}") # 示例2:从CSV批量生成(需要先创建CSV文件) print("\n" + "="*50) print("示例2:从CSV批量生成") # 创建示例CSV文件 sample_data = [ {"product_name": "青花瓷瓶", "product_type": "瓷器", "num_images": 2}, {"product_name": "丝绸汉服", "product_type": "服饰", "num_images": 3}, {"product_name": "端砚", "product_type": "文房四宝", "num_images": 2} ] df = pd.DataFrame(sample_data) csv_file = "sample_products.csv" df.to_csv(csv_file, index=False, encoding='utf-8-sig') print(f"已创建示例CSV文件: {csv_file}") # 批量生成 results = ecommerce_gen.batch_generate_from_csv(csv_file) print("\n批量生成完成!") if __name__ == "__main__": main()

5.2 创建产品信息CSV文件

为了让批量生成更加方便,我们可以创建一个CSV文件来管理产品信息。创建一个文件products.csv

product_name,product_type,num_images,description 西湖龙井明前茶,茶叶,4,顶级明前龙井,清香甘醇 景德镇青花瓷,瓷器,3,传统青花瓷,手工绘制 苏绣真丝汉服,服饰,4,手工苏绣,真丝面料 歙县徽墨,文房四宝,2,传统徽墨,墨色如漆 紫砂茶具,瓷器,3,宜兴紫砂,手工制作

然后创建一个脚本batch_from_csv.py

from ecommerce_generator import EcommerceImageGenerator def main(): # 创建生成器 generator = EcommerceImageGenerator() # 检查连接 if not generator.generator.test_connection(): print("请先启动LiuJuan模型服务") return # 从CSV文件批量生成 csv_file = "products.csv" print(f"开始从 {csv_file} 批量生成产品图片...") print("="*60) results = generator.batch_generate_from_csv(csv_file) print("\n" + "="*60) print("批量生成任务完成!") print(f"查看生成结果: {generator.output_dir}/") if __name__ == "__main__": main()

运行这个脚本,系统会自动读取CSV文件中的产品信息,为每个产品生成指定数量的国风宣传图。

6. 高级技巧:优化生成效果与性能

在实际使用中,我们可能需要对生成过程进行优化。这里分享一些实用的技巧。

6.1 提示词优化技巧

好的提示词能显著提升生成质量。创建一个提示词优化工具:

class PromptOptimizer: """ 提示词优化工具 帮助构建更有效的提示词,提升生成质量 """ def __init__(self): # 国风相关的质量提升词 self.quality_boosters = [ "masterpiece", "best quality", "high resolution", "detailed", "intricate details", "sharp focus", "professional" ] # 国风风格描述词 self.chinese_styles = [ "Chinese ink painting style", "traditional Chinese painting", "gongbi style", # 工笔 "xieyi style", # 写意 "watercolor ink style", "classical Chinese art" ] # 光线和氛围词 self.lighting_terms = [ "soft lighting", "dramatic lighting", "rim lighting", "golden hour", "misty", "hazy", "atmospheric" ] # 构图和视角词 self.composition_terms = [ "dynamic angle", "low angle", "high angle", "close-up", "full body", "medium shot", "rule of thirds", "balanced composition" ] def optimize_prompt(self, base_prompt, style="水墨", quality_level="high"): """ 优化提示词 Args: base_prompt: 基础提示词 style: 风格(水墨、工笔、青绿等) quality_level: 质量级别(low, medium, high) Returns: 优化后的提示词 """ # 根据风格选择描述词 style_mapping = { "水墨": "Chinese ink painting style, monochrome, expressive brush strokes", "工笔": "gongbi style, detailed, colorful, fine brushwork", "青绿": "qinglu shanshui style, blue-green landscape, mineral pigments", "年画": "Chinese New Year painting style, bright colors, folk art", "文人画": "literati painting style, minimalistic, poetic" } style_desc = style_mapping.get(style, "Chinese traditional painting style") # 根据质量级别选择质量词 quality_mapping = { "low": [], "medium": ["high quality", "detailed"], "high": self.quality_boosters[:3] } quality_terms = quality_mapping.get(quality_level, ["high quality"]) # 随机选择光线和构图词(增加多样性) import random lighting = random.choice(self.lighting_terms) composition = random.choice(self.composition_terms) # 构建完整提示词 components = [ base_prompt, style_desc, lighting, composition ] + quality_terms # 移除空组件并连接 components = [c for c in components if c] optimized_prompt = ", ".join(components) return optimized_prompt def create_negative_prompt(self, exclude_western=True, exclude_modern=True): """ 创建负面提示词 Args: exclude_western: 是否排除西方元素 exclude_modern: 是否排除现代元素 Returns: 负面提示词 """ negative_terms = [ "low quality", "blurry", "distorted", "deformed", "bad anatomy", "poor details", "ugly" ] if exclude_western: negative_terms.extend([ "western", "European", "American", "blonde hair", "blue eyes", "Caucasian" ]) if exclude_modern: negative_terms.extend([ "modern", "contemporary", "photograph", "photo", "3D render", "CGI" ]) return ", ".join(negative_terms) def generate_prompt_variations(self, base_prompt, num_variations=3): """ 生成提示词变体 Args: base_prompt: 基础提示词 num_variations: 变体数量 Returns: 提示词变体列表 """ styles = ["水墨", "工笔", "青绿", "年画", "文人画"] quality_levels = ["medium", "high"] variations = [] for i in range(num_variations): style = styles[i % len(styles)] quality = quality_levels[i % len(quality_levels)] optimized = self.optimize_prompt(base_prompt, style, quality) variations.append(optimized) return variations # 使用示例 def test_prompt_optimizer(): optimizer = PromptOptimizer() base_prompt = "一位古典女子在花园中" print("基础提示词:", base_prompt) print("\n优化后的提示词:") # 生成不同风格的变体 variations = optimizer.generate_prompt_variations(base_prompt, 3) for i, variation in enumerate(variations, 1): print(f"\n变体 {i}:") print(variation) # 生成负面提示词 negative_prompt = optimizer.create_negative_prompt() print(f"\n负面提示词:") print(negative_prompt) return variations, negative_prompt

6.2 性能优化技巧

当需要生成大量图片时,性能优化很重要:

import concurrent.futures import threading from queue import Queue import time class BatchGeneratorWithQueue: """ 使用队列的批量生成器 支持多线程生成,提高效率 """ def __init__(self, max_workers=2): self.generator = LiuJuanImageGenerator() self.max_workers = max_workers self.result_queue = Queue() self.error_queue = Queue() def worker(self, prompt, negative_prompt, index): """工作线程函数""" try: print(f"线程 {threading.current_thread().name} 开始生成第 {index} 张图片") image = self.generator.generate( prompt=prompt, negative_prompt=negative_prompt, save=False # 不在生成时保存,统一保存 ) if image: # 生成文件名 timestamp = int(time.time()) filename = f"batch_{timestamp}_{index}.png" self.result_queue.put((index, image, filename)) print(f"线程 {threading.current_thread().name} 完成第 {index} 张图片") else: self.error_queue.put((index, "生成失败")) except Exception as e: self.error_queue.put((index, str(e))) def batch_generate_parallel(self, prompts, negative_prompts=None): """ 并行批量生成 Args: prompts: 提示词列表 negative_prompts: 负面提示词列表 Returns: 生成的图片列表 """ if negative_prompts is None: negative_prompts = [""] * len(prompts) print(f"开始并行生成 {len(prompts)} 张图片,使用 {self.max_workers} 个线程") start_time = time.time() # 使用线程池 with concurrent.futures.ThreadPoolExecutor(max_workers=self.max_workers) as executor: # 提交所有任务 futures = [] for i, (prompt, negative_prompt) in enumerate(zip(prompts, negative_prompts)): future = executor.submit(self.worker, prompt, negative_prompt, i) futures.append(future) # 等待所有任务完成 concurrent.futures.wait(futures) # 收集结果 results = [] while not self.result_queue.empty(): index, image, filename = self.result_queue.get() # 保存图片 filepath = os.path.join("batch_output", filename) os.makedirs("batch_output", exist_ok=True) image.save(filepath) results.append({ 'index': index, 'image': image, 'filename': filename, 'filepath': filepath }) # 处理错误 errors = [] while not self.error_queue.empty(): index, error = self.error_queue.get() errors.append((index, error)) elapsed_time = time.time() - start_time print(f"\n并行生成完成") print(f"总耗时: {elapsed_time:.2f}秒") print(f"平均每张: {elapsed_time/len(prompts):.2f}秒") print(f"成功: {len(results)} 张") print(f"失败: {len(errors)} 张") if errors: print("\n失败详情:") for index, error in errors: print(f" 第 {index} 张: {error}") return results # 使用示例 def test_parallel_generation(): # 准备测试数据 prompts = [ "水墨山水,远山近水,雾气缭绕", "工笔花鸟,精细描绘,色彩鲜艳", "古典建筑,飞檐翘角,红墙黄瓦", "传统节日,舞龙舞狮,热闹喜庆", "文人雅集,吟诗作画,竹林七贤", "古代服饰,华丽汉服,精致配饰", "神话传说,仙女下凡,祥云缭绕", "历史人物,古代将军,战场英姿" ] # 创建生成器 batch_gen = BatchGeneratorWithQueue(max_workers=3) # 并行生成 results = batch_gen.batch_generate_parallel(prompts) print(f"\n生成完成,图片保存在 batch_output/ 目录") return results

7. 总结

通过本文的学习,你已经掌握了使用Python脚本自动化调用LiuJuan20260223Zimage模型的方法。让我们回顾一下关键要点:

7.1 核心技能掌握

  1. 基础调用:学会了如何通过requests库调用模型的API接口,实现单张图片生成
  2. 类封装:将生成功能封装成可复用的类,方便在不同项目中调用
  3. 批量处理:实现了批量生成功能,可以一次性生成多张图片
  4. 实战应用:创建了电商图片生成流水线,能够根据产品信息自动生成宣传图
  5. 性能优化:学习了提示词优化和并行生成技巧,提升生成效率和质量

7.2 实际应用价值

自动化脚本带来的价值是显而易见的:

  • 效率提升:从手动点击到自动生成,处理100张图片的时间从几小时缩短到几分钟
  • 一致性保证:通过脚本控制参数,确保生成风格和质量的一致性
  • 可集成性:可以轻松将生成功能集成到现有系统中
  • 可扩展性:脚本可以根据需求灵活调整和扩展

7.3 下一步学习建议

掌握了基础之后,你可以继续探索以下方向:

  1. 参数调优实验:系统性地测试不同参数组合对生成效果的影响,找到最优配置
  2. 质量评估系统:开发自动化的图片质量评估工具,筛选出最佳生成结果
  3. 工作流集成:将图片生成与其他工具(如PS、Figma)结合,创建完整的设计工作流
  4. Web应用开发:基于Flask或FastAPI开发一个Web界面,让非技术人员也能使用
  5. 风格迁移研究:尝试将LiuJuan模型的国风风格应用到其他类型的图片上

7.4 注意事项提醒

在使用自动化脚本时,有几点需要注意:

  1. 服务稳定性:确保模型服务稳定运行,避免在生成过程中服务中断
  2. 资源管理:批量生成时注意显存使用,避免超出硬件限制
  3. 结果验证:定期检查生成结果,确保质量符合要求
  4. 版本控制:保存不同版本的提示词和参数配置,方便回溯和优化

自动化脚本不仅是一个技术工具,更是释放创造力的钥匙。通过编程,你可以将重复性的操作交给机器,让自己专注于更有价值的创意工作。希望本文能帮助你更好地利用LiuJuan20260223Zimage模型,创作出更多精彩的国风作品。


获取更多AI镜像

想探索更多AI镜像和应用场景?访问 CSDN星图镜像广场,提供丰富的预置镜像,覆盖大模型推理、图像生成、视频生成、模型微调等多个领域,支持一键部署。

版权声明: 本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如若内容造成侵权/违法违规/事实不符,请联系邮箱:809451989@qq.com进行投诉反馈,一经查实,立即删除!
网站建设 2026/8/21 9:52:54

IBM Granite时间序列预测新突破:FlowState R1模型5分钟快速部署指南

IBM Granite时间序列预测新突破&#xff1a;FlowState R1模型5分钟快速部署指南 时间序列预测是数据分析领域的重要分支&#xff0c;从电力负荷预测到销售趋势分析&#xff0c;从设备故障预警到金融市场波动&#xff0c;几乎每个行业都离不开对时间序列数据的洞察。然而&#…

作者头像 李华
网站建设 2026/8/21 12:09:11

时间序列预测新选择:Granite模型快速部署与ETT数据集测试

时间序列预测新选择&#xff1a;Granite模型快速部署与ETT数据集测试 最近在探索时间序列预测的新工具时&#xff0c;我发现了IBM开源的Granite TimeSeries FlowState R1模型。这个只有910万参数的轻量级模型&#xff0c;却能在电力负荷、温度监测等场景下实现相当不错的预测效…

作者头像 李华
网站建设 2026/8/25 22:14:38

FeHelper升级全攻略:从基础到进阶的迁移指南

FeHelper升级全攻略&#xff1a;从基础到进阶的迁移指南 【免费下载链接】FeHelper &#x1f60d;FeHelper--Web前端助手&#xff08;Awesome&#xff01;Chrome & Firefox & MS-Edge Extension, All in one Toolbox!&#xff09; 项目地址: https://gitcode.com/gh_…

作者头像 李华
网站建设 2026/8/21 18:08:28

AI印象派艺术工坊性能评测:4种风格渲染速度全方位对比

AI印象派艺术工坊性能评测&#xff1a;4种风格渲染速度全方位对比 1. 项目概述与评测背景 AI印象派艺术工坊是一个基于OpenCV计算摄影学算法的艺术风格迁移工具&#xff0c;它能够将普通照片快速转换为四种不同的艺术风格&#xff1a;素描、彩铅、油画和水彩。与依赖大型深度…

作者头像 李华
网站建设 2026/8/22 1:10:31

【Qt】QSemaphore信号量在生产者和消费者模式中的高效应用

1. 信号量&#xff1a;不只是个“红绿灯”&#xff0c;更是多线程的“调度员” 如果你刚开始接触多线程编程&#xff0c;听到“信号量”这个词可能会觉得有点抽象。别担心&#xff0c;我们可以先把它想象成一个停车场的管理员。假设你有一个固定车位的停车场&#xff08;比如10…

作者头像 李华