% a& i6 `7 C$ Q$ u
! I+ r$ w' |/ S, SStable Diffusion安装GitHub1 e3 Z% v$ V: Y# C6 g: x
在安装 Stable Diffusion 模型时,通常有两种主要方式:直接从官方 GitHub 仓库克隆代码,或通过 Hugging Face 等平台安装预训练模型。下面将分别介绍这两种方法。
( ?' o8 f* t# n* U# [. H: c
2 y. x; b0 i6 N$ [+ d方法一:从 GitHub 克隆代码 n6 b2 L/ G: M9 o4 }
克隆 Stable Diffusion 仓库4 g8 s1 C% X. c3 Z# ?; E
4 Z. @, I$ U$ M% e) F
首先,你需要从 GitHub 克隆 Stable Diffusion 的官方仓库。截至目前(2023年),官方仓库地址为:
# I2 v: C3 N/ K, a2 d- J" N0 t! h0 D; p7 U0 `; y, V( F
https://github.com/CompVis/stable-diffusion' K' O$ |6 U8 i
0 `, C* F3 e7 F8 W: A
在终端中,使用以下命令克隆仓库:/ O5 Q' Q1 G: E6 W1 B% [' P# x V
/ ^7 I' q% b3 x" t; Q
git clone https://github.com/CompVis/stable-diffusion.git9 h; n+ I2 u& G' R' @2 X
cd stable-diffusion
" j) x: U7 x- b$ e
3 o" {4 z, t8 R: A0 p设置环境$ z% P( c5 V2 A% c9 H5 j! r) T
$ O- g( S4 w* X. I: T安装必要的依赖。Stable Diffusion 需要 Python 和一些特定的库。你可以使用 requirements.txt 文件中的依赖来安装它们。首先,确保你的 Python 版本符合要求(通常是 Python 3.8 或更高)。然后,使用以下命令安装依赖:$ Z& Y, L3 ~$ k! ]2 j( i
7 b; J. a3 x+ F7 V
pip install -r requirements.txt- Z% p# B9 w0 ]. C5 r- d
) q5 F9 l# [7 f* p4 \( P/ j运行 Stable Diffusion
6 S$ P/ V; E+ j: W+ n3 W- J! L$ Z1 n6 |
( d9 \8 Y0 E. I根据你的具体需求,你可以运行不同的脚本。例如,如果你只是想测试模型,可以运行:* I, g% Q! x/ O" Z" Z) H5 d6 Y
, V& p. E' |4 D n. a! y
python scripts/txt2img.py --prompt "a photo of an astronaut riding a horse") n2 K$ a' ]# L0 j: I1 n/ ~
. S, A6 g! f& s3 {' H方法二:通过 Hugging Face 安装预训练模型
2 M$ h4 J7 X0 v4 f如果你只是想使用预训练的模型而不想从源代码开始,你可以使用 Hugging Face 的 diffusers 库来加载和使用 Stable Diffusion 模型。
0 b: L. j- f0 q2 e8 E! s2 ]- Q' m+ H
安装 diffusers- b: R( B& |* K. l" d3 V
2 L# h# I- S2 c; k
首先,安装 diffusers 库:7 E% I- X, b% V1 V2 C" G
; _; I* D3 O9 \
pip install diffusers transformers scipy
1 J& ^/ V/ e% n# v0 |! v. Z
' w5 g' w& K$ ? c- |加载和使用模型
# i" k0 f* h7 |
# h1 S. L$ E% e4 v使用以下代码加载和使用 Stable Diffusion 模型:
6 g7 E% @0 ^9 f6 R6 h4 K: \" P- v
' E4 K$ c+ j6 K3 H gfrom diffusers import StableDiffusionPipeline+ R5 C& t( g3 A2 S
import torch
3 Z; M' ]" _6 z/ y) H: F& ?& ]
O. _, Y- s8 e, jdevice = "cuda" if torch.cuda.is_available() else "cpu"2 a3 H7 E; d4 M
model_id = "runwayml/stable-diffusion-v1-5" # 使用官方预训练模型ID) I( f2 p0 n+ U- Q5 o& I7 f
pipe = StableDiffusionPipeline.from_pretrained(model_id, use_auth_token=True)
0 I, j- J1 x5 w' U+ {$ ?- N) rpipe = pipe.to(device): \1 U f; y- P9 ~, A, P
' I5 J8 {& g3 iimage = pipe("a photo of an astronaut riding a horse", guidance_scale=7.5)
% E( I/ I- K# C. d& pimage[0].save("astronaut_riding_horse.png")
+ }" f, U% C, x, l0 B ]+ a* @- o3 ]2 ^ x7 \1 t$ p8 V
确保替换 use_auth_token=True 中的 True 为你的 Hugging Face 访问令牌,如果你有的话。如果没有,可以省略或设置为 None。你可以在 Hugging Face 的网站上获取访问令牌。5 J# K4 Y( C+ z- k" q& C
/ q' p( B- a) p3 U+ Q* ?: v
通过上述任何一种方法,你都可以开始使用 Stable Diffusion 生成图像了。选择哪种方法取决于你的具体需求,比如是否需要自定义模型或只是快速开始使用预训练模型。( B+ P$ t. _4 T m4 |! V& v+ ?
% u8 C$ H* y$ q, Q/ t) Y- o提示:AI自动生成,仅供参考
6 p: a& w# f& Y: A& X' b8 ?5 x, t8 _0 X- F1 r- J* k' M! } {
参考 |