DAMO-YOLO实战教程从requirements安装到API调用完整步骤想快速搭建一个高性能的手机检测服务吗今天带你从零开始手把手部署阿里巴巴开源的DAMO-YOLO手机检测模型。这个模型在手机检测任务上达到了88.8%的准确率推理速度仅需3.83毫秒无论是做手机质检、智能安防还是移动设备管理都能轻松应对。我花了几天时间把这个模型从安装到部署完整跑了一遍过程中踩了不少坑也总结了很多实用技巧。这篇教程就是我的实战笔记我会用最直白的方式告诉你每一步该怎么做让你少走弯路快速上手。1. 学习目标与环境准备1.1 你能学到什么学完这篇教程你将掌握如何从零开始搭建DAMO-YOLO手机检测环境两种使用方式Web界面和Python API如何优化部署让检测速度更快常见问题的解决方法1.2 前置知识要求你只需要基本的Linux命令行操作经验会写简单的Python代码有一台能联网的服务器或本地电脑不需要你是深度学习专家也不需要懂复杂的模型原理。我会用大白话解释每一步确保小白也能看懂。1.3 环境检查与准备开始之前先确认你的环境# 检查Python版本 python3 --version # 应该显示Python 3.8或更高版本 # 检查pip是否安装 pip3 --version # 检查磁盘空间模型需要约200MB空间 df -h如果你的系统是Ubuntu 20.04或CentOS 7以上基本上都能顺利运行。Windows用户建议使用WSL2或Docker环境。2. 快速安装与部署2.1 一键安装依赖这是最关键的一步很多问题都出在依赖安装上。我整理了一个完整的安装脚本#!/bin/bash # 保存为install.sh然后运行bash install.sh echo 开始安装DAMO-YOLO手机检测环境... # 创建项目目录 mkdir -p /root/cv_tinynas_object-detection_damoyolo_phone cd /root/cv_tinynas_object-detection_damoyolo_phone # 创建requirements.txt文件 cat requirements.txt EOF modelscope1.34.0 torch2.0.0 torchvision0.15.0 gradio4.0.0 opencv-python4.8.0 easydict1.10 numpy1.24.0 pillow9.5.0 EOF # 安装Python依赖 echo 正在安装Python依赖... pip3 install -r requirements.txt # 如果pip安装慢可以换成国内源 # pip3 install -r requirements.txt -i https://pypi.tuna.tsinghua.edu.cn/simple echo 依赖安装完成运行这个脚本它会自动创建项目目录并安装所有必需的包。整个过程大概需要5-10分钟取决于你的网速。2.2 下载模型文件模型文件比较大125MB有两种下载方式方式一自动下载推荐当你第一次运行代码时模型会自动下载到缓存目录。但有时候网络不好会下载失败所以我也准备了手动下载的方式。方式二手动下载# 创建模型缓存目录 mkdir -p /root/ai-models/iic/cv_tinynas_object-detection_damoyolo_phone # 下载模型文件需要先获取下载链接 # 通常可以从ModelScope官网找到 # 这里假设你已经有了下载链接 wget -O /root/ai-models/iic/cv_tinynas_object-detection_damoyolo_phone/model.pth 模型下载链接如果自动下载失败可以到ModelScope官网搜索damo/cv_tinynas_object-detection_damoyolo_phone找到模型文件手动下载。2.3 启动Web服务安装完成后启动服务非常简单# 进入项目目录 cd /root/cv_tinynas_object-detection_damoyolo_phone # 创建启动脚本 cat start.sh EOF #!/bin/bash cd $(dirname $0) python3 app.py EOF # 给脚本执行权限 chmod x start.sh # 启动服务 ./start.sh启动成功后你会看到类似这样的输出Running on local URL: http://0.0.0.0:7860现在打开浏览器访问http://你的服务器IP:7860就能看到Web界面了。3. Web界面使用指南3.1 界面功能详解Web界面基于Gradio搭建非常简洁易用。主要功能区域图片上传区可以拖拽上传图片或者点击选择文件示例图片区内置了几张测试图片点击就能直接用检测按钮点击开始检测开始处理结果显示区显示检测后的图片和结果信息我第一次用的时候发现界面虽然简单但功能很实用。上传一张包含手机的图片点击检测几秒钟就能看到结果。3.2 实际操作演示让我带你走一遍完整流程步骤1准备测试图片找一张包含手机的图片最好是手机在图片中比较明显光线不要太暗背景不要太复杂如果手头没有合适的图片可以直接使用界面提供的示例图片。步骤2上传图片点击上传区域选择你的图片。支持JPG、PNG格式大小建议不要超过10MB。步骤3开始检测点击开始检测按钮你会看到进度条开始走动。正常情况下3-5秒就能完成检测。步骤4查看结果检测完成后右侧会显示标注了手机位置的图片用方框框出来检测到的手机数量每个手机的置信度就是模型认为这是手机的可信度我测试了几张图片发现效果确实不错。即使是手机只露出一部分或者角度比较刁钻模型也能准确识别出来。3.3 使用技巧经过多次测试我总结了一些提升检测效果的小技巧图片质量尽量使用清晰的图片模糊的图片会影响检测精度手机大小手机在图片中的占比最好在10%-50%之间角度问题正面、侧面都能识别但完全背面的识别率会低一些多手机检测一张图片里有多部手机时都能检测出来4. Python API调用方法除了Web界面更常用的方式是通过Python API调用。这样你可以把检测功能集成到自己的项目中。4.1 基础调用代码先来看最简单的调用方式# 保存为detect_phone.py from modelscope.pipelines import pipeline from modelscope.utils.constant import Tasks import cv2 def detect_phone_simple(image_path): 最简单的手机检测函数 # 加载模型 detector pipeline( Tasks.domain_specific_object_detection, modeldamo/cv_tinynas_object-detection_damoyolo_phone, cache_dir/root/ai-models, trust_remote_codeTrue ) # 执行检测 result detector(image_path) # 打印结果 print(检测结果:) print(f检测到 {len(result[boxes])} 部手机) for i, box in enumerate(result[boxes]): print(f手机{i1}:) print(f 位置: {box}) print(f 置信度: {result[scores][i]:.3f}) return result # 使用示例 if __name__ __main__: result detect_phone_simple(test.jpg)运行这个脚本你就能看到检测结果。代码虽然简单但包含了最核心的功能。4.2 高级功能扩展实际项目中我们可能需要更多功能。下面是我在实际使用中封装的一些实用函数import os from PIL import Image import numpy as np class PhoneDetector: def __init__(self, model_pathNone): 初始化检测器 self.detector pipeline( Tasks.domain_specific_object_detection, modeldamo/cv_tinynas_object-detection_damoyolo_phone, cache_dir/root/ai-models, trust_remote_codeTrue ) def detect_from_file(self, image_path, confidence_threshold0.5): 从文件检测手机 if not os.path.exists(image_path): raise FileNotFoundError(f图片不存在: {image_path}) result self.detector(image_path) # 过滤低置信度的结果 filtered_boxes [] filtered_scores [] for box, score in zip(result[boxes], result[scores]): if score confidence_threshold: filtered_boxes.append(box) filtered_scores.append(score) return { boxes: filtered_boxes, scores: filtered_scores, count: len(filtered_boxes) } def detect_from_bytes(self, image_bytes): 从字节流检测手机 适用于网络传输或内存中的图片 # 将字节流转换为numpy数组 nparr np.frombuffer(image_bytes, np.uint8) image cv2.imdecode(nparr, cv2.IMREAD_COLOR) # 临时保存图片 temp_path /tmp/temp_detect.jpg cv2.imwrite(temp_path, image) # 检测 result self.detect_from_file(temp_path) # 清理临时文件 os.remove(temp_path) return result def batch_detect(self, image_folder, output_folderNone): 批量检测文件夹中的所有图片 if not os.path.exists(image_folder): raise FileNotFoundError(f文件夹不存在: {image_folder}) results {} image_files [f for f in os.listdir(image_folder) if f.lower().endswith((.jpg, .jpeg, .png))] print(f找到 {len(image_files)} 张图片) for i, filename in enumerate(image_files): print(f处理第 {i1}/{len(image_files)} 张: {filename}) image_path os.path.join(image_folder, filename) result self.detect_from_file(image_path) results[filename] result # 如果需要保存带标注的图片 if output_folder: self.save_result_image(image_path, result, output_folder, filename) return results def save_result_image(self, image_path, result, output_folder, output_name): 保存带检测框的图片 os.makedirs(output_folder, exist_okTrue) image cv2.imread(image_path) # 绘制检测框 for box in result[boxes]: x1, y1, x2, y2 map(int, box) cv2.rectangle(image, (x1, y1), (x2, y2), (0, 255, 0), 2) cv2.putText(image, Phone, (x1, y1-10), cv2.FONT_HERSHEY_SIMPLEX, 0.5, (0, 255, 0), 2) output_path os.path.join(output_folder, output_name) cv2.imwrite(output_path, image) return output_path # 使用示例 if __name__ __main__: # 初始化检测器 detector PhoneDetector() # 单张图片检测 result detector.detect_from_file(test.jpg) print(f检测到 {result[count]} 部手机) # 批量检测 # results detector.batch_detect(input_images, output_images)这个类封装了常用的功能你可以直接复制使用。我特别推荐batch_detect方法当你需要处理大量图片时它会非常有用。4.3 性能优化技巧在实际使用中我发现有几个地方可以优化性能技巧1模型复用不要每次检测都重新加载模型这样会很慢。正确的做法是# 全局初始化一次 detector PhoneDetector() # 然后重复使用 def process_request(image_data): # 直接使用已经初始化的detector result detector.detect_from_bytes(image_data) return result技巧2调整置信度阈值根据你的需求调整阈值# 严格模式只检测高置信度的手机 strict_result detector.detect_from_file(image.jpg, confidence_threshold0.7) # 宽松模式检测所有可能的手机 loose_result detector.detect_from_file(image.jpg, confidence_threshold0.3)技巧3图片预处理如果图片太大可以先缩放def preprocess_image(image_path, max_size1024): 预处理图片调整大小 image cv2.imread(image_path) height, width image.shape[:2] if max(height, width) max_size: scale max_size / max(height, width) new_width int(width * scale) new_height int(height * scale) image cv2.resize(image, (new_width, new_height)) return image5. 常见问题与解决方案在部署和使用过程中我遇到了一些问题这里分享解决方法5.1 安装问题问题1pip安装超时或失败# 解决方法使用国内镜像源 pip3 install -r requirements.txt -i https://pypi.tuna.tsinghua.edu.cn/simple # 或者使用阿里云镜像 pip3 install -r requirements.txt -i https://mirrors.aliyun.com/pypi/simple/问题2模型下载失败# 解决方法1手动下载 # 访问ModelScope官网搜索模型名称手动下载模型文件 # 然后放到 /root/ai-models/iic/cv_tinynas_object-detection_damoyolo_phone/ # 解决方法2设置代理如果有的话 export http_proxyhttp://你的代理地址:端口 export https_proxyhttp://你的代理地址:端口5.2 运行问题问题3端口7860被占用# 查看哪个进程占用了7860端口 sudo lsof -i :7860 # 如果不想用7860可以修改app.py中的端口号 # 找到这行代码demo.launch(server_name0.0.0.0, server_port7860) # 把7860改成其他端口比如8080问题4内存不足如果图片太大可能会内存不足。解决方法# 在检测前调整图片大小 def resize_image(image_path, max_dimension1024): from PIL import Image img Image.open(image_path) # 计算缩放比例 width, height img.size if max(width, height) max_dimension: ratio max_dimension / max(width, height) new_width int(width * ratio) new_height int(height * ratio) img img.resize((new_width, new_height), Image.Resampling.LANCZOS) img.save(resized.jpg) return resized.jpg5.3 性能问题问题5检测速度慢可能的原因和解决方法图片太大先缩放图片建议长边不超过1024像素GPU未启用检查是否使用了GPU加速模型首次加载慢第一次加载需要时间后续调用会快很多检查GPU是否可用import torch print(fCUDA可用: {torch.cuda.is_available()}) print(fGPU数量: {torch.cuda.device_count()}) if torch.cuda.is_available(): print(f当前GPU: {torch.cuda.get_device_name(0)})6. 实际应用案例6.1 手机质检系统我在一个手机工厂的质检项目中用过这个模型。他们的需求是检测手机外观是否有缺陷但第一步需要先定位手机位置。class PhoneQualityChecker: def __init__(self): self.detector PhoneDetector() def check_phone_quality(self, image_path): 手机质量检查流程 # 1. 检测手机位置 detection_result self.detector.detect_from_file(image_path) if detection_result[count] 0: return {status: error, message: 未检测到手机} # 2. 裁剪出手机区域 phone_region self.crop_phone_region(image_path, detection_result[boxes][0]) # 3. 进行质量检查这里可以接入其他检测模型 quality_result self.check_defects(phone_region) return { status: success, phone_count: detection_result[count], quality: quality_result, confidence: detection_result[scores][0] } def crop_phone_region(self, image_path, box): 根据检测框裁剪手机区域 image cv2.imread(image_path) x1, y1, x2, y2 map(int, box) phone_image image[y1:y2, x1:x2] return phone_image def check_defects(self, phone_image): 检查手机缺陷示例函数实际需要接入缺陷检测模型 # 这里可以接入划痕检测、颜色检测等模型 # 返回检测结果 return { scratches: none, # 划痕 color: normal, # 颜色 alignment: good # 对齐 }6.2 智能安防监控另一个应用场景是安防监控检测监控画面中是否出现手机import time from datetime import datetime class SecurityMonitor: def __init__(self, camera_url): self.detector PhoneDetector() self.camera_url camera_url self.alert_threshold 0.7 # 置信度阈值 self.last_alert_time None def monitor_stream(self): 监控视频流 import cv2 cap cv2.VideoCapture(self.camera_url) while True: ret, frame cap.read() if not ret: print(无法获取视频流) time.sleep(1) continue # 保存当前帧为临时文件 temp_path /tmp/frame.jpg cv2.imwrite(temp_path, frame) # 检测手机 result self.detector.detect_from_file(temp_path, self.alert_threshold) # 如果有手机且置信度高触发警报 if result[count] 0 and result[scores][0] 0.8: self.send_alert(frame, result) # 控制处理频率避免CPU占用过高 time.sleep(0.5) def send_alert(self, frame, result): 发送警报 current_time datetime.now() # 避免频繁报警 if self.last_alert_time and (current_time - self.last_alert_time).seconds 60: return print(f[警报] 检测到手机时间: {current_time}) print(f置信度: {result[scores][0]:.3f}) print(f位置: {result[boxes][0]}) # 保存警报截图 alert_filename falert_{current_time.strftime(%Y%m%d_%H%M%S)}.jpg cv2.imwrite(falerts/{alert_filename}, frame) self.last_alert_time current_time6.3 批量处理工具如果你需要处理大量图片这个批量处理工具会很实用import pandas as pd from tqdm import tqdm class BatchProcessor: def __init__(self): self.detector PhoneDetector() def process_folder(self, input_folder, output_csvresults.csv): 处理整个文件夹生成统计报告 all_results [] # 获取所有图片文件 image_files [] for ext in [.jpg, .jpeg, .png, .bmp]: image_files.extend(list(input_folder.glob(f*{ext}))) image_files.extend(list(input_folder.glob(f*{ext.upper()}))) print(f找到 {len(image_files)} 张图片) # 批量处理 for image_path in tqdm(image_files, desc处理进度): try: result self.detector.detect_from_file(str(image_path)) all_results.append({ filename: image_path.name, phone_count: result[count], confidence_avg: sum(result[scores]) / len(result[scores]) if result[scores] else 0, detection_time: datetime.now().strftime(%Y-%m-%d %H:%M:%S) }) except Exception as e: print(f处理失败: {image_path.name}, 错误: {str(e)}) all_results.append({ filename: image_path.name, phone_count: 0, confidence_avg: 0, detection_time: 处理失败, error: str(e) }) # 保存结果到CSV df pd.DataFrame(all_results) df.to_csv(output_csv, indexFalse, encodingutf-8-sig) # 生成统计信息 total_phones df[phone_count].sum() success_rate len(df[df[phone_count] 0]) / len(df) * 100 print(\n *50) print(处理完成) print(f总图片数: {len(df)}) print(f检测到手机总数: {total_phones}) print(f检测成功率: {success_rate:.1f}%) print(f结果已保存到: {output_csv}) print(*50) return df7. 总结通过这篇教程你应该已经掌握了DAMO-YOLO手机检测模型的完整部署和使用方法。让我们回顾一下重点7.1 核心要点总结安装很简单主要就是安装几个Python包按照教程一步步来基本不会出错两种使用方式Web界面适合快速测试Python API适合集成到项目性能很给力88.8%的准确率3.83毫秒的推理速度完全满足实时检测需求应用场景广从手机质检到安防监控再到批量处理都能用得上7.2 下一步学习建议如果你已经掌握了基础用法可以尝试性能优化尝试使用GPU加速或者调整图片预处理参数功能扩展结合其他模型比如手机型号识别、缺陷检测等部署优化将服务封装成Docker容器方便部署到不同环境实际项目找一个真实的应用场景用这个模型解决实际问题7.3 最后的小建议我在实际使用中发现这个模型对常见的智能手机检测效果很好但对一些老式手机或者特殊形状的手机检测效果会稍微差一点。如果你的应用场景中有这类手机可能需要收集一些样本进行微调。另外模型的检测速度受图片大小影响很大。在处理大量图片时先统一缩放到合适的大小可以显著提升处理速度。获取更多AI镜像想探索更多AI镜像和应用场景访问 CSDN星图镜像广场提供丰富的预置镜像覆盖大模型推理、图像生成、视频生成、模型微调等多个领域支持一键部署。