教程展示用Real-ESRGAN本地部署图像放大工具,避免云API限额约束,可直接集成到开发工作流或产品中。
低分辨率图像无处不在——压缩后的缩略图、旧的截图,或者那张你迫不及待想要重用的视频帧。作为开发者,你不想依赖那些月额度限制的云 API。你想要一个自己能掌控、在本地运行、可以集成到工作流中的方案。
本教程将向你展示如何用 Python 和 Real-ESRGAN 构建自己的 AI 图像放大器——一个最先进的超分辨率模型,完全离线运行。
Real-ESRGAN(增强型超分辨率生成对抗网络)是现存最好的开源放大模型之一:
本地运行 —— 无需 API 密钥、无月额度限制、无隐私顾虑
处理真实图像效果好 —— 经过训练能修复压缩伪影、模糊和噪声,而不仅仅是干净的合成图像
多个缩放因子 —— 支持 2 倍、4 倍及自定义放大倍数
活跃的社区 —— 模型持续改进,有专门针对人脸和动画的变体
# Python 3.8+ 推荐
pip install torch torchvision --index-url https://download.pytorch.org/whl/cu118 # GPU
# 或仅 CPU 版本:
pip install torch torchvision
pip install basicsr facexlib gfpgan
pip install realesrgan
注:如果你在 Mac(MPS)或纯 CPU 机器上,同样的代码能用——只是会慢一些。对一张 1MP 图像进行 4K 放大在 CPU 上大约需要 30-60 秒。
这是一个最小化、依赖紧凑的版本,处理常见场景:
import argparse
import time
from pathlib import Path
import cv2
import torch
from realesrgan import RealESRGANer
from basicsr.archs.rrdbnet_arch import RRDBNet
def build_upscaler(scale=4, gpu=True):
model = RRDBNet(num_in_ch=3, num_out_ch=3, num_feat=64, num_block=23, num_grow_ch=32, scale=scale)
weights = "https://github.com/xinntao/Real-ESRGAN/releases/download/v0.1.0/RealESRGAN_x4plus.pth"
device = torch.device("cuda" if gpu and torch.cuda.is_available() else "cpu")
print(f"[INFO] Using device: {device}")
upscaler = RealESRGANer(scale=scale, model_path=weights, model=model, tile=0, tile_pad=10, pre_pad=0, half=False, device=device)
return upscaler
def upscale_image(upscaler, input_path, output_path):
img = cv2.imread(input_path, cv2.IMREAD_COLOR)
if img is None:
raise FileNotFoundError(f"Could not read image: {input_path}")
output, _ = upscaler.enhance(img, outscale=4)
cv2.imwrite(output_path, output)
print(f"[OK] {input_path} -> {output_path}")
if __name__ == "__main__":
import argparse
parser = argparse.ArgumentParser(description="AI image upscaler")
parser.add_argument("input", type=str)
parser.add_argument("--output", default="output.png")
parser.add_argument("--scale", type=int, default=4, choices=[2, 4])
parser.add_argument("--cpu", action="store_true")
args = parser.parse_args()
upscaler = build_upscaler(scale=args.scale, gpu=not args.cpu)
upscale_image(upscaler, args.input, args.output)
用法:
python upscaler.py input.jpg --output result.png --scale 4
单张图像很好,但真实工作流需要批量处理。让我们添加目录支持:
def upscale_directory(upscaler, in_dir, out_dir, extensions=(".jpg", ".jpeg", ".png", ".webp")):
in_dir = Path(in_dir)
out_dir = Path(out_dir)
out_dir.mkdir(parents=True, exist_ok=True)
images = [p for p in in_dir.iterdir() if p.suffix.lower() in extensions]
print(f"[INFO] Found {len(images)} images to process")
for img_path in images:
out_path = out_dir / f"{img_path.stem}_x4.png"
try:
upscale_image(upscaler, str(img_path), str(out_path))
except Exception as e:
print(f"[ERROR] Failed {img_path.name}: {e}")
对于大型目录,添加分块处理来避免 GPU 内存溢出:
upscaler = RealESRGANer(scale=4, model_path=weights, model=model, tile=400, tile_pad=10, pre_pad=0, half=False, device=device)
分块处理在接缝质量上做出微小的权衡,以换取巨大的内存节省——在放大 8K+ 图像或在笔记本 GPU 上运行时至关重要。
Real-ESRGAN 单独使用在处理人脸时会有困难——可能看起来蜡质或扭曲。GFPGAN 模型能解决这个问题:
from gfpgan import GFPGANer
def build_face_upscaler(device="cpu"):
face_enhancer = GFPGANer(
model_path="https://github.com/TencentARC/GFPGAN/releases/download/v1.3.0/GFPGANv1.3.pth",
upscale=2,
arch="clean",
channel_multiplier=2,
bg_upsampler=None,
device=device,
)
return face_enhancer
对于旧家庭照片或低分辨率头像,这是个改变游戏规则的工具。
想要把你的 upscaler 暴露为服务?这是一个最小化的 FastAPI 端点:
from fastapi import FastAPI, File, UploadFile
from fastapi.responses import Response
import numpy as np
import cv2
app = FastAPI()
upscaler = build_upscaler(scale=4, gpu=False)
@app.post("/upscale")
async def upscale(file: UploadFile = File(...)):
data = await file.read()
img = cv2.imdecode(np.frombuffer(data, np.uint8), cv2.IMREAD_COLOR)
output, _ = upscaler.enhance(img, outscale=4)
ok, encoded = cv2.imencode(".png", output)
return Response(content=encoded.tobytes(), media_type="image/png")
启动服务:
uvicorn api:app --host 0.0.0.0 --port 8000
调用示例:
curl -X POST -F "file=@photo.jpg" http://localhost:8000/upscale -o result.png
中档 RTX 3060(12GB)上的粗略耗时:
CPU 上大约要乘以 10-15 倍。第一次运行会慢一点(模型下载和初始化)。
输出是黑色的 —— 通常是 dtype/范围问题。确保输入是 uint8 且 cv2.imwrite 获得有效的数组。如果你用了 half=True 并得到 NaN,你的 GPU 可能不支持 FP16 —— 设置 half=False。
大图像导致内存溢出 —— 使用 tile=400 和 tile_pad=10。永远不要在消费级 GPU 上不分块地放大 8K 图像。
CUDA 错误(新安装) —— 用与驱动版本匹配的正确 CUDA 索引 URL(cu118、cu121 等)安装 PyTorch。
模型无法自动下载 —— 将 model_path 设置为本地文件或用 wget 预先下载。
upscaler/
├── upscaler.py # 核心 + CLI
├── batch.py # 目录处理
├── face.py # GFPGAN 人脸增强
├── api.py # FastAPI 服务
├── requirements.txt
└── README.md
现在你拥有一个完全本地的、可脚本化的 AI 图像放大器。无需 API 密钥、无按图收费、无数据离开你的机器。它能处理单张图像、批量图像、人脸,甚至可以作为一个小型 Web 服务运行。
从小处开始——先用 --scale 2 放大几张测试图像来评估质量,然后对确定的图像提升到 4 倍。这个模型在让压缩 JPEG 看起来清晰方面出奇地出色。
如果你觉得这篇文章有用,可以查看 AIXHDD 上的原始文章了解更多 AI 工具分解和创意工作流。