当前位置: 首页 > news >正文

Stable Diffusion 实战教程:从安装到图像生成

Stable Diffusion 实战教程从安装到图像生成前言Stable Diffusion 是当前最流行的开源图像生成模型之一。它能够根据文字描述生成高质量的图像在创意设计、游戏开发等领域有广泛应用。我在多个项目中使用过 Stable Diffusion从简单的图像生成到风格迁移。今天分享完整的实战指南。环境准备# 创建虚拟环境 conda create -n sd python3.10 conda activate sd # 安装依赖 pip install torch torchvision torchaudio --index-url https://download.pytorch.org/whl/cu121 pip install diffusers transformers accelerate safetensors pip install gradio # 用于可视化基础使用文本到图像from diffusers import StableDiffusionPipeline import torch # 加载模型 pipe StableDiffusionPipeline.from_pretrained( runwayml/stable-diffusion-v1-5, torch_dtypetorch.float16 ).to(cuda) # 生成图像 prompt a beautiful sunset over the ocean, golden hour, photorealistic image pipe(prompt).images[0] # 保存图像 image.save(sunset.png)控制生成参数def generate_image( prompt: str, negative_prompt: str None, num_inference_steps: int 50, guidance_scale: float 7.5, seed: int None ) - Image: 生成图像 generator torch.Generator(cuda).manual_seed(seed) if seed else None image pipe( promptprompt, negative_promptnegative_prompt, num_inference_stepsnum_inference_steps, guidance_scaleguidance_scale, generatorgenerator ).images[0] return image # 使用示例 image generate_image( prompta cute cat playing with a ball, negative_promptugly, blurry, low quality, num_inference_steps30, guidance_scale7.5, seed42 )高级技巧图像到图像from diffusers import StableDiffusionImg2ImgPipeline from PIL import Image # 加载图像到图像模型 img2img_pipe StableDiffusionImg2ImgPipeline.from_pretrained( runwayml/stable-diffusion-v1-5, torch_dtypetorch.float16 ).to(cuda) # 加载输入图像 init_image Image.open(input.jpg).convert(RGB) init_image init_image.resize((512, 512)) # 生成 prompt turn this photo into a painting in the style of Van Gogh image img2img_pipe( promptprompt, imageinit_image, strength0.75 ).images[0] image.save(output.png)深度引导from diffusers import StableDiffusionDepth2ImgPipeline # 加载深度模型 depth_pipe StableDiffusionDepth2ImgPipeline.from_pretrained( stabilityai/stable-diffusion-2-depth, torch_dtypetorch.float16 ).to(cuda) # 使用深度图引导 prompt a futuristic city skyline image depth_pipe( promptprompt, imageinit_image, depth_mapNone # 自动计算深度 ).images[0]模型微调准备数据集from datasets import load_dataset # 加载数据集 dataset load_dataset(lambdalabs/pokemon-blip-captions) # 预处理 def preprocess(examples): images [image.convert(RGB).resize((512, 512)) for image in examples[image]] return {images: images, captions: examples[text]} dataset dataset.map(preprocess, batchedTrue)训练脚本from diffusers import StableDiffusionPipeline from diffusers.training_utils import set_seed # 设置种子 set_seed(42) # 加载模型 model_id runwayml/stable-diffusion-v1-5 pipe StableDiffusionPipeline.from_pretrained(model_id) # 配置训练参数 training_args { output_dir: ./pokemon-model, per_device_train_batch_size: 4, gradient_accumulation_steps: 4, learning_rate: 1e-5, num_train_epochs: 10, logging_steps: 10, save_steps: 100 } # 开始训练简化示例 # trainer.train()Web UI 部署import gradio as gr def generate(prompt, negative_prompt, steps, scale): 生成图像 image pipe( promptprompt, negative_promptnegative_prompt, num_inference_stepssteps, guidance_scalescale ).images[0] return image # 创建界面 with gr.Blocks() as demo: gr.Markdown(# Stable Diffusion Demo) with gr.Row(): with gr.Column(): prompt gr.Textbox(labelPrompt) negative_prompt gr.Textbox(labelNegative Prompt) steps gr.Slider(minimum10, maximum100, value50, labelSteps) scale gr.Slider(minimum1, maximum20, value7.5, labelGuidance Scale) generate_btn gr.Button(Generate) with gr.Column(): output gr.Image(labelOutput) generate_btn.click(generate, inputs[prompt, negative_prompt, steps, scale], outputsoutput) demo.launch()常见问题显存不足# 解决方案使用安全模式 pipe.enable_attention_slicing() # 或使用 CPU 卸载 pipe.enable_model_cpu_offload() # 或减少 batch size pipe.set_progress_bar_config(disableTrue)生成质量差# 提高质量的技巧 # 1. 使用更高的 steps # 2. 调整 guidance_scale # 3. 添加详细的 negative prompt # 4. 使用更好的模型如 SDXL总结Stable Diffusion 是强大的图像生成工具基础用法文本到图像的简单生成高级技巧图像到图像、深度引导微调适应特定风格或主题部署构建 Web 应用关键要点提示词质量直接影响生成结果negative prompt 很重要调整参数需要经验大显存 GPU 能显著提升速度
http://www.gsyq.cn/news/1341435.html

相关文章:

  • P1289 磁盘碎片整理【洛谷算法习题】
  • 小苯的数组构造【牛客tracker 每日一题】
  • 2025-2026年国际物流公司排行榜推荐:十大口碑产品评测铁路运输防货损场景价格 - 品牌推荐
  • Belkin向范围3排放碳中和目标迈进
  • 数字图像质量提升技术【附代码】
  • 计算机视觉与深度学习融合的群养猪行为识别与分类算法【附算法】
  • ElevenLabs顶级声库实战测评(含Wavenet级MOS评分+情感连贯性压测数据):这3个未公开API声线正在被头部AIGC团队悄悄部署
  • 2025-2026年广州除甲醛公司推荐:五大口碑产品评测全屋净化特点市场份额 - 品牌推荐
  • Java程序设计(第3版)第四章——类的组成
  • 8.C# —— 随机数、DateTime时间、字符串
  • 成都移动冷库技术深度解析:成都冷藏库/成都冷链冻库/成都冻库厂家/成都冻库工程/成都医药冷库/成都医药冻库/成都果蔬冻库/选择指南 - 优质品牌商家
  • 新旧版鸿蒙系统的区别详解——升级前必读指南
  • 鸿蒙系统给抖音开启相机权限的操作指南(2026)
  • 鸿蒙系统下抖音存储空间不足怎么办?缓存清理教程
  • 2025-2026年北京装修设计公司推荐:十大排行产品专业评测别墅定制防踩坑性价比高 - 品牌推荐
  • 长期使用中观察Taotoken账单的透明度与预测准确性
  • py每日spider案例之netease搜索接口获取
  • pubnub代码示例
  • 2026年至今,龙游专业鲜花服务选择指南与知音花艺生活馆深度推荐 - 2026年企业推荐榜
  • Midjourney金属渲染避坑清单(2024Q2最新):6类典型翻车案例+对应反向Prompt修复模板
  • 【仅剩最后47套】ElevenLabs丹麦语定制声音训练包(含哥本哈根/奥胡斯/奥尔堡三地方言样本库+声学特征标注集):20年语音工程团队内部封存资料限时开放
  • AI与云计算融合的考点中,机器学习基础流程、大模型应用基础及Prompt Engineering在系统设计中的作用是三大核心模块
  • 2026 年中国 GEO服务商/公司实力排名白皮书:技术、合规、效果、方案、续费率、口碑、好评榜、选型逻辑、全维度解析 - 互联网科技品牌测评
  • 知识竞赛裁判怎么当?评分标准与争议处理
  • 扣子平台全攻略:从零开发具有视频对话能力的心理陪伴机器人(附完整代码与详细解释)
  • 在NVIDIA DGX-Spark上部署NeMo框架实现微调与TensorRT Bit量化的全流程指南
  • 2026年四川城市管道清淤检测服务机构实测评测:四川城市管道清淤检测、四川工业污水转运、四川市政管道清淤检测、四川排水管道清淤检测选择指南 - 优质品牌商家
  • 2026年温州整体装修品牌实力对比:5家头部企业服务深度评测与选企建议 - 优家闲谈
  • 新乡施工选仿石漆:在平顶山施工选仿石漆选谁、在开封施工选仿石漆选谁、在新乡施工选仿石漆选谁、在洛阳施工选仿石漆选谁选择指南 - 优质品牌商家
  • TVA:打通数字AI到物理AI的关键桥梁(系列)