Python 创意:AI 图像生成
一、基于 Stable Diffusion 的本地创意创作
Stable Diffusion 是开源图像生成模型的代表,通过 Python 结合diffusers
库,可实现本地图像生成。
1. 环境搭建
首先,安装必要的库:
pip install diffusers transformers torch
若使用 GPU 加速,需安装对应版本的 CUDA 和 cuDNN。
2. 基础图像生成
from diffusers import StableDiffusionPipeline
import torch# 加载模型
pipe = StableDiffusionPipeline.from_pretrained("runwayml/stable-diffusion-v1-5", torch_dtype=torch.float16)
pipe = pipe.to("cuda")# 生成图像
prompt = "A fantasy landscape with a magical castle"
image = pipe(prompt).images[0]
image.save("fantasy_castle.png")
上述代码加载了 Stable Diffusion v1.5 模型,输入 “奇幻景观与魔法城堡” 的文本提示,即可生成对应图像并保存。
3. 创意扩展
- 风格化控制:通过添加风格提示词,如 “in the style of Van Gogh”(梵高风格),能生成特定艺术风格