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

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

一、前言

在无聊的时候,想瞅一下sd生图遂做了一下

二、具体步骤

1、启动SD的api设置

在这里插入图片描述
注意,运行后的api相关功能可以在:http://127.0.0.1:7860/docs 查看
在这里插入图片描述
比如这一次我们要的生图的地址就是/sdapi/v1/txt2img 是POST
所以可以通过requests 向 "http://127.0.0.1:7860/sdapi/v1/txt2img"发送POST请求并拿到数据

注意将69行的: txt2img_url = “http://127.0.0.1:7860/sdapi/v1/txt2img” # 服务器地址 ,里面的地址和端口改成你的

2、运行生图程序

程序如下

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://127.0.0.1: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("|", "_")[:40]
    response = submit_post(txt2img_url, data)
    save_encoded_image(response.json()['images'][0], output_path)
    save_json_file(response.json(), output_path)

运行结果:
在这里插入图片描述

说明:

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

TIP:

  • 如果要调用特定模型请在body中加入额外的参数如
    • data = {'prompt': prompt, 'negative_prompt': negative_prompt,"sd_model_name":"animePastelDream_softBakedVae"}
      
    • 要使用更多参数请查看上面提到的docs,可以在里面查看支持修改的属性(基本全部可以奥)
  • 4
    点赞
  • 6
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论
好的!以下是一个使用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`参数来获得不同的结果。

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

风吹落叶花飘荡

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值