DeOldify开源大模型部署教程:874MB UNet模型在消费级GPU上的优化实践

1. 前言:让老照片重获新生的魔法

你有没有翻过家里的老相册?那些泛黄的黑白照片,记录着爷爷奶奶的青春、父母年轻时的模样,还有你小时候的可爱瞬间。但黑白照片总感觉少了点什么,对吧?色彩能让记忆变得更鲜活。

以前要给黑白照片上色,要么找专业修图师花大价钱,要么自己用PS一点点调色,费时费力效果还不一定自然。现在好了,有了DeOldify这个开源项目,你也能轻松给老照片上色了。

今天我要分享的,就是如何在你的电脑上快速部署这个神奇的图像上色工具。最棒的是,它用的是只有874MB的UNet模型,这意味着即使你只有一块普通的消费级显卡(比如RTX 3060、RTX 4060这种),也能流畅运行。

2. DeOldify到底是什么?

简单来说,DeOldify是一个基于深度学习的图像上色工具。它用了一个叫做U-Net的神经网络架构,专门处理图像分割和生成任务。

2.1 技术原理大白话版

想象一下,你小时候学过填色画。给你一张黑白线稿,你要根据经验判断:天空应该是蓝色,草地应该是绿色,人脸应该有肤色。DeOldify做的事情类似,但它不是靠经验,而是靠“学习”。

这个模型看过成千上万张彩色照片,学会了各种物体的颜色规律。当你给它一张黑白照片时,它会:

  1. 识别内容:先分析图片里有什么(人、树、建筑、天空等)
  2. 推理颜色:根据学到的知识,推测每个部分应该是什么颜色
  3. 生成彩色:把推测的颜色“画”到对应的位置上

2.2 为什么选择这个版本?

你可能听说过DeOldify有几个不同的模型版本,为什么我推荐这个874MB的UNet版本呢?原因很简单:

  • 体积小:874MB在深度学习模型里算是“轻量级”了,下载快,加载也快
  • 效果好:虽然体积小,但上色效果相当不错,特别是对人像和自然风景
  • 硬件友好:8GB显存的显卡就能跑,很多人的游戏显卡都能胜任
  • 速度快:处理一张普通照片只要5-10秒

3. 环境准备:你的电脑能跑吗?

在开始之前,我们先确认一下你的电脑配置。别担心,要求真的不高。

3.1 硬件要求

组件最低要求推荐配置
显卡NVIDIA GTX 1060 6GBRTX 3060 12GB
显存6GB8GB以上
内存8GB16GB
硬盘10GB可用空间20GB可用空间
系统Windows 10/11, Ubuntu 20.04+Ubuntu 22.04

重要提示:如果你用的是Mac电脑,很抱歉,这个方案主要针对NVIDIA显卡。Mac的M系列芯片虽然强大,但深度学习生态还是NVIDIA的CUDA更成熟。

3.2 软件环境

你需要准备以下软件:

  1. Python 3.8-3.10(别用太新的,兼容性可能有问题)
  2. CUDA 11.7或11.8(根据你的显卡驱动选择)
  3. PyTorch 1.13+(深度学习框架)
  4. Git(用来下载代码)

如果你不确定自己的环境,可以打开命令行(Windows用CMD或PowerShell,Linux/macOS用终端),输入以下命令检查:

# 检查Python版本
python --version

# 检查CUDA是否可用(如果有NVIDIA显卡)
nvidia-smi

# 检查Git
git --version

4. 一步步部署:从零到上色

好了,现在开始真正的部署过程。我会尽量详细,确保小白也能跟着做。

4.1 第一步:创建项目目录

首先,找个合适的地方放我们的项目。我建议在D盘或E盘创建一个专门的文件夹:

# Windows用户(在PowerShell中运行)
mkdir D:\AI_Projects
cd D:\AI_Projects
mkdir DeOldify_Deployment
cd DeOldify_Deployment

# Linux/macOS用户
mkdir -p ~/AI_Projects/DeOldify_Deployment
cd ~/AI_Projects/DeOldify_Deployment

4.2 第二步:下载模型文件

DeOldify的模型文件比较大,我们先下载下来。这里我提供一个国内能快速下载的地址:

# 创建模型目录
mkdir models
cd models

# 下载UNet模型(874MB版本)
# 如果你在国内,可以用这个镜像地址(把下面的URL复制到浏览器下载)
# https://modelscope.cn/models/iic/cv_unet_image-colorization

# 或者用wget命令(Linux/macOS)
wget https://modelscope.cn/api/v1/models/iic/cv_unet_image-colorization/repo?Revision=master&FilePath=cv_unet_image-colorization.tar.gz

# 解压
tar -zxvf cv_unet_image-colorization.tar.gz

# 回到项目根目录
cd ..

注意:如果下载速度慢,可以尝试用迅雷或其他下载工具。模型文件大概874MB,下载需要一些时间。

4.3 第三步:安装Python依赖

现在我们来安装需要的Python包。先创建一个虚拟环境(这样不会搞乱你系统的Python环境):

# 创建虚拟环境
python -m venv venv

# 激活虚拟环境
# Windows
venv\Scripts\activate
# Linux/macOS
source venv/bin/activate

# 安装PyTorch(根据你的CUDA版本选择)
# CUDA 11.7
pip install torch torchvision torchaudio --index-url https://download.pytorch.org/whl/cu117

# CUDA 11.8  
pip install torch torchvision torchaudio --index-url https://download.pytorch.org/whl/cu118

# CPU版本(如果没有NVIDIA显卡)
pip install torch torchvision torchaudio

# 安装其他依赖
pip install flask gunicorn pillow requests opencv-python numpy

安装过程可能需要几分钟,取决于你的网速。如果某个包安装失败,可以多试几次,或者用清华镜像源:

pip install -i https://pypi.tuna.tsinghua.edu.cn/simple 包名

4.4 第四步:编写服务代码

我们来创建一个简单的Web服务,这样就能通过浏览器上传图片了。创建一个叫app.py的文件:

import os
import cv2
import numpy as np
from flask import Flask, request, jsonify, send_file
from PIL import Image
import io
import base64
import torch
from modelscope.pipelines import pipeline
from modelscope.utils.constant import Tasks

# 初始化Flask应用
app = Flask(__name__)

# 全局变量存储模型
colorizer = None

def load_model():
    """加载上色模型"""
    global colorizer
    try:
        print("正在加载图像上色模型...")
        
        # 使用ModelScope的pipeline
        colorizer = pipeline(
            Tasks.image_colorization,
            model='damo/cv_unet_image-colorization',
            device='cuda' if torch.cuda.is_available() else 'cpu'
        )
        
        print(f"模型加载完成,使用设备: {'GPU' if torch.cuda.is_available() else 'CPU'}")
        return True
    except Exception as e:
        print(f"模型加载失败: {e}")
        return False

@app.route('/health', methods=['GET'])
def health_check():
    """健康检查接口"""
    return jsonify({
        'service': 'cv_unet_image-colorization',
        'status': 'healthy',
        'model_loaded': colorizer is not None,
        'device': 'cuda' if torch.cuda.is_available() else 'cpu'
    })

@app.route('/colorize', methods=['POST'])
def colorize_image():
    """图片上色接口"""
    if colorizer is None:
        return jsonify({'success': False, 'error': '模型未加载'}), 500
    
    try:
        # 检查是否有文件上传
        if 'image' not in request.files:
            return jsonify({'success': False, 'error': '没有上传图片文件'}), 400
        
        file = request.files['image']
        
        # 检查文件类型
        if file.filename == '':
            return jsonify({'success': False, 'error': '未选择文件'}), 400
        
        # 读取图片
        img_bytes = file.read()
        nparr = np.frombuffer(img_bytes, np.uint8)
        img = cv2.imdecode(nparr, cv2.IMREAD_COLOR)
        
        # 如果图片是彩色的,先转为灰度再上色(模拟黑白照片)
        if len(img.shape) == 3 and img.shape[2] == 3:
            # 实际上DeOldify可以直接处理彩色图片,但为了效果更好,我们可以先转灰度
            gray = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)
            img = cv2.cvtColor(gray, cv2.COLOR_GRAY2BGR)
        
        print(f"开始处理图片,尺寸: {img.shape}")
        
        # 使用模型上色
        result = colorizer(img)
        
        # 获取上色后的图片
        colored_img = result['output_img']
        
        # 转换为base64返回
        _, buffer = cv2.imencode('.png', colored_img)
        img_base64 = base64.b64encode(buffer).decode('utf-8')
        
        return jsonify({
            'success': True,
            'output_img_base64': img_base64,
            'format': 'png',
            'original_size': img.shape,
            'processed_size': colored_img.shape
        })
        
    except Exception as e:
        print(f"处理图片时出错: {e}")
        return jsonify({'success': False, 'error': str(e)}), 500

@app.route('/colorize_url', methods=['POST'])
def colorize_from_url():
    """从URL上色接口"""
    if colorizer is None:
        return jsonify({'success': False, 'error': '模型未加载'}), 500
    
    try:
        data = request.get_json()
        if not data or 'url' not in data:
            return jsonify({'success': False, 'error': '缺少URL参数'}), 400
        
        import requests
        from io import BytesIO
        
        # 从URL下载图片
        response = requests.get(data['url'])
        img_bytes = response.content
        
        # 后续处理与文件上传相同
        nparr = np.frombuffer(img_bytes, np.uint8)
        img = cv2.imdecode(nparr, cv2.IMREAD_COLOR)
        
        # 处理图片
        result = colorizer(img)
        colored_img = result['output_img']
        
        # 转换为base64
        _, buffer = cv2.imencode('.png', colored_img)
        img_base64 = base64.b64encode(buffer).decode('utf-8')
        
        return jsonify({
            'success': True,
            'output_img_base64': img_base64,
            'format': 'png'
        })
        
    except Exception as e:
        print(f"处理URL图片时出错: {e}")
        return jsonify({'success': False, 'error': str(e)}), 500

if __name__ == '__main__':
    # 先加载模型
    if load_model():
        print("服务启动中...")
        # 启动Flask服务
        app.run(host='0.0.0.0', port=7860, debug=False)
    else:
        print("模型加载失败,服务无法启动")

4.5 第五步:创建Web界面

光有后端API还不够,我们还需要一个简单的网页界面。创建一个templates文件夹,在里面放一个index.html文件:

<!DOCTYPE html>
<html lang="zh-CN">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>老照片上色工具 - DeOldify</title>
    <style>
        * {
            margin: 0;
            padding: 0;
            box-sizing: border-box;
        }
        
        body {
            font-family: 'Segoe UI', Tahoma, Geneva, Verdana, sans-serif;
            line-height: 1.6;
            color: #333;
            background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
            min-height: 100vh;
            padding: 20px;
        }
        
        .container {
            max-width: 1200px;
            margin: 0 auto;
            background: white;
            border-radius: 20px;
            box-shadow: 0 20px 60px rgba(0,0,0,0.3);
            overflow: hidden;
        }
        
        header {
            background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
            color: white;
            padding: 40px;
            text-align: center;
        }
        
        h1 {
            font-size: 2.8rem;
            margin-bottom: 10px;
            font-weight: 300;
        }
        
        .subtitle {
            font-size: 1.2rem;
            opacity: 0.9;
            font-weight: 300;
        }
        
        .main-content {
            padding: 40px;
            display: grid;
            grid-template-columns: 1fr 1fr;
            gap: 40px;
        }
        
        @media (max-width: 768px) {
            .main-content {
                grid-template-columns: 1fr;
            }
        }
        
        .upload-section {
            background: #f8f9fa;
            padding: 30px;
            border-radius: 15px;
            border: 2px dashed #dee2e6;
            transition: all 0.3s ease;
        }
        
        .upload-section:hover {
            border-color: #667eea;
            background: #f0f2ff;
        }
        
        .upload-area {
            text-align: center;
            padding: 40px 20px;
            cursor: pointer;
        }
        
        .upload-icon {
            font-size: 4rem;
            color: #667eea;
            margin-bottom: 20px;
        }
        
        .upload-text {
            font-size: 1.1rem;
            color: #666;
            margin-bottom: 10px;
        }
        
        .file-input {
            display: none;
        }
        
        .url-input {
            width: 100%;
            padding: 12px 15px;
            border: 1px solid #dee2e6;
            border-radius: 8px;
            font-size: 1rem;
            margin-top: 20px;
        }
        
        .btn {
            background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
            color: white;
            border: none;
            padding: 15px 30px;
            font-size: 1.1rem;
            border-radius: 8px;
            cursor: pointer;
            transition: transform 0.2s ease;
            width: 100%;
            margin-top: 20px;
            font-weight: 600;
        }
        
        .btn:hover {
            transform: translateY(-2px);
            box-shadow: 0 10px 20px rgba(102, 126, 234, 0.3);
        }
        
        .btn:active {
            transform: translateY(0);
        }
        
        .btn:disabled {
            opacity: 0.6;
            cursor: not-allowed;
        }
        
        .result-section {
            padding: 30px;
        }
        
        .image-container {
            display: grid;
            grid-template-columns: 1fr 1fr;
            gap: 20px;
            margin-bottom: 30px;
        }
        
        .image-box {
            background: #f8f9fa;
            border-radius: 10px;
            overflow: hidden;
            border: 1px solid #dee2e6;
        }
        
        .image-box img {
            width: 100%;
            height: 300px;
            object-fit: contain;
            background: white;
        }
        
        .image-label {
            padding: 15px;
            background: white;
            text-align: center;
            font-weight: 600;
            color: #333;
            border-top: 1px solid #dee2e6;
        }
        
        .loading {
            display: none;
            text-align: center;
            padding: 20px;
        }
        
        .spinner {
            border: 4px solid #f3f3f3;
            border-top: 4px solid #667eea;
            border-radius: 50%;
            width: 40px;
            height: 40px;
            animation: spin 1s linear infinite;
            margin: 0 auto 15px;
        }
        
        @keyframes spin {
            0% { transform: rotate(0deg); }
            100% { transform: rotate(360deg); }
        }
        
        .status {
            padding: 15px;
            border-radius: 8px;
            margin-top: 20px;
            display: none;
        }
        
        .status.success {
            background: #d4edda;
            color: #155724;
            border: 1px solid #c3e6cb;
        }
        
        .status.error {
            background: #f8d7da;
            color: #721c24;
            border: 1px solid #f5c6cb;
        }
        
        footer {
            text-align: center;
            padding: 20px;
            color: #666;
            font-size: 0.9rem;
            border-top: 1px solid #dee2e6;
            background: #f8f9fa;
        }
        
        .tips {
            background: #fff3cd;
            border: 1px solid #ffeaa7;
            color: #856404;
            padding: 15px;
            border-radius: 8px;
            margin-top: 20px;
            font-size: 0.9rem;
        }
        
        .tip-title {
            font-weight: bold;
            margin-bottom: 5px;
        }
    </style>
</head>
<body>
    <div class="container">
        <header>
            <h1>🎨 老照片上色工具</h1>
            <p class="subtitle">基于 DeOldify 深度学习模型 · 让黑白记忆重焕色彩</p>
        </header>
        
        <div class="main-content">
            <div class="upload-section">
                <h2>上传图片</h2>
                <p style="color: #666; margin-bottom: 20px;">支持 JPG、PNG、BMP 格式,最大 50MB</p>
                
                <div class="upload-area" id="dropArea">
                    <div class="upload-icon">📁</div>
                    <div class="upload-text">点击或拖拽图片到这里</div>
                    <div style="color: #999; font-size: 0.9rem; margin-top: 10px;">
                        支持 JPG、PNG、JPEG、BMP、TIFF、WEBP
                    </div>
                </div>
                
                <input type="file" id="fileInput" class="file-input" accept=".jpg,.jpeg,.png,.bmp,.tiff,.webp">
                
                <div style="text-align: center; margin: 20px 0; color: #666;">或</div>
                
                <input type="text" id="urlInput" class="url-input" placeholder="输入图片URL地址...">
                
                <button id="colorizeBtn" class="btn">开始上色</button>
                
                <div class="loading" id="loading">
                    <div class="spinner"></div>
                    <p>正在处理图片,请稍候...</p>
                    <p style="font-size: 0.9rem; color: #666;">通常需要 5-10 秒</p>
                </div>
                
                <div class="status" id="status"></div>
                
                <div class="tips">
                    <div class="tip-title">💡 使用提示:</div>
                    <p>1. 使用清晰的黑白照片效果最佳</p>
                    <p>2. 人像、风景、建筑照片上色效果较好</p>
                    <p>3. 处理时间取决于图片大小和服务器性能</p>
                    <p>4. 右键点击结果图片可以保存</p>
                </div>
            </div>
            
            <div class="result-section">
                <h2>上色结果</h2>
                <p style="color: #666; margin-bottom: 20px;">左侧为原始图片,右侧为上色结果</p>
                
                <div class="image-container">
                    <div class="image-box">
                        <img id="originalImage" src="https://via.placeholder.com/400x300/cccccc/969696?text=原始图片" alt="原始图片">
                        <div class="image-label">原始图片</div>
                    </div>
                    
                    <div class="image-box">
                        <img id="coloredImage" src="https://via.placeholder.com/400x300/667eea/ffffff?text=上色结果" alt="上色结果">
                        <div class="image-label">上色结果</div>
                    </div>
                </div>
                
                <div style="text-align: center;">
                    <button id="downloadBtn" class="btn" style="width: auto; padding: 12px 25px;" disabled>
                        💾 下载彩色图片
                    </button>
                </div>
                
                <div class="tips" style="margin-top: 30px;">
                    <div class="tip-title">🔧 技术信息:</div>
                    <p>• 模型: DeOldify UNet (874MB)</p>
                    <p>• 框架: PyTorch + ModelScope</p>
                    <p>• 支持设备: GPU / CPU</p>
                    <p>• 处理时间: 5-30秒(依图片大小)</p>
                </div>
            </div>
        </div>
        
        <footer>
            <p>Powered by DeOldify & ModelScope | 本服务仅供学习和研究使用</p>
            <p style="margin-top: 5px; font-size: 0.8rem;">© 2024 老照片上色工具 | 版本 1.0.0</p>
        </footer>
    </div>

    <script>
        // DOM元素
        const dropArea = document.getElementById('dropArea');
        const fileInput = document.getElementById('fileInput');
        const urlInput = document.getElementById('urlInput');
        const colorizeBtn = document.getElementById('colorizeBtn');
        const downloadBtn = document.getElementById('downloadBtn');
        const loading = document.getElementById('loading');
        const status = document.getElementById('status');
        const originalImage = document.getElementById('originalImage');
        const coloredImage = document.getElementById('coloredImage');
        
        let currentColoredImageData = null;
        
        // 点击上传区域触发文件选择
        dropArea.addEventListener('click', () => {
            fileInput.click();
        });
        
        // 拖拽上传功能
        dropArea.addEventListener('dragover', (e) => {
            e.preventDefault();
            dropArea.style.borderColor = '#667eea';
            dropArea.style.background = '#f0f2ff';
        });
        
        dropArea.addEventListener('dragleave', () => {
            dropArea.style.borderColor = '#dee2e6';
            dropArea.style.background = '#f8f9fa';
        });
        
        dropArea.addEventListener('drop', (e) => {
            e.preventDefault();
            dropArea.style.borderColor = '#dee2e6';
            dropArea.style.background = '#f8f9fa';
            
            const files = e.dataTransfer.files;
            if (files.length > 0) {
                handleFileSelect(files[0]);
            }
        });
        
        // 文件选择处理
        fileInput.addEventListener('change', (e) => {
            if (e.target.files.length > 0) {
                handleFileSelect(e.target.files[0]);
            }
        });
        
        function handleFileSelect(file) {
            // 检查文件类型
            const validTypes = ['image/jpeg', 'image/jpg', 'image/png', 'image/bmp', 'image/tiff', 'image/webp'];
            if (!validTypes.includes(file.type)) {
                showStatus('请选择图片文件(JPG、PNG、BMP等格式)', 'error');
                return;
            }
            
            // 检查文件大小(50MB限制)
            if (file.size > 50 * 1024 * 1024) {
                showStatus('文件太大,请选择小于50MB的图片', 'error');
                return;
            }
            
            // 显示预览
            const reader = new FileReader();
            reader.onload = (e) => {
                originalImage.src = e.target.result;
                urlInput.value = ''; // 清空URL输入
                currentColoredImageData = null;
                downloadBtn.disabled = true;
                showStatus('图片已选择,点击"开始上色"按钮进行处理', 'success');
            };
            reader.readAsDataURL(file);
        }
        
        // 开始上色按钮点击事件
        colorizeBtn.addEventListener('click', async () => {
            const file = fileInput.files[0];
            const url = urlInput.value.trim();
            
            if (!file && !url) {
                showStatus('请选择图片文件或输入图片URL', 'error');
                return;
            }
            
            // 显示加载中
            loading.style.display = 'block';
            colorizeBtn.disabled = true;
            status.style.display = 'none';
            
            try {
                let formData = new FormData();
                
                if (file) {
                    // 文件上传
                    formData.append('image', file);
                    var apiUrl = '/colorize';
                } else if (url) {
                    // URL上传
                    formData = JSON.stringify({ url: url });
                    var apiUrl = '/colorize_url';
                }
                
                const response = await fetch(apiUrl, {
                    method: 'POST',
                    body: file ? formData : formData,
                    headers: file ? {} : { 'Content-Type': 'application/json' }
                });
                
                const result = await response.json();
                
                if (result.success) {
                    // 显示上色结果
                    coloredImage.src = 'data:image/png;base64,' + result.output_img_base64;
                    currentColoredImageData = result.output_img_base64;
                    downloadBtn.disabled = false;
                    showStatus('上色完成!可以下载彩色图片了', 'success');
                } else {
                    showStatus('上色失败:' + (result.error || '未知错误'), 'error');
                }
            } catch (error) {
                showStatus('网络错误:' + error.message, 'error');
            } finally {
                loading.style.display = 'none';
                colorizeBtn.disabled = false;
            }
        });
        
        // 下载按钮点击事件
        downloadBtn.addEventListener('click', () => {
            if (!currentColoredImageData) return;
            
            // 创建下载链接
            const link = document.createElement('a');
            link.href = 'data:image/png;base64,' + currentColoredImageData;
            link.download = 'colored_image_' + new Date().getTime() + '.png';
            document.body.appendChild(link);
            link.click();
            document.body.removeChild(link);
            
            showStatus('图片下载开始', 'success');
        });
        
        // URL输入框回车键触发上色
        urlInput.addEventListener('keypress', (e) => {
            if (e.key === 'Enter') {
                colorizeBtn.click();
            }
        });
        
        // 显示状态信息
        function showStatus(message, type) {
            status.textContent = message;
            status.className = 'status ' + type;
            status.style.display = 'block';
            
            // 3秒后自动隐藏
            setTimeout(() => {
                status.style.display = 'none';
            }, 3000);
        }
        
        // 页面加载时检查服务状态
        window.addEventListener('load', async () => {
            try {
                const response = await fetch('/health');
                const data = await response.json();
                if (data.status === 'healthy') {
                    showStatus('服务已就绪,可以开始上色', 'success');
                }
            } catch (error) {
                showStatus('服务连接中...', 'error');
            }
        });
    </script>
</body>
</html>

4.6 第六步:创建启动脚本

为了让服务更容易管理,我们创建几个脚本文件。先创建一个scripts文件夹,然后创建以下脚本:

start.sh(Linux/macOS)或start.bat(Windows):

#!/bin/bash
# start.sh - Linux/macOS启动脚本

echo "启动DeOldify图像上色服务..."

# 激活虚拟环境
source venv/bin/activate

# 启动Flask服务
python app.py
@echo off
REM start.bat - Windows启动脚本

echo 启动DeOldify图像上色服务...

REM 激活虚拟环境
call venv\Scripts\activate

REM 启动Flask服务
python app.py

stop.sh(Linux/macOS):

#!/bin/bash
# stop.sh - 停止服务

echo "停止DeOldify服务..."

# 查找并杀死相关进程
pkill -f "python app.py"
pkill -f "gunicorn"

echo "服务已停止"

5. 优化技巧:让服务跑得更快更稳

现在基本功能都有了,但我们可以做一些优化,让服务更好用。

5.1 GPU内存优化

如果你的显卡显存不大(比如8GB),可以添加以下代码来优化内存使用:

# 在app.py的load_model函数中添加
import torch

def load_model():
    """加载上色模型(优化版)"""
    global colorizer
    
    # 设置GPU内存优化
    if torch.cuda.is_available():
        # 清理GPU缓存
        torch.cuda.empty_cache()
        
        # 设置内存分配策略(对于小显存显卡很重要)
        torch.backends.cudnn.benchmark = True
        
        # 限制GPU内存使用(根据你的显存调整)
        total_memory = torch.cuda.get_device_properties(0).total_memory
        if total_memory < 9 * 1024**3:  # 小于9GB
            # 为小显存显卡优化
            torch.cuda.set_per_process_memory_fraction(0.5)  # 最多使用50%显存
            print("检测到小显存显卡,已启用内存优化")
    
    # ... 其余代码不变 ...

5.2 图片预处理优化

有些图片太大,处理起来很慢。我们可以添加图片预处理:

def preprocess_image(img, max_size=1024):
    """预处理图片,调整大小"""
    height, width = img.shape[:2]
    
    # 如果图片太大,等比例缩小
    if max(height, width) > max_size:
        scale = max_size / max(height, width)
        new_width = int(width * scale)
        new_height = int(height * scale)
        img = cv2.resize(img, (new_width, new_height), interpolation=cv2.INTER_AREA)
        print(f"图片已从 {width}x{height} 调整到 {new_width}x{new_height}")
    
    return img

# 在colorize_image函数中使用
def colorize_image():
    # ... 前面的代码 ...
    
    # 预处理图片
    img = preprocess_image(img)
    
    # ... 后面的代码 ...

5.3 添加批量处理功能

如果你想一次处理多张图片,可以添加批量处理接口:

@app.route('/batch_colorize', methods=['POST'])
def batch_colorize():
    """批量图片上色"""
    if colorizer is None:
        return jsonify({'success': False, 'error': '模型未加载'}), 500
    
    try:
        # 支持多文件上传
        files = request.files.getlist('images')
        
        if not files:
            return jsonify({'success': False, 'error': '没有上传图片文件'}), 400
        
        results = []
        
        for i, file in enumerate(files):
            try:
                # 处理每张图片
                img_bytes = file.read()
                nparr = np.frombuffer(img_bytes, np.uint8)
                img = cv2.imdecode(nparr, cv2.IMREAD_COLOR)
                
                # 预处理
                img = preprocess_image(img)
                
                # 上色
                result = colorizer(img)
                colored_img = result['output_img']
                
                # 转换为base64
                _, buffer = cv2.imencode('.png', colored_img)
                img_base64 = base64.b64encode(buffer).decode('utf-8')
                
                results.append({
                    'filename': file.filename,
                    'success': True,
                    'output_img_base64': img_base64
                })
                
            except Exception as e:
                results.append({
                    'filename': file.filename,
                    'success': False,
                    'error': str(e)
                })
        
        return jsonify({
            'success': True,
            'total': len(files),
            'processed': len([r for r in results if r['success']]),
            'results': results
        })
        
    except Exception as e:
        return jsonify({'success': False, 'error': str(e)}), 500

6. 实际测试:看看效果怎么样

理论说再多不如实际测试。我来展示几个实际的上色效果。

6.1 测试准备

首先准备几张测试图片:

  1. 一张黑白人像照片
  2. 一张风景照片
  3. 一张建筑照片

你可以从网上找一些老照片,或者用手机拍张照片转成黑白。

6.2 启动服务

# 激活虚拟环境
# Windows
venv\Scripts\activate
# Linux/macOS
source venv/bin/activate

# 启动服务
python app.py

如果一切正常,你会看到类似这样的输出:

正在加载图像上色模型...
模型加载完成,使用设备: GPU
服务启动中...
 * Serving Flask app 'app'
 * Debug mode: off
 * Running on all addresses (0.0.0.0)
 * Running on http://127.0.0.1:7860
 * Running on http://192.168.1.100:7860

6.3 访问Web界面

打开浏览器,访问:http://localhost:7860

你会看到一个漂亮的上色工具界面。点击上传区域选择图片,或者拖拽图片到上传区域,然后点击"开始上色"按钮。

6.4 效果对比

我测试了几种类型的图片,效果如下:

人像照片:

  • 优点:肤色还原自然,头发颜色准确
  • 不足:有时候衣服颜色可能不太准确
  • 建议:使用清晰、光线均匀的人像照片

风景照片:

  • 优点:天空、草地、树木的颜色还原很好
  • 不足:复杂场景下的颜色可能过于鲜艳
  • 建议:自然风景效果最佳

建筑照片:

  • 优点:砖墙、屋顶等材质颜色还原准确
  • 不足:现代建筑玻璃反光处理一般
  • 建议:传统建筑效果更好

7. 常见问题与解决方案

在实际使用中,你可能会遇到一些问题。这里我整理了一些常见问题和解决方法。

7.1 模型加载失败

问题:启动时提示"模型加载失败"

可能原因:

  1. 模型文件损坏或下载不完整
  2. 网络问题导致无法从ModelScope下载
  3. 磁盘空间不足

解决方案:

# 重新下载模型
cd models
rm -rf cv_unet_image-colorization
# 重新下载(使用国内镜像)
wget https://modelscope.cn/api/v1/models/iic/cv_unet_image-colorization/repo?Revision=master&FilePath=cv_unet_image-colorization.tar.gz

# 检查磁盘空间
df -h  # Linux/macOS
# 或
wmic logicaldisk get size,freespace,caption  # Windows

7.2 显存不足

问题:处理图片时提示CUDA out of memory

可能原因:

  1. 图片太大
  2. 同时处理多张图片
  3. 显卡显存太小

解决方案:

# 方法1:在代码中添加图片大小限制
def preprocess_image(img, max_size=768):  # 从1024改为768
    # ... 代码不变 ...

# 方法2:添加显存清理
import gc
import torch

def colorize_image():
    try:
        # ... 处理代码 ...
    finally:
        # 清理显存
        if torch.cuda.is_available():
            torch.cuda.empty_cache()
        gc.collect()

7.3 处理速度慢

问题:上色一张图片要很久

可能原因:

  1. 使用CPU而不是GPU
  2. 图片太大
  3. 电脑性能不足

解决方案:

# 检查是否使用GPU
python -c "import torch; print(torch.cuda.is_available())"

# 如果返回False,需要检查:
# 1. 是否正确安装了CUDA版本的PyTorch
# 2. 显卡驱动是否安装
# 3. CUDA版本是否匹配

# 优化图片大小
# 在上传前,先用工具压缩图片
# 推荐使用500-1000像素宽度的图片

7.4 Web界面无法访问

问题:浏览器打不开localhost:7860

可能原因:

  1. 服务没有启动成功
  2. 端口被占用
  3. 防火墙阻止

解决方案:

# 检查服务是否运行
ps aux | grep python  # Linux/macOS
# 或
tasklist | findstr python  # Windows

# 检查端口占用
netstat -ano | findstr :7860  # Windows
# 或
lsof -i :7860  # Linux/macOS

# 如果端口被占用,可以修改端口
# 在app.py中修改:
# app.run(host='0.0.0.0', port=7870)  # 改为7870

8. 进阶使用:API集成与自动化

如果你想把上色功能集成到自己的应用中,这里有一些进阶用法。

8.1 Python客户端示例

import requests
import base64
from PIL import Image
from io import BytesIO
import os

class DeOldifyClient:
    """DeOldify API客户端"""
    
    def __init__(self, base_url="http://localhost:7860"):
        self.base_url = base_url
    
    def health_check(self):
        """检查服务状态"""
        try:
            response = requests.get(f"{self.base_url}/health", timeout=5)
            return response.json()
        except:
            return {"status": "unavailable"}
    
    def colorize_file(self, image_path):
        """上传文件上色"""
        with open(image_path, 'rb') as f:
            files = {'image': f}
            response = requests.post(
                f"{self.base_url}/colorize",
                files=files,
                timeout=30
            )
        return response.json()
    
    def colorize_url(self, image_url):
        """通过URL上色"""
        data = {"url": image_url}
        response = requests.post(
            f"{self.base_url}/colorize_url",
            json=data,
            timeout=30
        )
        return response.json()
    
    def save_colored_image(self, result, output_path):
        """保存上色后的图片"""
        if result.get('success'):
            img_data = base64.b64decode(result['output_img_base64'])
            img = Image.open(BytesIO(img_data))
            img.save(output_path)
            return True
        return False
    
    def batch_process(self, input_folder, output_folder):
        """批量处理文件夹中的图片"""
        os.makedirs(output_folder, exist_ok=True)
        
        results = []
        for filename in os.listdir(input_folder):
            if filename.lower().endswith(('.jpg', '.jpeg', '.png', '.bmp')):
                input_path = os.path.join(input_folder, filename)
                output_path = os.path.join(output_folder, f"colored_{filename}")
                
                print(f"处理: {filename}")
                result = self.colorize_file(input_path)
                
                if self.save_colored_image(result, output_path):
                    results.append((filename, True))
                    print(f"  ✓ 成功")
                else:
                    results.append((filename, False))
                    print(f"  ✗ 失败: {result.get('error', '未知错误')}")
        
        return results

# 使用示例
if __name__ == "__main__":
    client = DeOldifyClient()
    
    # 检查服务
    status = client.health_check()
    print(f"服务状态: {status}")
    
    # 单张图片上色
    result = client.colorize_file("old_photo.jpg")
    if client.save_colored_image(result, "colored_photo.jpg"):
        print("上色成功!")
    
    # 批量处理
    client.batch_process("./old_photos", "./colored_photos")

8.2 与其他工具集成

你可以把DeOldify集成到各种工作流中:

与Photoshop集成:

# 使用Photoshop的Python API
import photoshop.api as ps

def colorize_for_photoshop(image_path):
    """为Photoshop准备上色图片"""
    client = DeOldifyClient()
    result = client.colorize_file(image_path)
    
    if result['success']:
        # 保存临时文件
        temp_path = "temp_colored.png"
        client.save_colored_image(result, temp_path)
        
        # 在Photoshop中打开
        app = ps.Application()
        doc = app.open(temp_path)
        
        # 进行后续处理...
        return doc
    return None

与网站集成:

<!-- 简单的上传表单 -->
<form id="colorizeForm">
    <input type="file" id="photoUpload" accept="image/*">
    <button type="submit">上色</button>
</form>

<script>
document.getElementById('colorizeForm').addEventListener('submit', async (e) => {
    e.preventDefault();
    
    const fileInput = document.getElementById('photoUpload');
    const formData = new FormData();
    formData.append('image', fileInput.files[0]);
    
    const response = await fetch('http://你的服务器IP:7860/colorize', {
        method: 'POST',
        body: formData
    });
    
    const result = await response.json();
    
    if (result.success) {
        // 显示结果
        const img = document.createElement('img');
        img.src = 'data:image/png;base64,' + result.output_img_base64;
        document.body.appendChild(img);
    }
});
</script>

9. 性能优化建议

如果你想让服务跑得更快、更稳定,这里有一些优化建议。

9.1 使用Gunicorn替代Flask开发服务器

Flask自带的服务器不适合生产环境。改用Gunicorn:

# 安装Gunicorn
pip install gunicorn

# 创建Gunicorn配置文件gunicorn_config.py
workers = 2
worker_class = 'sync'
bind = '0.0.0.0:7860'
timeout = 120
keepalive = 5

# 启动服务
gunicorn -c gunicorn_config.py app:app

9.2 添加缓存机制

对于相同的图片,可以缓存处理结果:

import hashlib
import pickle
import os
from functools import lru_cache

class ColorizerWithCache:
    def __init__(self, model):
        self.model = model
        self.cache_dir = "cache"
        os.makedirs(self.cache_dir, exist_ok=True)
    
    def get_cache_key(self, image_data):
        """生成缓存键"""
        return hashlib.md5(image_data).hexdigest()
    
    def colorize(self, image_data):
        """带缓存的上色"""
        cache_key = self.get_cache_key(image_data)
        cache_path = os.path.join(self.cache_dir, f"{cache_key}.pkl")
        
        # 检查缓存
        if os.path.exists(cache_path):
            print(f"从缓存加载: {cache_key}")
            with open(cache_path, 'rb') as f:
                return pickle.load(f)
        
        # 处理图片
        nparr = np.frombuffer(image_data, np.uint8)
        img = cv2.imdecode(nparr, cv2.IMREAD_COLOR)
        result = self.model(img)
        
        # 保存到缓存
        with open(cache_path, 'wb') as f:
            pickle.dump(result, f)
        
        return result

9.3 使用Nginx反向代理

如果你有域名,可以用Nginx做反向代理:

# nginx配置示例
server {
    listen 80;
    server_name colorize.yourdomain.com;
    
    location / {
        proxy_pass http://127.0.0.1:7860;
        proxy_set_header Host $host;
        proxy_set_header X-Real-IP $remote_addr;
        proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
        
        # 超时设置
        proxy_connect_timeout 60s;
        proxy_send_timeout 60s;
        proxy_read_timeout 60s;
    }
    
    # 限制上传大小
    client_max_body_size 50M;
}

10. 总结

通过这个教程,你应该已经成功在本地部署了DeOldify图像上色服务。我们来回顾一下关键点:

10.1 部署要点总结

  1. 环境准备:确保有NVIDIA显卡和合适的CUDA版本
  2. 模型下载:874MB的UNet模型,下载快、运行快
  3. 服务搭建:用Flask构建Web服务,提供API和界面
  4. 优化调整:根据你的硬件调整参数,特别是显存设置
  5. 测试验证:用不同类型的图片测试效果

10.2 实际应用建议

  • 家庭使用:给老照片上色,让家族记忆更鲜活
  • 摄影工作室:快速处理黑白照片,提高工作效率
  • 内容创作:为文章、视频配图添加色彩
  • 教育用途:学习深度学习图像处理的实际应用

10.3 后续优化方向

如果你对这个项目感兴趣,还可以继续优化:

  1. 模型微调:用特定类型的图片训练,获得更好的上色效果
  2. 批量处理:添加队列系统,支持大量图片处理
  3. 效果调整:让用户能调整上色强度、风格等参数
  4. 移动端适配:开发手机App,随时随地给照片上色

最重要的是,这个项目展示了如何在消费级硬件上运行深度学习模型。874MB的模型大小意味着它可以在很多普通电脑上运行,让更多人能体验到AI技术的魅力。

现在,你可以开始给你的老照片上色了。试试看,效果可能会让你惊喜!


获取更多AI镜像

想探索更多AI镜像和应用场景?访问 CSDN星图镜像广场,提供丰富的预置镜像,覆盖大模型推理、图像生成、视频生成、模型微调等多个领域,支持一键部署。

Logo

聚焦RDK与具身智能,汇集机器人开发教程、开源案例和技术交流

更多推荐