AI 图片视频处理 — 工具使用手册
这篇不是讲原理的——是给你直接复制粘贴的命令、配置和工作流。ComfyUI 9 大核心节点、SD 三大管线(文生图/图生图/Inpainting)、LoRA 多模型组合、ControlNet 边缘控制、4 家 API 调用——全部整理为一条命令可执行的形式。配合系列第 5 篇(图片生成原理)和第 6 篇(精确控制与视频生成)阅读。
阅读约 12 分钟 | 系列配套附录
⚠️ 时效性提示:本文基于 2026 年 7 月的技术状态撰写。大模型版本迭代迅速(通常 3-6 个月一次大版本更新),文中涉及的模型名称、API 端点及性能基准数据请以各厂商最新公告为准。建议重点关注文章中的操作方法和工具选型逻辑——这些内容具有更长的时效性。
一、环境搭建
1.1 Python 版本兼容性
| Python | PyTorch | diffusers | OpenCV Contrib | 推荐 |
|---|---|---|---|---|
| 3.11 | ✅ | ✅ | ✅ | ★★★★★ 首选 |
| 3.12 | ✅ 2.3+ | ✅ | ✅ | ★★★★ |
| 3.13 | ⚠️ 部分支持 | ⚠️ | ⚠️ | ★★★ |
| 3.14 | ❌ 不支持 | ✅ | ✅ | ★☆ 不推荐用于图像任务 |
1.2 各 Python 包的功能定位
| 包名 | 功能定位 | 若不安装的影响 |
|---|---|---|
| torch | AI 模型推理运行时(GPU 上的 numpy) | 任何模型均无法运行 |
| diffusers | 扩散模型的管线工厂,一行加载、一行推理 | 需手动编写数百行管线代码 |
| transformers | 文本编码(diffusers 内部依赖) | diffusers 自动安装 |
| opencv-contrib-python-headless | 图像读写、DNN 推理、超分辨率模块 | 读写/缩放/超分均需另寻替代方案 |
| accelerate | 自动 GPU 分配、混合精度、多 GPU 并行 | 需手写 .to("cuda") 及显存管理逻辑 |
| Pillow (PIL) | 基础图像读写库(同时是 OpenCV 中文路径问题的兼容方案) | 无法处理常见图像格式 |
| huggingface_hub | 从 HuggingFace 自动下载模型权重 | 需手动下载并指定本地路径 |
| xformers(可选) | 注意力机制加速,可节省约 30% 显存 | 显存更紧张(仅支持 Linux) |
| bitsandbytes(可选) | 8-bit/4-bit 量化推理 | 大模型超出显存上限,无法运行 |
| ultralytics | YOLO 目标检测 | 无法自动检测图像中的人物位置 |
| onnxruntime | 使模型脱离 PyTorch 环境独立运行 | 生产部署时依赖体积大、冷启动慢 |
1.3 安装命令
# 核心依赖
pip install torch torchvision --index-url https://download.pytorch.org/whl/cu121
pip install diffusers transformers accelerate
pip install opencv-contrib-python-headless
# 辅助工具
pip install Pillow numpy huggingface_hub
# YOLO 目标检测
pip install ultralytics
# 可选组件
pip install xformers # 注意力加速(仅 Linux)
pip install bitsandbytes # 量化推理
pip install onnxruntime # 部署推理
1.4 国内镜像加速
# HuggingFace 镜像
export HF_ENDPOINT=https://hf-mirror.com
# pip 镜像
pip config set global.index-url https://pypi.tuna.tsinghua.edu.cn/simple
1.5 安装验证
以下 4 条命令全部通过,即表示环境就绪:
python -c "import torch; print(torch.cuda.is_available())" # → True
python -c "import torch; print(torch.version.cuda)" # → 12.1
python -c "from diffusers import DiffusionPipeline; print('OK')" # → OK
python -c "import cv2; cv2.dnn_superres.DnnSuperResImpl_create()" # → 成功
二、远程 API 调用
2.1 SiliconFlow — OpenAI 兼容接口,可用模型种类最多
# pip install openai
from openai import OpenAI
client = OpenAI(
base_url="https://api.siliconflow.cn/v1",
api_key="sk-xxxxxxxx" # 在 cloud.siliconflow.cn 注册后获取
)
# 文生图
response = client.images.generate(
model="black-forest-labs/FLUX.1-dev", # 照片级写实,推荐首选
# model="stabilityai/stable-diffusion-3-5-medium", # 需要使用 ControlNet 时选择
# model="nvidia/SANA-1.5", # 极速版,低延迟场景
prompt="一只戴墨镜的橘猫坐在沙滩上,日落光线,电影质感",
size="1024x1024",
n=1
)
2.2 智谱 — CogView-4,支持对话式迭代编辑
# pip install zhipuai
# 方式 A:官方 SDK
from zhipuai import ZhipuAI
client = ZhipuAI(api_key="xxxxxxxx") # 在 open.bigmodel.cn 注册后获取
response = client.images.generations(
model="cogview-4", prompt="一只戴墨镜的橘猫坐在沙滩上", size="1024x1024"
)
print(response.data[0].url)
# 方式 B:OpenAI 兼容接口
from openai import OpenAI
client = OpenAI(base_url="https://open.bigmodel.cn/api/paas/v4", api_key="xxxxxxxx")
response = client.images.generate(model="cogview-4", prompt="一只猫", size="1024x1024")
# 特色功能:对话式编辑(在上一张图的基础上迭代修改)
response = client.images.generations(
model="cogview-4", prompt="把猫的墨镜改成红色",
image_url=response.data[0].url # 传入上一张图的 URL 作为编辑基础
)
2.3 阿里百炼 — 中文字符渲染领先 + 图片编辑 API
# pip install dashscope
import dashscope
from dashscope import ImageSynthesis
response = ImageSynthesis.call(
api_key="sk-xxxxxxxx", model="qwen-image-max",
prompt="一只橘猫在沙发上打哈欠,温暖的午后阳光",
n=1, size="1024*1024"
)
# 特色功能:图片编辑 API(支持 Inpainting 和指令式编辑)
response = ImageSynthesis.call(
model="qwen-image-edit",
prompt="把背景改成夜晚星空",
image_url="https://xxx.com/original.jpg",
mask_url="https://xxx.com/mask.png", # 遮罩 URL(可选)
n=1, size="1024*1024"
)
2.4 视频生成 API
# 阿里百炼 — 通义万相视频生成(异步任务,需轮询结果)
task = VideoSynthesis.async_call(
api_key="sk-xxx", model="wanx-video",
prompt="一只橘猫在海边散步,夕阳,慢动作",
duration=5, size="1280*720"
)
result = VideoSynthesis.wait(task.task_id, api_key="sk-xxx")
# 智谱 — CogVideoX
client = ZhipuAI(api_key="xxx")
response = client.videos.generations(
model="cogvideo-x", prompt="一只橘猫在阳台上打哈欠,自然光,温馨氛围"
)
三、diffusers 实战
3.1 文生图
from diffusers import AutoPipelineForText2Image
import torch
pipe = AutoPipelineForText2Image.from_pretrained(
"black-forest-labs/FLUX.1-schnell",
torch_dtype=torch.bfloat16
).to("cuda")
image = pipe(
prompt="一只橘猫戴着墨镜坐在沙滩上,日落光线,电影质感",
num_inference_steps=4,
guidance_scale=3.5,
generator=torch.Generator("cuda").manual_seed(42),
).images[0]
image.save("output.jpg")
推理性能参考基准
以下数据基于 2026 年 7 月的常见硬件配置实测,仅供参考:
| 显卡 | 显存 | FLUX-schnell 1024² | SD 3.5 Medium 1024² | SDXL 1024² | 备注 |
|---|---|---|---|---|---|
| RTX 4060 | 8GB | 6-8s | 12-15s | 4-6s | FLUX 需要 enable_attention_slicing() |
| RTX 4070 | 12GB | 4-5s | 8-10s | 3-4s | 甜点级 |
| RTX 4090 | 24GB | 2-3s | 4-6s | 1-2s | 消费级旗舰 |
| Mac M3 Max | 36GB | ~45s (MPS) | ~60s (MPS) | ~20s (MPS) | MPS 后端,速度显著慢于 NVIDIA |
| CPU (i9-13900K) | — | ~8min | ~15min | ~4min | 仅用于验证 |
显存不够时的优先策略:
pipe.enable_attention_slicing()→ 省 20-30% 显存,速度降 10%pipe.enable_model_cpu_offload()→ 大幅降低峰值占用,但慢 2-3 倍- 降低输出尺寸(1024² → 512²)→ 显存占用减半
3.2 图生图
from diffusers import AutoPipelineForImage2Image
from PIL import Image
pipe = AutoPipelineForImage2Image.from_pretrained(
"black-forest-labs/FLUX.1-schnell", torch_dtype=torch.bfloat16
).to("cuda")
original = Image.open("my_photo.jpg")
result = pipe(
prompt="水彩画风格,柔和的色彩",
image=original, strength=0.5, num_inference_steps=4,
).images[0]
strength 调参指南:0.1(色调微调)→ 0.3(风格转变)→ 0.5(显著变化)→ 1.0(等价文生图)
3.3 Inpainting
from diffusers import AutoPipelineForInpainting
pipe = AutoPipelineForInpainting.from_pretrained(
"black-forest-labs/FLUX.1-schnell", torch_dtype=torch.bfloat16
).to("cuda")
original = Image.open("my_photo.jpg")
mask = Image.open("mask.png") # 白色=允许修改,黑色=保持原样
result = pipe(
prompt="干净的街道背景,自然的建筑外墙",
image=original, mask_image=mask, num_inference_steps=4,
).images[0]
制作遮罩的三种方式:
# 方式 1:手动标注矩形或椭圆区域
from PIL import Image, ImageDraw
mask = Image.new("L", img.size, 0)
draw = ImageDraw.Draw(mask)
draw.rectangle([100, 200, 300, 400], fill=255) # 矩形
draw.ellipse([400, 200, 500, 350], fill=255) # 椭圆
# 方式 2:YOLO 自动检测人物并生成遮罩
from ultralytics import YOLO
model = YOLO("yolov8n.pt")
results = model(img, classes=[0], conf=0.3) # class 0 = person
# 方式 3:SAM(Segment Anything Model)精确分割(精度最高)
Inpainting 注意事项:遮罩占比 >30% → 成功率显著下降;遮罩边缘锐利 → cv2.GaussianBlur(mask, (21,21), 10) 羽化。
3.4 超分辨率
# 方案 A:CNN 超分(OpenCV LapSRN)— 严格保真,不编造内容
import cv2
sr = cv2.dnn_superres.DnnSuperResImpl_create()
sr.readModel("LapSRN_x4.pb")
sr.setModel("lapsrn", 4)
result = sr.upsample(cv_img)
# 方案 B:扩散超分 — 以极低 strength 仅增强纹理
result = pipe_img2img(
prompt="high resolution, sharp details, 4K",
image=original, strength=0.15,
).images[0]
3.5 LoRA 加载
pipe.load_lora_weights("path/to/character_lora.safetensors")
pipe.fuse_lora()
# 多 LoRA 组合
pipe.load_lora_weights("char1.safetensors", adapter_name="char1")
pipe.load_lora_weights("style.safetensors", adapter_name="style")
pipe.set_adapters(["char1", "style"], adapter_weights=[0.8, 0.5])
# LoRA 文件获取:civitai.com / huggingface.co
3.6 ControlNet 使用(以 Canny 边缘检测为例)
from diffusers import StableDiffusion3ControlNetPipeline, ControlNetModel
controlnet = ControlNetModel.from_pretrained(
"InstantX/SD3-Controlnet-Canny", torch_dtype=torch.float16
)
pipe = StableDiffusion3ControlNetPipeline.from_pretrained(
"stabilityai/stable-diffusion-3.5-medium",
controlnet=controlnet, torch_dtype=torch.float16
).to("cuda")
edges = cv2.Canny(cv2.cvtColor(np.array(original), cv2.COLOR_RGB2BGR), 100, 200)
control_image = Image.fromarray(edges)
result = pipe(
prompt="a photorealistic cat sitting in a cozy living room",
control_image=control_image,
controlnet_conditioning_scale=0.8,
).images[0]
3.7 IP-Adapter 使用
# ⚠️ IP-Adapter 的权重文件必须匹配基础模型版本,否则会报维度不匹配错误:
# - SDXL 模型 → subfolder="sdxl_models", weight_name="ip-adapter_sdxl.bin"
# - SD3/3.5 模型 → subfolder="sd3", weight_name="ip-adapter_sd3.safetensors"
# - FLUX 模型 → 需专门的 FLUX.1-IP-Adapter(diffusers 0.32+ 支持)
pipe.load_ip_adapter(
"h94/IP-Adapter", subfolder="sd3",
weight_name="ip-adapter_sd3.safetensors"
)
reference = Image.open("reference_style.jpg")
result = pipe(
prompt="a cat sitting on a windowsill",
ip_adapter_image=reference, ip_adapter_scale=0.6,
).images[0]
四、OpenCV 图像处理
4.1 经典 Inpainting(内容感知填充,不生成虚构内容)
# Telea(快速行进法):适用于小面积纹理修复
result = cv2.inpaint(image, mask, inpaintRadius=5, flags=cv2.INPAINT_TELEA)
# NS(Navier-Stokes):适用于稍大面积的结构保持型修复
result = cv2.inpaint(image, mask, inpaintRadius=10, flags=cv2.INPAINT_NS)
4.2 中文路径处理
OpenCV 不支持中文文件路径,需通过 PIL 中转:
from PIL import Image
import numpy as np
import cv2
# 读取:PIL → numpy → OpenCV
pil_img = Image.open("中文路径/图片.jpg")
cv_img = cv2.cvtColor(np.array(pil_img), cv2.COLOR_RGB2BGR)
# 保存:OpenCV → numpy → PIL
result_rgb = cv2.cvtColor(cv_result, cv2.COLOR_BGR2RGB)
Image.fromarray(result_rgb).save("中文路径/输出.jpg", quality=95)
4.3 常用图像操作
img = Image.open("photo.jpg")
img_resized = img.resize((1024, 1024), Image.LANCZOS)
img_cropped = img.crop((100, 100, 500, 500))
img.save("output.jpg", "JPEG", quality=95)
五、ComfyUI 快速入门
git clone https://github.com/comfyanonymous/ComfyUI.git
cd ComfyUI && pip install -r requirements.txt
python main.py --auto-launch # Windows
# 启动后浏览器访问 http://127.0.0.1:8188
节点含义:Load Checkpoint = 加载模型权重;CLIP Text Encode = Prompt 编码;KSampler = 执行去噪循环;VAE Decode = 潜空间→像素。
推荐社区节点:ComfyUI-Impact-Pack(面部细化)、ComfyUI_IPAdapter_plus(IP-Adapter)、WAS-Node-Suite(图像处理)、ComfyUI-VideoHelperSuite(视频处理)。
六、FFmpeg 视频管线
# 提取帧
ffmpeg -i input.mp4 -vf fps=1 frame_%04d.png
# 帧序列合成视频
ffmpeg -framerate 24 -i frame_%04d.png -c:v libx264 output.mp4
# AI 处理 + FFmpeg 组合管线
ffmpeg -i input.mp4 -vf fps=10 frames/%06d.png
python process_frames.py frames/ output_frames/
ffmpeg -framerate 10 -i output_frames/%06d.png -c:v libx264 output.mp4
ffmpeg -i output.mp4 -i input.mp4 -c:v copy -c:a aac -map 0:v:0 -map 1:a:0 final.mp4
七、FastAPI 服务化部署
# image_service.py
from fastapi import FastAPI, Form
from fastapi.responses import Response
from diffusers import AutoPipelineForText2Image
import io, torch
app = FastAPI()
@app.on_event("startup")
async def load_models():
global pipe
pipe = AutoPipelineForText2Image.from_pretrained(
"black-forest-labs/FLUX.1-schnell", torch_dtype=torch.bfloat16
).to("cuda")
@app.post("/generate")
async def generate(prompt: str = Form(...), seed: int = Form(42)):
generator = torch.Generator("cuda").manual_seed(seed)
image = pipe(prompt=prompt, generator=generator).images[0]
buf = io.BytesIO(); image.save(buf, format="JPEG", quality=95)
return Response(content=buf.getvalue(), media_type="image/jpeg")
# 启动:uvicorn image_service:app --port 8000
# 调用:curl -X POST http://localhost:8000/generate -F "prompt=一只猫" -o cat.jpg
生产环境注意事项:异步任务队列(Celery + Redis)、GPU 并发控制(Semaphore)、超时处理、结果缓存、模型常驻显存。
八、常见问题速查
| 问题 | 原因分析 | 解决方案 |
|---|---|---|
CUDA out of memory | 图像尺寸过大或模型超出显存 | 减小输出尺寸、启用 enable_attention_slicing()、或切换至 CPU 模式 |
pip install torch 超时或失败 | Python 版本过新 | 降级至 Python 3.11 或 3.12 |
cv2.dnn_superres 模块为空 | 安装了非 contrib 版本 | pip install opencv-contrib-python-headless --force-reinstall |
| OpenCV 中文路径读写失败 | OpenCV 不支持非 ASCII 字符路径 | 通过 PIL 中转读写(参见 §4.2) |
| SD Inpainting 背景填充不自然 | 生成式模型倾向于虚构内容 | 改用内容感知填充方案,或缩小遮罩面积 |
| 生成结果与遮罩边缘存在明显接缝 | 遮罩边缘过渡不自然 | cv2.GaussianBlur(mask, (21,21), 10) 羽化处理 |
| HuggingFace 模型下载缓慢或超时 | 国内网络访问受限 | export HF_ENDPOINT=https://hf-mirror.com |
| 每次推理均需等待较长时间 | 每次请求时重复加载模型 | 服务启动时加载一次并常驻显存 |
核心要点回顾
- 环境是最容易出问题的环节——CUDA 与 PyTorch 版本不匹配占环境问题的 80%,Python 3.11/3.12 是当前最稳定版本
- 远程 API 和本地部署使用同一份模型权重——区别仅在于计算归属和推理优化,选择取决于场景(数据隐私 vs 成本)
- diffusers 的三条核心管线(Text2Image / Image2Image / Inpainting)覆盖 90% 的图片处理需求——关键是理解 strength(改多少)和 mask(改哪里)两个参数
- Inpainting 的遮罩占比 >30% 时成功率显著下降——小面积修复用 OpenCV 内容感知填充,大面积创造新内容用扩散模型
- LoRA/ControlNet/IP-Adapter 三者协同使用可实现"角色+姿态+风格"的精确控制
- 生产环境的三大注意事项:异步任务队列、GPU 并发控制、模型常驻显存
这份命令速查表是系列第 5/6 篇的工具箱——搭配阅读效果最好。收藏这篇,下次配 ComfyUI 工作流直接翻出来抄。
上一篇:《Claude Code深度拆解》(文本AI线收束) | 下一篇:《AI面试准备指南》(番外) 系列合集:掘金AI合集