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,可以在里面查看支持修改的属性(基本全部可以奥)

您可能感兴趣的与本文相关的镜像

Python3.8

Python3.8

Conda
Python

Python 是一种高级、解释型、通用的编程语言,以其简洁易读的语法而闻名,适用于广泛的应用,包括Web开发、数据分析、人工智能和自动化脚本

### 使用 Python 调用 Stable Diffusion 并在 CPU 上运行的示例代码 对于希望利用 Python 来调用并操作 Stable Diffusion开发者而言,在仅使用中央处理器(CPU)的情况下启动图像生成任务是一个常见的需求。下面提供了一段可以在纯CPU环境下工作的Python脚本实例。 ```python from diffusers import StableDiffusionPipeline import torch model_id = "runwayml/stable-diffusion-v1-5" pipe = StableDiffusionPipeline.from_pretrained( model_id, torch_dtype=torch.float32, # Use float32 for better compatibility on CPU safety_checker=None # Optional: Disable safety checker to speed up generation ) # Ensure the pipeline runs entirely on CPU device = "cpu" pipe = pipe.to(device) prompt = "a cute panda eating bamboo in a bamboo forest" image = pipe(prompt).images[0] output_path = "panda_cpu_generated.png" image.save(output_path) ``` 这段代码展示了如何初始化一个基于指定模型ID(`runwayml/stable-diffusion-v1-5`)的Stable Diffusion管道,并设置数据类型为`torch.float32`以确保更好的CPU兼容性[^3]。此外,通过设定设备参数为`cpu`,可以强制所有的计算都在CPU上完成而不是尝试转移到图形处理单元(GPU)。 值得注意的是,默认情况下Stable Diffusion会自动检测是否有可用的CUDA环境;如果没有找到,则默认回退到CPU执行模式。然而显式指明这一点有助于提高程序行为的一致性和可预测性。 #### 关键配置选项解释: - `torch_dtype`: 当前被设为`torch.float32`而非更高效的半精度浮点数(如float16),因为后者通常只适用于支持特定指令集的现代GPU硬件,而大多数CPU并不具备这样的优化特性。 - `safety_checker`: 此项用于控制是否启用内置的安全检查机制,禁用它可以略微加快图片生的速度,但这可能会导致某些敏感内容未经过滤即被产出,请谨慎考虑这一选项的实际应用场景下的适用性。 最后保存由提示词描述所生成的艺术风格化的熊猫图片至当前工作目录下名为`panda_cpu_generated.png`的位置。
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

打赏作者

风吹落叶花飘荡

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

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

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

打赏作者

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

抵扣说明:

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

余额充值