这里我们使用 OpenAI 的 DALL-E 接口作为示范。
首先安装法宝:pip install openai
from openai import OpenAI
# 1. 注入灵力 (API Key)
client = OpenAI(api_key="sk-你的密钥")
# 2. 念动咒语 (Prompt)
prompt = "一只穿着道袍的熊猫在云端写代码,赛博朋克风格"
# 3. 施法 (生成图片)
response = client.images.generate(
model="dall-e-3",
prompt=prompt,
size="1024x1024",
quality="standard",
n=1,
)
# 4. 获取画卷 (URL)
image_url = response.data[0].url
print(f"画好了!快看这里: {image_url}")
如果你有强大的法宝 (显卡 GPU),也可以在本地部署 Stable Diffusion。
使用 diffusers 库:
# 这是一个高级法术,需要 PyTorch 和 CUDA 支持
from diffusers import StableDiffusionPipeline
import torch
pipe = StableDiffusionPipeline.from_pretrained("runwayml/stable-diffusion-v1-5")
pipe = pipe.to("cuda")
prompt = "A futuristic city floating in the sky, ancient chinese style"
image = pipe(prompt).images[0]
image.save("ascension_city.png")
任务:在 DALL-E 接口中,我们通过什么参数来描述我们想画的内容?