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

Mac电脑手动安装原版Stable Diffusion,开启本地API调用生成图片

Mac 上安装 Stable Diffusion 的方法:
安装 Homebrew(如果尚未安装)
打开终端,执行以下命令:

/bin/bash -c "$(curl -fsSL https://raw.githubusercontent.com/Homebrew/install/HEAD/install.sh)"

安装 Python 3.10.x

brew install python@3.10

安装 Git

brew install git

安装步骤
克隆 automatic1111 仓库

git clone https://github.com/AUTOMATIC1111/stable-diffusion-webui.git
# 如果clone不下来,直接到github去下载再解压(unzip)也可以
cd stable-diffusion-webui

创建并激活虚拟环境

python3.10 -m venv venv
source venv/bin/activate

执行webui.sh

./webui.sh

在这里插入图片描述
等结束后会自动跳转127.0.0.1:7860
在这里插入图片描述
下载model

https://civitai.com/models

model放到stable diffusion webui/models/Stable Diffusion下
在这里插入图片描述
开启API

# 在webui-user.sh添加
# Stable Diffusion WebUI启动脚本
export COMMANDLINE_ARGS="--lowvram --precision full --no-half --skip-torch-cuda-test --disable-nan-check --api"

在这里插入图片描述
再启动./webui.sh
在这里插入图片描述
编写本地调用api代码

import requests
import json
import base64
from PIL import Image
from io import BytesIO
import os# API地址(默认端口7860)
API_URL = "http://127.0.0.1:7860"# 1. 文本生成图像(txt2img)
def txt2img(prompt, negative_prompt="", steps=20, width=512, height=512, sampler="Euler a"):payload = {"prompt": prompt,"negative_prompt": negative_prompt,"steps": steps,"width": width,"height": height,"sampler_name": sampler,"cfg_scale": 7,  # 提示词相关性,值越高越贴近提示"seed": -1,  # -1表示随机种子}response = requests.post(f"{API_URL}/sdapi/v1/txt2img", json=payload)if response.status_code == 200:result = response.json()for i, img_data in enumerate(result["images"]):image = Image.open(BytesIO(base64.b64decode(img_data)))save_path = f"txt2img_result_{i}.png"image.save(save_path)print(f"图片已保存至: {save_path}")return resultelse:print(f"请求失败,状态码: {response.status_code}")print(response.text)return None# 2. 图像生成图像(img2img)
def img2img(prompt, image_path, negative_prompt="", steps=20, strength=0.7, sampler="Euler a"):# 读取图像并转换为base64with open(image_path, "rb") as f:image_data = f.read()image_base64 = base64.b64encode(image_data).decode('utf-8')payload = {"prompt": prompt,"negative_prompt": negative_prompt,"init_images": [image_base64],"steps": steps,"sampler_name": sampler,"strength": strength,  # 0.1-0.9,数值越高与原图差异越大"cfg_scale": 7,"seed": -1,}response = requests.post(f"{API_URL}/sdapi/v1/img2img", json=payload)if response.status_code == 200:result = response.json()for i, img_data in enumerate(result["images"]):image = Image.open(BytesIO(base64.b64decode(img_data)))save_path = f"img2img_result_{i}.png"image.save(save_path)print(f"图片已保存至: {save_path}")return resultelse:print(f"请求失败,状态码: {response.status_code}")print(response.text)return None# 3. 获取可用模型列表
def get_models():response = requests.get(f"{API_URL}/sdapi/v1/sd-models")if response.status_code == 200:return response.json()return []# 4. 切换模型
def switch_model(model_name):payload = {"sd_model_checkpoint": model_name}response = requests.post(f"{API_URL}/sdapi/v1/options", json=payload)return response.status_code == 200# 示例调用
if __name__ == "__main__":# 示例1: 文本生成图像txt2img(prompt="a beautiful landscape, mountains, lake, detailed, realistic, 4k",negative_prompt="blurry, low quality, deformed",steps=30,width=768,height=512)# 示例2: 图像生成图像(取消注释并提供图片路径)# img2img(#     prompt="make it more vibrant, add birds in the sky",#     image_path="input_image.png",#     strength=0.6# )# 示例3: 获取可用模型# models = get_models()# print("可用模型:", [model["title"] for model in models])# 示例4: 切换模型# switch_model("v1-5-pruned-emaonly.ckpt")

运行后
在这里插入图片描述
这样就可以编写本地脚本,实现自动化生图了,而无需在webui上一张张图自己生成了。

相关文章:

  • 基于云的平板挠度模拟:动画与建模-AI云计算数值分析和代码验证
  • Linux中部署Nacos保姆级教程
  • Wpf布局之WrapPanel面板!
  • Java面试宝典:基础二
  • JSON + 存储过程:SaaS 架构下的统一接口与租户定制之道
  • 2025年渗透测试面试题总结-2025年HW(护网面试) 19(题目+回答)
  • OpenCV读取照片和可视化详解和代码示例
  • Java 数据结构 泛型
  • Hive SQL 快速入门指南
  • 线性相关和线性无关
  • 【记录】服务器多用户共享Conda环境——Ubuntu24.04
  • HarmonyOS NEXT仓颉开发语言实战案例:健身App
  • HarmonyOS NEXT仓颉开发语言实战案例:小而美的旅行App
  • GO 语言学习 之 数组和切片
  • 无人机用shell远程登录机载电脑,每次需要环境配置原因
  • 现代 JavaScript (ES6+) 入门到实战(六):异步的终极形态 - async/await 的优雅魔法
  • Redis分布式锁深度解析:从原理到实践
  • C++迭代器解析:正向、反向与随机访问迭代器
  • 【C++ 基础】 C++ 与 C 语言差异面试题(附大厂真题解析)
  • 【系统分析师】高分论文:论软件的系统测试及其应用