DAMO-YOLO手机检测结果导出CSV/Excel格式检测数据批量生成教程1. 项目背景与需求场景在日常的手机检测工作中我们经常遇到这样的需求不仅要看到图片上的检测框还需要将检测结果整理成结构化的数据表格。比如安防监控需要统计每个时间段检测到的手机数量生成日报表考场管理要导出作弊嫌疑记录作为处理依据数据分析需要批量处理大量图片分析手机使用规律传统的做法是一张张截图、手动记录既费时又容易出错。而DAMO-YOLO手机检测系统自带的Web界面虽然能显示检测结果却没有提供批量导出功能。这就是本文要解决的问题教你如何批量导出DAMO-YOLO的检测结果生成规范的CSV和Excel格式数据报告。2. 环境准备与快速部署2.1 系统要求确认在开始之前请确保你的系统满足以下要求已部署DAMO-YOLO手机检测系统访问地址通常是http://服务器IP:7860Python 3.7 环境基本的命令行操作知识2.2 安装必要的依赖包打开终端执行以下命令安装所需库# 安装数据处理相关库 pip install pandas openpyxl requests pillow # 验证安装 python -c import pandas; print(pandas版本:, pandas.__version__) python -c import openpyxl; print(openpyxl安装成功)这些库的作用分别是pandas数据处理核心库用于生成表格数据openpyxlExcel文件读写支持requests网络请求用于调用检测APIpillow图片处理用于准备检测图片3. 核心代码实现3.1 单张图片检测结果获取首先我们需要编写一个函数来获取单张图片的检测结果import requests import json import base64 from PIL import Image import io def detect_single_image(image_path, server_urlhttp://localhost:7860): 单张图片检测函数 :param image_path: 图片路径 :param server_url: 检测服务器地址 :return: 检测结果列表 # 读取并编码图片 with open(image_path, rb) as image_file: image_data base64.b64encode(image_file.read()).decode(utf-8) # 准备请求数据 payload { data: [ fdata:image/jpeg;base64,{image_data} ] } # 发送检测请求 try: response requests.post( f{server_url}/run/predict, jsonpayload, timeout30 ) response.raise_for_status() # 解析检测结果 result response.json() detections result[data][0] if result[data] else [] return detections except Exception as e: print(f检测失败: {e}) return []3.2 检测结果解析与格式化获取到原始检测数据后我们需要将其解析为结构化的信息def parse_detection_results(detections, image_name): 解析检测结果并格式化 :param detections: 原始检测数据 :param image_name: 图片名称 :return: 格式化后的检测结果列表 results [] if not detections: return results # 解析每个检测框 for i, detection in enumerate(detections): # 检测结果格式: [x_min, y_min, x_max, y_max, confidence, class_id] if len(detection) 6: result_item { 图片名称: image_name, 检测ID: i 1, 置信度: round(float(detection[4]) * 100, 2), # 转换为百分比 边界框Xmin: int(detection[0]), 边界框Ymin: int(detection[1]), 边界框Xmax: int(detection[2]), 边界框Ymax: int(detection[3]), 检测时间: datetime.now().strftime(%Y-%m-%d %H:%M:%S) } results.append(result_item) return results3.3 批量处理与数据导出现在编写批量处理函数支持处理整个文件夹的图片import os import pandas as pd from datetime import datetime def batch_process_images(image_folder, output_file, server_urlhttp://localhost:7860): 批量处理图片并导出结果 :param image_folder: 图片文件夹路径 :param output_file: 输出文件路径 :param server_url: 检测服务器地址 all_results [] supported_formats [.jpg, .jpeg, .png, .bmp] # 收集所有图片文件 image_files [] for file_name in os.listdir(image_folder): if any(file_name.lower().endswith(fmt) for fmt in supported_formats): image_files.append(file_name) print(f找到 {len(image_files)} 张待处理图片) # 逐张处理图片 for i, file_name in enumerate(image_files, 1): image_path os.path.join(image_folder, file_name) print(f正在处理第 {i}/{len(image_files)} 张: {file_name}) # 获取检测结果 detections detect_single_image(image_path, server_url) # 解析结果 parsed_results parse_detection_results(detections, file_name) all_results.extend(parsed_results) # 显示进度 if parsed_results: print(f → 检测到 {len(parsed_results)} 个手机) else: print( → 未检测到手机) # 导出结果 if all_results: export_to_file(all_results, output_file) print(f\n处理完成共检测到 {len(all_results)} 个手机) print(f结果已导出到: {output_file}) else: print(\n未检测到任何手机)3.4 多种格式导出功能实现支持CSV和Excel两种格式的导出功能def export_to_file(results, output_file): 将结果导出为文件 :param results: 检测结果列表 :param output_file: 输出文件路径 # 转换为DataFrame df pd.DataFrame(results) # 根据文件扩展名选择导出格式 if output_file.lower().endswith(.csv): # CSV格式导出 df.to_csv(output_file, indexFalse, encodingutf-8-sig) print(已生成CSV格式报告) elif output_file.lower().endswith((.xlsx, .xls)): # Excel格式导出 with pd.ExcelWriter(output_file, engineopenpyxl) as writer: df.to_excel(writer, sheet_name手机检测结果, indexFalse) # 获取工作表对象进行格式调整 worksheet writer.sheets[手机检测结果] # 调整列宽 for column in worksheet.columns: max_length 0 column_letter column[0].column_letter for cell in column: try: if len(str(cell.value)) max_length: max_length len(str(cell.value)) except: pass adjusted_width min(max_length 2, 50) worksheet.column_dimensions[column_letter].width adjusted_width print(已生成Excel格式报告) else: raise ValueError(不支持的文件格式请使用 .csv 或 .xlsx)4. 完整使用示例4.1 创建配置文件建议创建一个配置文件来管理常用参数# config.py CONFIG { server_url: http://localhost:7860, # 检测服务器地址 image_folder: ./images, # 图片文件夹路径 output_csv: ./results/detection_results.csv, # CSV输出路径 output_excel: ./results/detection_report.xlsx, # Excel输出路径 supported_formats: [.jpg, .jpeg, .png, .bmp] }4.2 主程序示例创建一个简单的主程序来调用批量处理功能# main.py from detection_export import batch_process_images import os def main(): # 创建输出目录 os.makedirs(./results, exist_okTrue) print( DAMO-YOLO手机检测结果批量导出工具 ) print(开始处理图片...) # 批量处理并导出CSV batch_process_images( image_folder./images, output_file./results/手机检测报告.csv, server_urlhttp://localhost:7860 ) # 也可以导出Excel格式 batch_process_images( image_folder./images, output_file./results/手机检测报告.xlsx, server_urlhttp://localhost:7860 ) print(批量处理完成) if __name__ __main__: main()4.3 命令行使用示例如果你更喜欢命令行操作可以这样使用# 直接运行Python脚本 python detection_export.py --input ./images --output ./results/report.csv # 或者使用更详细的参数 python detection_export.py \ --input ./监控图片 \ --output ./日报/手机检测记录_20231201.xlsx \ --server http://192.168.1.100:78605. 高级功能扩展5.1 添加统计汇总功能在导出数据的基础上我们可以添加统计功能def add_statistical_summary(results, output_file): 添加统计汇总信息 df pd.DataFrame(results) # 基础统计 total_detections len(df) unique_images df[图片名称].nunique() avg_confidence df[置信度].mean() # 按图片分组统计 image_stats df.groupby(图片名称).agg({ 检测ID: count, 置信度: mean }).rename(columns{检测ID: 检测数量, 置信度: 平均置信度}) # 导出带有多工作表的工作簿 with pd.ExcelWriter(output_file, engineopenpyxl) as writer: # 详细数据 df.to_excel(writer, sheet_name详细数据, indexFalse) # 统计摘要 summary_data { 统计项: [总检测数, 图片数量, 平均置信度], 数值: [total_detections, unique_images, round(avg_confidence, 2)] } pd.DataFrame(summary_data).to_excel(writer, sheet_name统计摘要, indexFalse) # 按图片统计 image_stats.to_excel(writer, sheet_name按图片统计) print(已生成带统计汇总的详细报告)5.2 定时自动导出脚本对于需要定期导出的场景可以创建定时任务# auto_export.py import schedule import time from detection_export import batch_process_images def daily_export(): 每日自动导出任务 date_str time.strftime(%Y%m%d) output_file f./daily_reports/手机检测_{date_str}.xlsx print(f开始执行每日导出任务: {time.strftime(%Y-%m-%d %H:%M:%S)}) batch_process_images(./daily_images, output_file) print(f每日导出任务完成: {output_file}) # 设置每天凌晨1点执行 schedule.every().day.at(01:00).do(daily_export) print(定时导出服务已启动...) while True: schedule.run_pending() time.sleep(60)6. 实际应用案例6.1 考场监控数据导出某学校使用DAMO-YOLO系统监控考场每天考试结束后需要导出检测报告# exam_monitoring.py def export_exam_report(exam_date, exam_room): 导出考场监控报告 image_folder f/监控照片/{exam_date}/{exam_room} output_file f/考试报告/{exam_date}_{exam_room}_手机检测.xlsx # 处理图片并导出 batch_process_images(image_folder, output_file) # 添加额外信息 add_exam_metadata(output_file, exam_date, exam_room) print(f{exam_date} {exam_room}考场报告已生成) def add_exam_metadata(excel_file, exam_date, exam_room): 添加考场元数据信息 # 这里可以添加具体的考场信息到Excel文件中 pass6.2 企业安全审计报告企业安全部门需要按月生成手机使用情况审计报告# security_audit.py def generate_monthly_audit(month): 生成月度安全审计报告 # 收集该月所有图片 monthly_images gather_monthly_images(month) # 批量处理 output_file f/安全审计/手机使用报告_{month}.xlsx batch_process_images(monthly_images, output_file) # 生成可视化图表 add_audit_charts(output_file) print(f{month}月度安全审计报告已生成)7. 总结与建议通过本教程你已经学会了如何将DAMO-YOLO手机检测系统的结果批量导出为结构化的CSV和Excel格式数据。这种方法可以大大提高工作效率特别适用于批量处理场景需要处理大量图片时自动化导出节省大量时间数据归档需求生成规范的电子档案便于长期保存和查询统计分析用途导出结构化数据后可以进一步进行数据分析和可视化系统集成应用导出的数据可以与其他管理系统集成实用建议对于日常使用建议使用CSV格式兼容性好且文件较小需要正式报告时使用Excel格式可以包含多工作表和格式设置定期清理旧的图片文件避免存储空间不足重要数据建议同时备份CSV和Excel两种格式下一步学习方向学习使用pandas进行更复杂的数据分析探索将导出功能集成到Web界面中研究自动邮件发送报告的功能现在你已经掌握了DAMO-YOLO检测结果导出的全套技能快去尝试处理你自己的图片数据吧获取更多AI镜像想探索更多AI镜像和应用场景访问 CSDN星图镜像广场提供丰富的预置镜像覆盖大模型推理、图像生成、视频生成、模型微调等多个领域支持一键部署。