国产操作系统适配:DamoFD-0.5G在统信UOS上的部署实践

最近在做一个智慧社区的项目,需要用到人脸检测功能。团队里的小伙伴推荐了达摩院的DamoFD-0.5G模型,说是轻量又精准,特别适合边缘设备。但问题来了——我们的服务器用的是统信UOS,一个国产的操作系统,很多常见的AI模型部署教程在这里都不太灵光。

我花了两天时间,踩了不少坑,总算把DamoFD-0.5G在统信UOS上跑起来了。整个过程比在常见的Linux发行版上要复杂一些,主要是国产CPU架构和系统依赖库的适配问题。今天就把我的部署经验完整地分享出来,如果你也在信创环境下搞AI部署,这篇应该能帮你省下不少时间。

1. 环境准备:从零开始的UOS系统配置

在统信UOS上部署AI应用,第一步不是装Python,而是搞清楚你的硬件架构。UOS通常运行在国产CPU上,比如飞腾或者龙芯,这和常见的x86架构有很大不同。

1.1 确认系统信息

打开终端,先看看你的系统到底是什么配置:

# 查看CPU架构
uname -m

# 查看系统版本
cat /etc/os-release

# 查看Python版本(如果已安装)
python3 --version

在我的机器上,输出是这样的:

  • CPU架构:aarch64(飞腾处理器)
  • 系统版本:统信UOS 20
  • Python版本:3.7.5(系统自带)

重要提示:如果你的CPU架构是aarch64(ARM架构),后面安装PyTorch时要特别注意,不能直接用pip install torch,需要找ARM架构的版本。

1.2 安装基础开发环境

UOS系统默认的软件源可能不全,建议先配置好开发环境:

# 更新软件源
sudo apt update

# 安装基础开发工具
sudo apt install -y build-essential cmake git wget curl

# 安装Python开发环境
sudo apt install -y python3-dev python3-pip python3-venv

# 安装图像处理相关依赖(重要!)
sudo apt install -y libgl1-mesa-glx libglib2.0-0 libsm6 libxrender1 libxext6

这里有个小坑:UOS系统默认可能缺少一些图形库,如果不提前安装,后面运行人脸检测时可能会报错,提示找不到某些.so文件。

2. Python环境与PyTorch安装

这是整个部署过程中最关键的步骤,也是坑最多的地方。

2.1 创建独立的Python虚拟环境

我强烈建议不要用系统自带的Python,而是创建一个独立的虚拟环境:

# 创建项目目录
mkdir damofd_uos && cd damofd_uos

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

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

激活后,你的命令行提示符前面应该会出现(venv)字样,表示现在是在虚拟环境中操作。

2.2 安装PyTorch(ARM架构特别版)

对于ARM架构的CPU,不能直接用PyTorch官网的pip安装命令。我找到了两种可行的方案:

方案一:使用预编译的ARM版本(推荐)

# 先升级pip
pip install --upgrade pip

# 安装PyTorch(ARM架构版本)
pip install torch==1.8.1 torchvision==0.9.1 -f https://torch.kmtea.eu/whl/stable.html

这个torch.kmtea.eu源提供了ARM架构的预编译包,亲测在飞腾CPU上可用。

方案二:从源码编译(耗时但最可靠)

如果上面的方法不行,或者你需要特定版本的PyTorch,可以考虑从源码编译:

# 安装编译依赖
sudo apt install -y ninja-build git cmake

# 克隆PyTorch源码
git clone --recursive https://github.com/pytorch/pytorch
cd pytorch

# 切换到稳定版本(比如1.8.1)
git checkout v1.8.1

# 安装Python依赖
pip install -r requirements.txt

# 编译安装(这步很慢,可能要几个小时)
python setup.py install

编译过程确实很慢,我的飞腾FT-2000/4处理器编译了大概3个小时。但好处是编译出来的版本绝对适配你的硬件。

2.3 验证PyTorch安装

安装完成后,写个小脚本验证一下:

import torch

print(f"PyTorch版本: {torch.__version__}")
print(f"CUDA是否可用: {torch.cuda.is_available()}")
print(f"设备信息: {torch.cuda.get_device_name(0) if torch.cuda.is_available() else 'CPU only'}")

# 测试一个简单的张量运算
x = torch.rand(3, 3)
print(f"随机矩阵:\n{x}")
print(f"矩阵乘法结果:\n{x @ x.t()}")

在ARM架构的CPU上,CUDA通常不可用(除非你有ARM架构的NVIDIA显卡),所以看到"CPU only"是正常的。

3. 安装ModelScope和DamoFD依赖

ModelScope是达摩院的模型服务平台,DamoFD模型就是通过它来管理的。

3.1 安装ModelScope核心库

# 安装ModelScope核心库
pip install modelscope

# 安装计算机视觉相关依赖
pip install "modelscope[cv]" -f https://modelscope.oss-cn-beijing.aliyuncs.com/releases/repo.html

这里又有一个坑:ModelScope的一些依赖包托管在阿里云OSS上,所以需要加上-f参数指定源。

3.2 安装其他必要依赖

DamoFD模型还需要一些额外的依赖:

# 安装OpenCV(用于图像处理)
pip install opencv-python opencv-python-headless

# 安装Matplotlib(用于可视化)
pip install matplotlib

# 安装科学计算库
pip install numpy scipy

# 安装图像处理库
pip install pillow imageio

注意:如果安装opencv-python时遇到问题,可以尝试先安装系统版的OpenCV:

sudo apt install -y python3-opencv

3.3 处理缺失的系统依赖库

在UOS系统上,你可能会遇到一些奇怪的错误,比如:

ImportError: libgthread-2.0.so.0: cannot open shared object file: No such file or directory

这是因为一些系统库的路径或版本不同。解决方法:

# 查找缺失的库
ldd /path/to/your/venv/lib/python3.7/site-packages/cv2/*.so | grep "not found"

# 安装缺失的库(根据实际情况调整)
sudo apt install -y libglib2.0-0 libsm6 libxrender1 libxext6 libgthread-2.0-0

# 如果还是找不到,可以尝试创建软链接
sudo ln -s /usr/lib/aarch64-linux-gnu/libgthread-2.0.so.0 /usr/lib/libgthread-2.0.so.0

4. DamoFD-0.5G模型部署与测试

环境终于配好了,现在可以开始玩真的了。

4.1 最简单的单张图片推理

先写一个最简单的测试脚本,看看模型能不能跑起来:

import cv2
from modelscope.pipelines import pipeline
from modelscope.utils.constant import Tasks
from modelscope.utils.cv.image_utils import draw_face_detection_result
from modelscope.preprocessors.image import LoadImage

# 创建人脸检测pipeline
print("正在加载DamoFD-0.5G模型...")
face_detection = pipeline(task=Tasks.face_detection, 
                          model='damo/cv_ddsar_face-detection_iclr23-damofd')
print("模型加载完成!")

# 使用测试图片(这里用一张网络图片做演示)
img_path = 'https://modelscope.oss-cn-beijing.aliyuncs.com/test/images/face_detection2.jpeg'

print(f"正在检测图片: {img_path}")
result = face_detection(img_path)

print(f"检测到 {len(result['boxes'])} 张人脸")
for i, (box, score) in enumerate(zip(result['boxes'], result['scores'])):
    print(f"人脸{i+1}: 置信度={score:.4f}, 位置={box}")

# 可视化结果
img = LoadImage.convert_to_ndarray(img_path)
img_draw = draw_face_detection_result(img, result)

# 保存结果
output_path = 'detection_result.jpg'
cv2.imwrite(output_path, img_draw)
print(f"结果已保存到: {output_path}")

# 显示关键点信息
if 'keypoints' in result:
    print("\n关键点坐标:")
    for i, kps in enumerate(result['keypoints']):
        print(f"人脸{i+1}: 左眼={kps[0]}, 右眼={kps[1]}, 鼻子={kps[2]}, 左嘴角={kps[3]}, 右嘴角={kps[4]}")

运行这个脚本,如果一切正常,你应该能看到类似这样的输出:

正在加载DamoFD-0.5G模型...
模型加载完成!
正在检测图片: https://modelscope.oss-cn-beijing.aliyuncs.com/test/images/face_detection2.jpeg
检测到 3 张人脸
人脸1: 置信度=0.9987, 位置=[232.4, 156.2, 345.6, 289.3]
人脸2: 置信度=0.9965, 位置=[412.3, 178.9, 523.1, 310.5]
人脸3: 置信度=0.9876, 位置=[589.7, 145.8, 701.2, 278.4]
结果已保存到: detection_result.jpg

4.2 使用本地图片进行测试

网络图片测试通过后,试试本地图片:

import cv2
import os
from modelscope.pipelines import pipeline
from modelscope.utils.constant import Tasks

# 初始化pipeline
face_detection = pipeline(task=Tasks.face_detection, 
                          model='damo/cv_ddsar_face-detection_iclr23-damofd')

# 准备测试图片
test_images = [
    'family_photo.jpg',      # 家庭合影
    'selfie.jpg',            # 自拍照
    'group_photo.jpg',       # 集体照
    'low_light.jpg',         # 低光照图片
    'side_face.jpg'          # 侧脸
]

for img_file in test_images:
    if os.path.exists(img_file):
        print(f"\n处理图片: {img_file}")
        
        # 读取图片
        img = cv2.imread(img_file)
        if img is None:
            print(f"  无法读取图片: {img_file}")
            continue
            
        # 调整图片大小(如果太大)
        height, width = img.shape[:2]
        if max(height, width) > 2000:
            scale = 2000 / max(height, width)
            new_width = int(width * scale)
            new_height = int(height * scale)
            img = cv2.resize(img, (new_width, new_height))
            print(f"  图片已缩放到: {new_width}x{new_height}")
        
        # 保存临时文件
        temp_path = f"temp_{img_file}"
        cv2.imwrite(temp_path, img)
        
        # 进行人脸检测
        result = face_detection(temp_path)
        
        # 输出结果
        num_faces = len(result['boxes'])
        print(f"  检测到 {num_faces} 张人脸")
        
        # 在图片上绘制检测框
        for box in result['boxes']:
            x1, y1, x2, y2 = map(int, box)
            cv2.rectangle(img, (x1, y1), (x2, y2), (0, 255, 0), 2)
            
            # 绘制关键点
            if 'keypoints' in result:
                for kps in result['keypoints']:
                    for kp in kps:
                        x, y = map(int, kp)
                        cv2.circle(img, (x, y), 3, (0, 0, 255), -1)
        
        # 保存结果
        output_file = f"result_{img_file}"
        cv2.imwrite(output_file, img)
        print(f"  结果已保存: {output_file}")
        
        # 清理临时文件
        os.remove(temp_path)
    else:
        print(f"图片不存在: {img_file}")

4.3 批量处理图片

在实际项目中,我们经常需要处理整个文件夹的图片:

import os
import json
from tqdm import tqdm
from modelscope.pipelines import pipeline
from modelscope.utils.constant import Tasks

def batch_process_images(input_dir, output_dir, result_file='results.json'):
    """
    批量处理文件夹中的所有图片
    
    Args:
        input_dir: 输入图片文件夹
        output_dir: 输出结果文件夹
        result_file: 结果JSON文件
    """
    # 创建输出目录
    os.makedirs(output_dir, exist_ok=True)
    
    # 初始化pipeline
    print("初始化人脸检测模型...")
    face_detection = pipeline(task=Tasks.face_detection,
                              model='damo/cv_ddsar_face-detection_iclr23-damofd')
    
    # 获取所有图片文件
    image_extensions = ['.jpg', '.jpeg', '.png', '.bmp', '.tiff']
    image_files = []
    for file in os.listdir(input_dir):
        if any(file.lower().endswith(ext) for ext in image_extensions):
            image_files.append(file)
    
    print(f"找到 {len(image_files)} 张图片")
    
    # 存储所有结果
    all_results = {}
    
    # 批量处理
    for filename in tqdm(image_files, desc="处理图片"):
        input_path = os.path.join(input_dir, filename)
        
        try:
            # 检测人脸
            result = face_detection(input_path)
            
            # 保存结果
            all_results[filename] = {
                'num_faces': len(result['boxes']),
                'boxes': result['boxes'].tolist() if hasattr(result['boxes'], 'tolist') else result['boxes'],
                'scores': result['scores'].tolist() if hasattr(result['scores'], 'tolist') else result['scores'],
                'keypoints': result.get('keypoints', [])
            }
            
            # 每处理10张图片保存一次中间结果
            if len(all_results) % 10 == 0:
                with open(os.path.join(output_dir, 'temp_' + result_file), 'w') as f:
                    json.dump(all_results, f, indent=2)
                    
        except Exception as e:
            print(f"处理图片 {filename} 时出错: {str(e)}")
            all_results[filename] = {'error': str(e)}
    
    # 保存最终结果
    with open(os.path.join(output_dir, result_file), 'w') as f:
        json.dump(all_results, f, indent=2)
    
    print(f"\n处理完成!")
    print(f"总图片数: {len(image_files)}")
    print(f"成功处理: {sum(1 for r in all_results.values() if 'error' not in r)}")
    print(f"失败: {sum(1 for r in all_results.values() if 'error' in r)}")
    
    # 统计人脸数量分布
    face_counts = {}
    for result in all_results.values():
        if 'error' not in result:
            count = result['num_faces']
            face_counts[count] = face_counts.get(count, 0) + 1
    
    print("\n人脸数量分布:")
    for count in sorted(face_counts.keys()):
        print(f"  {count}张人脸: {face_counts[count]}张图片")
    
    return all_results

# 使用示例
if __name__ == "__main__":
    # 设置你的图片文件夹路径
    input_directory = "./test_images"
    output_directory = "./detection_results"
    
    # 批量处理
    results = batch_process_images(input_directory, output_directory)

5. 性能优化与问题解决

在UOS系统上部署,性能优化很重要。ARM架构的CPU通常性能不如x86,所以需要一些调优技巧。

5.1 模型推理性能优化

import time
import numpy as np
from modelscope.pipelines import pipeline
from modelscope.utils.constant import Tasks

class OptimizedFaceDetector:
    def __init__(self, model_name='damo/cv_ddsar_face-detection_iclr23-damofd'):
        """
        优化的面部检测器
        
        Args:
            model_name: 模型名称
        """
        print("正在初始化优化版人脸检测器...")
        start_time = time.time()
        
        # 设置环境变量,优化性能
        import os
        os.environ['OMP_NUM_THREADS'] = '4'  # 设置OpenMP线程数
        os.environ['MKL_NUM_THREADS'] = '4'  # 设置MKL线程数
        
        # 初始化pipeline
        self.pipeline = pipeline(
            task=Tasks.face_detection,
            model=model_name
        )
        
        init_time = time.time() - start_time
        print(f"模型初始化完成,耗时: {init_time:.2f}秒")
        
        # 预热模型
        self._warm_up()
    
    def _warm_up(self):
        """预热模型,让第一次推理更快"""
        print("正在预热模型...")
        warm_up_image = np.random.randint(0, 255, (640, 480, 3), dtype=np.uint8)
        
        # 保存临时图片
        import cv2
        cv2.imwrite('warm_up.jpg', warm_up_image)
        
        # 运行几次推理
        for _ in range(3):
            _ = self.pipeline('warm_up.jpg')
        
        # 清理临时文件
        import os
        os.remove('warm_up.jpg')
        print("模型预热完成")
    
    def detect(self, image_path, confidence_threshold=0.5):
        """
        检测人脸,带性能监控
        
        Args:
            image_path: 图片路径
            confidence_threshold: 置信度阈值
            
        Returns:
            检测结果和性能信息
        """
        start_time = time.time()
        
        # 执行检测
        result = self.pipeline(image_path)
        
        inference_time = time.time() - start_time
        
        # 过滤低置信度结果
        filtered_boxes = []
        filtered_scores = []
        filtered_keypoints = []
        
        if result['boxes'] and result['scores']:
            for i, score in enumerate(result['scores']):
                if score >= confidence_threshold:
                    filtered_boxes.append(result['boxes'][i])
                    filtered_scores.append(score)
                    if 'keypoints' in result and result['keypoints']:
                        filtered_keypoints.append(result['keypoints'][i])
        
        # 性能信息
        perf_info = {
            'total_time': inference_time,
            'num_faces_detected': len(result['boxes']),
            'num_faces_filtered': len(filtered_boxes),
            'avg_confidence': np.mean(result['scores']) if result['scores'] else 0
        }
        
        # 返回过滤后的结果
        filtered_result = {
            'boxes': filtered_boxes,
            'scores': filtered_scores,
            'keypoints': filtered_keypoints if filtered_keypoints else [],
            'performance': perf_info
        }
        
        return filtered_result
    
    def batch_detect(self, image_paths, batch_size=4):
        """
        批量检测(伪批量,实际是顺序处理)
        
        Args:
            image_paths: 图片路径列表
            batch_size: 批量大小
            
        Returns:
            所有图片的检测结果
        """
        all_results = []
        total_start = time.time()
        
        for i in range(0, len(image_paths), batch_size):
            batch_paths = image_paths[i:i+batch_size]
            batch_results = []
            
            for path in batch_paths:
                result = self.detect(path)
                batch_results.append(result)
            
            all_results.extend(batch_results)
            
            # 显示进度
            progress = min(i + batch_size, len(image_paths))
            print(f"进度: {progress}/{len(image_paths)}")
        
        total_time = time.time() - total_start
        print(f"批量处理完成,总耗时: {total_time:.2f}秒")
        print(f"平均每张图片: {total_time/len(image_paths):.3f}秒")
        
        return all_results

# 使用示例
if __name__ == "__main__":
    # 创建优化版检测器
    detector = OptimizedFaceDetector()
    
    # 测试单张图片
    result = detector.detect("test_image.jpg")
    print(f"检测到 {len(result['boxes'])} 张人脸")
    print(f"推理时间: {result['performance']['total_time']:.3f}秒")
    
    # 测试批量图片
    image_list = ["img1.jpg", "img2.jpg", "img3.jpg", "img4.jpg"]
    batch_results = detector.batch_detect(image_list, batch_size=2)

5.2 常见问题与解决方案

在部署过程中,我遇到了不少问题,这里总结一下:

问题1:内存不足

RuntimeError: CUDA out of memory

解决方案:在ARM CPU上,我们通常没有CUDA,但可能会有类似的内存问题。可以尝试:

  • 减小图片尺寸
  • 降低批量大小
  • 使用内存映射文件

问题2:依赖库缺失

ImportError: libXXX.so.X: cannot open shared object file

解决方案

# 查找缺失的库
ldconfig -p | grep libXXX

# 安装对应的开发包
sudo apt install -y libXXX-dev

# 或者从源码编译

问题3:模型下载慢

Downloading model from https://modelscope.cn/... (速度很慢)

解决方案

# 设置镜像源
import os
os.environ['MODELSCOPE_CACHE'] = '/path/to/your/cache'
os.environ['MODELSCOPE_ENDPOINT'] = 'https://modelscope.cn'

问题4:推理速度慢 解决方案

  • 使用更小的图片输入
  • 启用多线程
  • 使用模型量化(如果支持)

6. 实际应用:构建一个简单的人脸检测服务

最后,我们来构建一个简单的Web服务,把DamoFD模型封装成API:

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

app = Flask(__name__)

# 全局模型实例
face_detector = None

def init_model():
    """初始化模型"""
    global face_detector
    if face_detector is None:
        print("正在加载人脸检测模型...")
        face_detector = pipeline(
            task=Tasks.face_detection,
            model='damo/cv_ddsar_face-detection_iclr23-damofd'
        )
        print("模型加载完成")

def base64_to_image(base64_string):
    """将base64字符串转换为OpenCV图像"""
    # 移除前缀(如果有)
    if ',' in base64_string:
        base64_string = base64_string.split(',')[1]
    
    # 解码base64
    image_data = base64.b64decode(base64_string)
    
    # 转换为PIL图像
    pil_image = Image.open(BytesIO(image_data))
    
    # 转换为OpenCV格式
    opencv_image = cv2.cvtColor(np.array(pil_image), cv2.COLOR_RGB2BGR)
    
    return opencv_image

def image_to_base64(image):
    """将OpenCV图像转换为base64字符串"""
    # 转换为RGB
    image_rgb = cv2.cvtColor(image, cv2.COLOR_BGR2RGB)
    
    # 转换为PIL图像
    pil_image = Image.fromarray(image_rgb)
    
    # 保存到字节流
    buffered = BytesIO()
    pil_image.save(buffered, format="JPEG")
    
    # 编码为base64
    img_str = base64.b64encode(buffered.getvalue()).decode()
    
    return img_str

@app.route('/health', methods=['GET'])
def health_check():
    """健康检查接口"""
    return jsonify({
        'status': 'healthy',
        'model_loaded': face_detector is not None
    })

@app.route('/detect', methods=['POST'])
def detect_faces():
    """人脸检测接口"""
    try:
        # 获取请求数据
        data = request.json
        
        if not data or 'image' not in data:
            return jsonify({'error': '缺少image参数'}), 400
        
        # 初始化模型
        init_model()
        
        # 转换图片
        image = base64_to_image(data['image'])
        
        # 保存临时文件(ModelScope需要文件路径)
        temp_path = 'temp_detect.jpg'
        cv2.imwrite(temp_path, image)
        
        # 执行人脸检测
        result = face_detector(temp_path)
        
        # 清理临时文件
        import os
        os.remove(temp_path)
        
        # 处理结果
        faces = []
        for i, (box, score) in enumerate(zip(result['boxes'], result['scores'])):
            face_info = {
                'id': i + 1,
                'confidence': float(score),
                'bbox': {
                    'x1': float(box[0]),
                    'y1': float(box[1]),
                    'x2': float(box[2]),
                    'y2': float(box[3])
                }
            }
            
            # 添加关键点(如果有)
            if 'keypoints' in result and i < len(result['keypoints']):
                kps = result['keypoints'][i]
                face_info['keypoints'] = {
                    'left_eye': [float(kps[0][0]), float(kps[0][1])],
                    'right_eye': [float(kps[1][0]), float(kps[1][1])],
                    'nose': [float(kps[2][0]), float(kps[2][1])],
                    'left_mouth': [float(kps[3][0]), float(kps[3][1])],
                    'right_mouth': [float(kps[4][0]), float(kps[4][1])]
                }
            
            faces.append(face_info)
        
        # 是否返回带标注的图片
        annotated_image = None
        if data.get('return_image', False):
            # 在图片上绘制检测框
            for box in result['boxes']:
                x1, y1, x2, y2 = map(int, box)
                cv2.rectangle(image, (x1, y1), (x2, y2), (0, 255, 0), 2)
            
            # 绘制关键点
            if 'keypoints' in result:
                for kps in result['keypoints']:
                    for kp in kps:
                        x, y = map(int, kp)
                        cv2.circle(image, (x, y), 3, (0, 0, 255), -1)
            
            annotated_image = image_to_base64(image)
        
        # 返回结果
        response = {
            'success': True,
            'num_faces': len(faces),
            'faces': faces
        }
        
        if annotated_image:
            response['annotated_image'] = annotated_image
        
        return jsonify(response)
        
    except Exception as e:
        return jsonify({
            'success': False,
            'error': str(e)
        }), 500

@app.route('/batch_detect', methods=['POST'])
def batch_detect():
    """批量人脸检测接口"""
    try:
        data = request.json
        
        if not data or 'images' not in data:
            return jsonify({'error': '缺少images参数'}), 400
        
        # 初始化模型
        init_model()
        
        results = []
        for img_data in data['images']:
            try:
                # 处理单张图片
                image = base64_to_image(img_data['image'])
                temp_path = f"temp_batch_{len(results)}.jpg"
                cv2.imwrite(temp_path, image)
                
                result = face_detector(temp_path)
                os.remove(temp_path)
                
                # 统计人脸数量
                num_faces = len(result['boxes'])
                
                results.append({
                    'image_id': img_data.get('id', len(results)),
                    'num_faces': num_faces,
                    'success': True
                })
                
            except Exception as e:
                results.append({
                    'image_id': img_data.get('id', len(results)),
                    'success': False,
                    'error': str(e)
                })
        
        return jsonify({
            'success': True,
            'total_images': len(results),
            'successful': sum(1 for r in results if r['success']),
            'failed': sum(1 for r in results if not r['success']),
            'results': results
        })
        
    except Exception as e:
        return jsonify({
            'success': False,
            'error': str(e)
        }), 500

if __name__ == '__main__':
    # 初始化模型
    init_model()
    
    # 启动服务
    print("人脸检测服务启动中...")
    print("访问 http://localhost:5000/health 检查服务状态")
    print("访问 http://localhost:5000/detect 进行人脸检测")
    
    app.run(host='0.0.0.0', port=5000, debug=False)

这个Web服务提供了三个接口:

  1. /health - 健康检查
  2. /detect - 单张图片人脸检测
  3. /batch_detect - 批量图片人脸检测

你可以用curl或者Python的requests库来调用:

import requests
import base64

# 读取图片并转换为base64
with open('test.jpg', 'rb') as f:
    image_base64 = base64.b64encode(f.read()).decode()

# 调用检测接口
response = requests.post('http://localhost:5000/detect', json={
    'image': image_base64,
    'return_image': True
})

print(response.json())

7. 总结与建议

折腾了两天,总算把DamoFD-0.5G在统信UOS上跑起来了。整体来说,这个过程比在Ubuntu或CentOS上要复杂一些,主要是ARM架构的适配和系统依赖库的问题。

从实际使用效果来看,DamoFD-0.5G确实是个不错的模型。在飞腾FT-2000/4处理器上,处理一张640x480的图片大概需要0.3-0.5秒,精度也足够满足大多数应用场景。对于智慧社区、门禁系统这类应用,完全够用了。

如果你也要在国产操作系统上部署AI模型,我的建议是:

  1. 提前规划:先搞清楚你的硬件架构(x86还是ARM),这决定了后面所有的安装步骤。
  2. 环境隔离:一定要用虚拟环境,避免污染系统Python环境。
  3. 耐心编译:ARM架构上很多包需要从源码编译,做好心理准备。
  4. 逐步调试:遇到问题不要慌,从最简单的测试开始,一步步排查。
  5. 性能监控:ARM CPU性能有限,要密切关注内存和CPU使用情况。

这次部署经历让我深刻体会到,在信创环境下搞AI开发,确实有不少额外的挑战。但一旦走通了,后面的路就好走多了。希望这篇记录能帮到正在类似环境下奋斗的你。


获取更多AI镜像

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

Logo

腾讯云面向开发者汇聚海量精品云计算使用和开发经验,营造开放的云计算技术生态圈。

更多推荐