使用stable diffusion生成图片

准备

    硬件:有GPU的主机,显存6G+
    系统:windows10 或者 ubuntu 20.04
    软件: anaconda

1.下载安装anaconda

    wget https://repo.anaconda.com/archive/Anaconda3-2022.10-Linux-x86_64.sh
    sh Anaconda3-2022.10-Linux-x86_64.sh
    
    验证是否安装成功
    conda --version  //输出 conda 4.5.11

2.创建虚拟环境

    conda create -n diffusers python==3.9

3.安装需要的python库

    source activate diffusers
    pip install -r requirements.txt
    pip install torch==2.0.0+cu117 torchvision==0.15.1+cu117 torchaudio==2.0.0+cu117 -f https://download.pytorch.org/whl/torch_stable.html

requirements.txt 内容如下

    diffusers
    transformers
    accelerate
    ftfy
    spacy
    filelock
    charset-normalizer
    tqdm
    opencv-python
    datasets

4.python脚本

    from diffusers import StableDiffusionPipeline
    import torch
    import matplotlib.pyplot as plt
    import cv2
    import numpy as np

    model_id = "runwayml/stable-diffusion-v1-5"

    def generateImage(pipe, prompt):
        image = pipe(prompt).images[0]
        img_bgr = cv2.cvtColor(np.asarray(image), cv2.COLOR_RGB2BGR)
        cv2.imshow('img_bgr', img_bgr)
        cv2.waitKey(1000)

    if __name__=='__main__':
        print(torch.cuda.is_available())
        pipe = StableDiffusionPipeline.from_pretrained(model_id, torch_dtype=torch.float16)
        pipe.safety_checker = lambda images, clip_input: (images, False)
        pipe = pipe.to("cuda")
        while True:
            prompt= input('输入描述来生成图片:')
            generateImage(pipe, prompt)

保存为stable_diffusion.py并执行

        python stable_diffusion.py

效果图

 

### 使用 Stable Diffusion 模型生成图像的数据生成教程 #### 3.1 安装依赖库 为了使用 Stable Diffusion 模型生成图像,首先需要安装必要的 Python 库。可以通过 pip 来完成这一操作。 ```bash pip install torch torchvision torchaudio gradio diffusers transformers accelerate ``` #### 3.2 加载预训练模型 加载由 Hugging Face 提供的预训练 Stable Diffusion 模型是非常简单的一步。这一步骤会初始化一个用于后续推理的管道对象。 ```python from diffusers import StableDiffusionPipeline import torch model_id = "CompVis/stable-diffusion-v1-4" device = "cuda" if torch.cuda.is_available() else "cpu" pipeline = StableDiffusionPipeline.from_pretrained(model_id, use_auth_token=True).to(device) ``` #### 3.3 配置参数并生成图像 配置一些基本参数来控制生成过程中的行为,比如提示词(prompt)、步数(num_inference_steps),以及指导权重(guidance_scale)。之后调用 `__call__` 方法执行实际的图像生成工作。 ```python prompt = "A beautiful landscape with mountains and lakes under a clear sky." image = pipeline(prompt=prompt, num_inference_steps=50, guidance_scale=7.5)["sample"][0] image.save("output_image.png") ``` 上述代码片段展示了如何利用指定的文字描述作为输入,让模型根据该描述创建一张对应的图片[^1]。 #### 3.4 利用 Gradio 构建交互界面 为了让用户更方便地测试不同文本到图像转换的结果,可以借助 Gradio 创建一个简易的 Web UI 接口。这样不仅提高了用户体验度,同时也便于分享成果给更多的人群查看。 ```python import gradio as gr def generate_image(text_prompt): image = pipeline(prompt=text_prompt, num_inference_steps=50, guidance_scale=7.5)["sample"][0] return image gr_interface = gr.Interface(fn=generate_image, inputs="text", outputs="image") if __name__ == "__main__": gr_interface.launch() ``` 这段脚本定义了一个函数 `generate_image()` ,接受一段文字作为参数并通过之前设置好的 pipeline 进行处理得到最终产物;接着构建了 Gradio 的接口实例,并指定了输入输出形式为纯文本和 PNG 图片文件。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

打赏作者

telllong

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

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

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

打赏作者

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

抵扣说明:

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

余额充值