Python 使用 Stable Diffusion API 生成图片示例

在这里插入图片描述
在这里插入图片描述
代码:

import base64
import datetime
import json
import os

import requests


def submit_post(url: str, data: dict):
    """
    Submit a POST request to the given URL with the given data.
    :param url:  url
    :param data: data
    :return:  response
    """
    return requests.post(url, data=json.dumps(data))


def save_encoded_image(b64_image: str, output_path: str):
    """
    Save the given image to the given output path.
    :param b64_image:  base64 encoded image
    :param output_path:  output path
    :return:  None
    """
    # 判断当前目录下是否存在 output 文件夹,如果不存在则创建
    if not os.path.exists("output"):
        os.mkdir("output")
    timestamp = datetime.datetime.now().strftime("%Y%m%d%H%M%S")
    output_path = f"{output_path}_{timestamp}" + ".png"
    # 将文件放入当前目录下的 output 文件夹中
    output_path = f"output/{output_path}"
    with open(output_path, "wb") as f:
        f.write(base64.b64decode(b64_image))


def save_json_file(data: dict, output_path: str):
    """
    Save the given data to the given output path.
    :param data:  data
    :param output_path:  output path
    :return:  None
    """
    # 忽略 data 中的 images 字段
    data.pop('images')
    # 将 data 中的 info 字段转为 json 字符串,info 当前数据需要转义
    data['info'] = json.loads(data['info'])

    # 输出 data.info.infotexts
    info_texts = data['info']['infotexts']
    for info_text in info_texts:
        print(info_text)

    # 判断当前目录下是否存在 output 文件夹,如果不存在则创建
    if not os.path.exists("output"):
        os.mkdir("output")
    timestamp = datetime.datetime.now().strftime("%Y%m%d%H%M%S")
    output_path = f"{output_path}_{timestamp}" + ".json"
    # 将文件放入当前目录下的 output 文件夹中
    output_path = f"output/{output_path}"
    with open(output_path, "w") as f:
        json.dump(data, f, indent=4, ensure_ascii=False)


if __name__ == '__main__':
    """
    Example usage: python3 txt2img.py
    """
    txt2img_url = "http://192.168.2.82:7860/sdapi/v1/txt2img" # 服务器地址
    prompt = input("请输入提示词:")
    negative_prompt = input("请输入反面提示词:")
    data = {'prompt': prompt, 'negative_prompt': negative_prompt}
    # 将 data.prompt 中的文本,删除文件名非法字符,已下划线分隔,作为文件名
    output_path = data['prompt'].replace(" ", "_").replace("/", "_").replace("\\", "_").replace(":", "_").replace("\"",
                                                                                                                  "_").replace(
        "<", "_").replace(">", "_").replace("|", "_")
    response = submit_post(txt2img_url, data)
    save_encoded_image(response.json()['images'][0], output_path)
    save_json_file(response.json(), output_path)

输出:

>> python txt2img.py
请输入提示词:masterpiece, best quality, 1boy, orc, male focus, mecha, robot, science fiction, solo, black background <lora:nijiMecha:1> <lora:wzh-000022:1>
请输入反面提示词:(worst quality, low quality:1.4), greyscale, monochrome, watermark, signature

masterpiece, best quality, 1boy, orc, male focus, mecha, robot, science fiction, solo, black background <lora:nijiMecha:1> <lora:wzh-000022:1>
Negative prompt: (worst quality, low quality:1.4), greyscale, monochrome, watermark, signature
Steps: 50, Sampler: Euler, CFG scale: 7.0, Seed: 274772779, Size: 512x512, Model hash: ce67b54cf2, Model: oukaNiji5_v10, Seed resize from: -1x-1, Denoising strength: 0, Clip skip: 2


说明:

  • 运行后,图片以及 JSON 将会输出到当前目录下 output 中;

TIP:

  • 当然前提是你已经部署好 Stable Diffusion API 服务;
  • 并且安装好跟我一样的模型以及一些相关的 LoRA

print('HELLO WORLD') # http://www.skyner.cn
  • 4
    点赞
  • 16
    收藏
    觉得还不错? 一键收藏
  • 1
    评论
好的!以下是一个使用Python编写的stable diffusion模型生成图片的代码示例: ```python import numpy as np from PIL import Image # 定义stable diffusion函数 def stable_diffusion(image, alpha, delta_t, iterations): # 获取图像的大小 height, width, channels = image.shape # 初始化变量 u = np.zeros((height, width, channels)) u_new = np.zeros((height, width, channels)) # 将输入图像转换为浮点数类型 image = image.astype(np.float32) # 初始化u和u_new u[:] = image u_new[:] = image # 定义Laplacian算子 laplacian = np.array([[0, 1, 0], [1, -4, 1], [0, 1, 0]]) # 迭代stable diffusion模型 for i in range(iterations): # 计算Laplacian of u lu = np.zeros((height, width, channels)) for c in range(channels): lu[:, :, c] = np.abs(np.fft.fftshift(np.fft.ifft2(np.fft.fft2(u[:, :, c]) * np.fft.fft2(laplacian, s=u.shape[:2], axes=(0, 1))))).real # 更新u_new u_new = u + delta_t * (lu ** alpha) * laplacian # 更新u u[:] = u_new # 将u转换为整数类型 u = u.astype(np.uint8) # 返回u return u # 加载图像 image = np.array(Image.open('input.jpg')) # 运行stable diffusion模型 alpha = 1.0 delta_t = 0.1 iterations = 100 output_image = stable_diffusion(image, alpha, delta_t, iterations) # 显示结果图像 Image.fromarray(output_image).show() # 保存结果图像 Image.fromarray(output_image).save('output.jpg') ``` 你可以将上述代码保存在一个.py文件中,然后使用Python解释器运行。请确保在代码中替换`input.jpg`和`output.jpg`为你所需的图像文件名。此外,你还可以尝试调整`alpha`,`delta_t`和`iterations`参数来获得不同的结果。
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值