1. 項目目標
- 生成藝術作品:利用 AI 模型(如 Stable Diffusion)生成具有藝術風格的圖像。
- 自定義風格:通過文本提示(prompt)控制圖像的藝術風格(如賽博朋克、印象派、超現實主義等)。
- 后處理:使用 Python 進行圖像增強或風格遷移,增加獨特性。
- 工具:Python, Stable Diffusion (Hugging Face), PyTorch, Pillow, OpenCV。
2. 技術路線
以下是實現步驟:
- 安裝必要的庫:
- 安裝 Python 環境(推薦 Python 3.8+)。
- 安裝 AI 和圖像處理相關庫。
- 使用預訓練模型生成圖像:
- 使用 Stable Diffusion 模型通過文本提示生成基礎藝術圖像。
- 圖像后處理:
- 使用 Pillow 或 OpenCV 添加濾鏡、調整顏色或進行風格遷移。
- 保存和展示:
- 將生成的藝術作品保存為高分辨率圖像。
3. 環境準備
安裝依賴
確保你有以下庫:
pip install diffusers transformers torch pillow opencv-python numpy
硬件要求
- GPU(推薦):Stable Diffusion 在 GPU 上運行更快(需要 NVIDIA GPU 和 CUDA 支持)。
- CPU(可選):如果沒有 GPU,可以用 CPU,但生成速度較慢。
Hugging Face 登錄
Stable Diffusion 模型需要從 Hugging Face 下載,并可能需要登錄:
pip install huggingface_hub
huggingface-cli login
輸入你的 Hugging Face 令牌(在 Hugging Face 官網獲取)。
4. 代碼實現
以下是一個完整的 Python 腳本,結合 Stable Diffusion 生成藝術圖像,并進行后處理。
import torch
from diffusers import StableDiffusionPipeline
from PIL import Image
import cv2
import numpy as np
import os# 1. 初始化 Stable Diffusion 模型
model_id = "runwayml/stable-diffusion-v1-5"
pipe = StableDiffusionPipeline.from_pretrained(model_id, torch_dtype=torch.float16)
pipe = pipe.to("cuda") # 使用 GPU(如果沒有 GPU,注釋此行)# 2. 定義藝術風格的文本提示
prompt = "A surreal painting of a futuristic city at sunset, vibrant colors, in the style of Salvador Dali"
negative_prompt = "low quality, blurry, text, watermark" # 避免生成低質量圖像# 3. 生成圖像
image = pipe(prompt,negative_prompt=negative_prompt,num_inference_steps=50, # 推理步數,控制生成質量guidance_scale=7.5, # 提示引導強度
).images[0]# 4. 保存原始生成圖像
output_dir = "art_output"
os.makedirs(output_dir, exist_ok=True)
image.save(os.path.join(output_dir, "original_art.png"))# 5. 圖像后處理:添加藝術濾鏡
def apply_artistic_filter(image_pil, filter_type="edge_enhance"):# 將 PIL 圖像轉換為 OpenCV 格式image_np = np.array(image_pil)image_cv = cv2.cvtColor(image_np, cv2.COLOR_RGB2BGR)if filter_type == "edge_enhance":# 增強邊緣,模擬手繪效果kernel = np.array([[0, -1, 0], [-1, 5, -1], [0, -1, 0]])image_cv = cv2.filter2D(image_cv, -1, kernel)elif filter_type == "color_boost":# 增強顏色鮮艷度image_cv = cv2.convertScaleAbs(image_cv, alpha=1.2, beta=10)# 轉換回 PIL 格式image_filtered = cv2.cvtColor(image_cv, cv2.COLOR_BGR2RGB)return Image.fromarray(image_filtered)# 6. 應用濾鏡并保存
filtered_image = apply_artistic_filter(image, filter_type="edge_enhance")
filtered_image.save(os.path.join(output_dir, "filtered_art.png"))print("藝術作品已生成并保存至 art_output 目錄!")
5. 代碼說明
- Stable Diffusion:
- 使用
runwayml/stable-diffusion-v1-5
模型,通過文本提示生成圖像。 prompt
定義了圖像的內容和風格,例如“超現實的未來城市,達利風格”。negative_prompt
避免生成不需要的元素(如模糊或低質量圖像)。num_inference_steps
和guidance_scale
控制生成質量和提示的遵循程度。
- 使用
- 后處理:
apply_artistic_filter
函數使用 OpenCV 實現兩種濾鏡:edge_enhance
:增強圖像邊緣,模擬手繪效果。color_boost
:提升顏色鮮艷度,增加藝術感。
- 可以根據需要擴展更多濾鏡(如模糊、素描效果等)。
- 輸出:
- 生成的原始圖像和濾鏡處理后的圖像保存至
art_output
目錄。
- 生成的原始圖像和濾鏡處理后的圖像保存至
6. 擴展與優化
為了讓作品更獨特,可以嘗試以下方法:
- 自定義提示:
- 嘗試不同的藝術風格,如:
- “A cyberpunk cityscape in the style of Van Gogh”
- “An abstract portrait of a woman, vibrant watercolor style”
- 使用更復雜的提示,結合藝術家風格或藝術流派。
- 嘗試不同的藝術風格,如:
- 風格遷移:
- 使用預訓練的神經風格遷移模型(如 PyTorch 的
torchvision.models
或neural-style-transfer
)將生成的圖像與特定藝術風格(如畢加索、莫奈)融合。 - 示例庫:
pytorch-CycleGAN-and-pix2pix
。
- 使用預訓練的神經風格遷移模型(如 PyTorch 的
- 批量生成:
- 編寫循環,生成多個圖像并挑選最佳作品:
for i in range(3):image = pipe(prompt, negative_prompt=negative_prompt).images[0]image.save(os.path.join(output_dir, f"art_{i}.png"))
- 編寫循環,生成多個圖像并挑選最佳作品:
- 交互界面:
- 使用
Streamlit
或Gradio
構建一個 Web 界面,讓用戶輸入提示并實時預覽生成的藝術作品。 - 示例:
pip install gradio
import gradio as gr def generate_art(prompt):image = pipe(prompt).images[0]return image gr.Interface(fn=generate_art, inputs="text", outputs="image").launch()
- 使用
7. 常見問題與解決方案
- 顯存不足:
- 如果 GPU 顯存不足,嘗試:
- 降低
torch_dtype
為torch.float16
。 - 減少
num_inference_steps
(如 30)。 - 使用 CPU(注釋
pipe.to("cuda")
)。
- 降低
- 如果 GPU 顯存不足,嘗試:
- 生成圖像質量不高:
- 增加
num_inference_steps
(如 100)。 - 調整
guidance_scale
(7.5~12.5 通常效果較好)。 - 使用更詳細的提示詞。
- 增加
- 模型下載慢:
- 確保網絡穩定,或提前下載模型到本地:
pipe = StableDiffusionPipeline.from_pretrained(model_id, cache_dir="./models")
- 確保網絡穩定,或提前下載模型到本地:
8. 其他 AI 藝術生成工具
如果你想探索更多 AI 藝術生成工具,可以嘗試:
- DALL·E 3:通過 OpenAI API 生成高質量圖像(需要付費)。
- MidJourney:專注于藝術風格的生成(通過 Discord 操作)。
- Artbreeder:基于 GAN 的圖像混合與生成。
- VQ-VAE-2:生成像素藝術或低分辨率風格圖像。
這些工具可以通過 API 或 Python 腳本集成到你的工作流中。
9. 成果展示
運行上述代碼后,你將得到:
- 一張原始的 AI 生成圖像(如超現實的未來城市)。
- 一張經過濾鏡處理的藝術圖像(邊緣增強或顏色提升)。
- 保存路徑:
art_output/original_art.png
和art_output/filtered_art.png
。
你可以進一步將這些圖像用于:
- 數字藝術展覽。
- NFT 創作。
- 個性化壁紙或印刷品。
10. 總結
通過 Python 和 Stable Diffusion,你可以快速生成獨特的藝術圖像,并通過后處理增加個性化效果。上述代碼提供了從生成到增強的完整流程,且易于擴展。