当前位置:   article > 正文

利用Stable Diffusion Web UI API实现高级图像生成

利用Stable Diffusion Web UI API实现高级图像生成

下面代码是一个 Python 脚本,用于与 Stable Diffusion 模型的 Web UI 服务器进行交互,实现文本到图像(txt2img)和图像到图像(img2img)的转换。这个脚本展示了如何通过编程方式使用 API 来生成和修改图像,这在自动化图像生成和处理的应用中非常有价值。

  1. from datetime import datetime
  2. import urllib.request
  3. import base64
  4. import json
  5. import time
  6. import os
  7. # 文档https://github.com/AUTOMATIC1111/stable-diffusion-webui/wiki/API
  8. webui_server_url = '' # 输入api
  9. out_dir = 'api_out'
  10. out_dir_t2i = os.path.join(out_dir, 'txt2img')
  11. out_dir_i2i = os.path.join(out_dir, 'img2img')
  12. os.makedirs(out_dir_t2i, exist_ok=True)
  13. os.makedirs(out_dir_i2i, exist_ok=True)
  14. def timestamp():
  15. return datetime.fromtimestamp(time.time()).strftime("%Y%m%d-%H%M%S")
  16. def encode_file_to_base64(path):
  17. with open(path, 'rb') as file:
  18. return base64.b64encode(file.read()).decode('utf-8')
  19. def decode_and_save_base64(base64_str, save_path):
  20. with open(save_path, "wb") as file:
  21. file.write(base64.b64decode(base64_str))
  22. def call_api(api_endpoint, **payload):
  23. data = json.dumps(payload).encode('utf-8')
  24. request = urllib.request.Request(
  25. f'{webui_server_url}/{api_endpoint}',
  26. headers={'Content-Type': 'application/json'},
  27. data=data,
  28. )
  29. response = urllib.request.urlopen(request)
  30. return json.loads(response.read().decode('utf-8'))
  31. def call_txt2img_api(**payload):
  32. response = call_api('sdapi/v1/txt2img', **payload)
  33. for index, image in enumerate(response.get('images')):
  34. save_path = os.path.join(out_dir_t2i, f'txt2img-{timestamp()}-{index}.png')
  35. decode_and_save_base64(image, save_path)
  36. def call_img2img_api(**payload):
  37. response = call_api('sdapi/v1/img2img', **payload)
  38. for index, image in enumerate(response.get('images')):
  39. save_path = os.path.join(out_dir_i2i, f'img2img-{timestamp()}-{index}.png')
  40. decode_and_save_base64(image, save_path)
  41. if __name__ == '__main__':
  42. payload = {
  43. "prompt": "masterpiece, (best quality:1.1), 1girl <lora:lora_model:1>", # extra networks also in prompts
  44. "negative_prompt": "",
  45. "seed": 1,
  46. "steps": 20,
  47. "width": 512,
  48. "height": 512,
  49. "cfg_scale": 7,
  50. "sampler_name": "DPM++ 2M Karras",
  51. "n_iter": 1,
  52. "batch_size": 1,
  53. # x/y/z图的参数示例
  54. # "script_name": "x/y/z plot",
  55. # "script_args": [
  56. # 1,
  57. # "10,20",
  58. # [],
  59. # 0,
  60. # "",
  61. # [],
  62. # 0,
  63. # "",
  64. # [],
  65. # True,
  66. # True,
  67. # False,
  68. # False,
  69. # 0,
  70. # False
  71. # ],
  72. # Refiner和ControlNet的示例参数
  73. # "alwayson_scripts": {
  74. # "ControlNet": {
  75. # "args": [
  76. # {
  77. # "batch_images": "",
  78. # "control_mode": "Balanced",
  79. # "enabled": True,
  80. # "guidance_end": 1,
  81. # "guidance_start": 0,
  82. # "image": {
  83. # "image": encode_file_to_base64(r"B:\path\to\control\img.png"),
  84. # "mask": None # base64, None when not need
  85. # },
  86. # "input_mode": "simple",
  87. # "is_ui": True,
  88. # "loopback": False,
  89. # "low_vram": False,
  90. # "model": "control_v11p_sd15_canny [d14c016b]",
  91. # "module": "canny",
  92. # "output_dir": "",
  93. # "pixel_perfect": False,
  94. # "processor_res": 512,
  95. # "resize_mode": "Crop and Resize",
  96. # "threshold_a": 100,
  97. # "threshold_b": 200,
  98. # "weight": 1
  99. # }
  100. # ]
  101. # },
  102. # "Refiner": {
  103. # "args": [
  104. # True,
  105. # "sd_xl_refiner_1.0",
  106. # 0.5
  107. # ]
  108. # }
  109. # },
  110. # "enable_hr": True,
  111. # "hr_upscaler": "R-ESRGAN 4x+ Anime6B",
  112. # "hr_scale": 2,
  113. # "denoising_strength": 0.5,
  114. # "styles": ['style 1', 'style 2'],
  115. # "override_settings": {
  116. # 'sd_model_checkpoint': "sd_xl_base_1.0", # this can use to switch sd model
  117. # },
  118. }
  119. call_txt2img_api(**payload)
  120. init_images = [
  121. encode_file_to_base64("output.png"),
  122. # encode_file_to_base64(r"B:\path\to\img_2.png"),
  123. # "https://image.can/also/be/a/http/url.png",
  124. ]
  125. batch_size = 2
  126. payload = {
  127. "prompt": "1girl, blue hair",
  128. "seed": 1,
  129. "steps": 20,
  130. "width": 512,
  131. "height": 512,
  132. "denoising_strength": 0.5,
  133. "n_iter": 1,
  134. "init_images": init_images,
  135. "batch_size": batch_size if len(init_images) == 1 else len(init_images),
  136. # "mask": encode_file_to_base64(r"B:\path\to\mask.png")
  137. }
  138. # if len(init_images) > 1 then batch_size should be == len(init_images)
  139. # else if len(init_images) == 1 then batch_size can be any value int >= 1
  140. call_img2img_api(**payload)
  141. # there exist a useful extension that allows converting of webui calls to api payload
  142. # particularly useful when you wish setup arguments of extensions and scripts
  143. # https://github.com/huchenlei/sd-webui-api-payload-display

代码解析

  1. 导入必要的库: 使用datetime、urllib.request、base64、json、time和os等库来处理日期时间、网络请求、文件编码、JSON处理、时间和文件系统操作。
  2. 初始化输出目录: 创建两个输出目录out_dir_t2i和out_dir_i2i,分别用于存储文本到图像和图像到图像的结果。
  3. 定义辅助函数: timestamp(): 生成当前时间戳。 encode_file_to_base64(path): 将文件编码为Base64字符串。 decode_and_save_base64(base64_str, save_path): 将Base64字符串解码并保存为文件。
  4. 定义API调用函数: call_api(api_endpoint, **payload): 发送请求到指定的API端点。 call_txt2img_api(**payload): 调用文本到图像的API。 call_img2img_api(**payload): 调用图像到图像的API。
  5. 实际的API调用示例: 在脚本的主体部分,提供了用于调用文本到图像和图像到图像API的示例payload。

代码的实际应用

这个脚本在AI图像生成和处理的领域具有广泛的应用,例如:

  • 创意艺术和设计:艺术家和设计师可以使用这个脚本来自动化地生成创意图像。
  • 数据可视化:数据科学家可以利用图像到图像的功能来增强数据可视化效果。
  • 媒体和娱乐:媒体公司可以用它来快速生成或修改图像,用于社交媒体、广告等。

应用场景

  • 自动化内容生成:自动创建图像内容,用于社交媒体、网站等。
  • 图像编辑和增强:修改已有图像,加入新元素或改变风格。

声明:本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有侵权的内容,请联系我们。转载请注明出处:【wpsshop博客】
推荐阅读
相关标签
  

闽ICP备14008679号