实时手机检测-通用教程:Gradio界面汉化+结果导出Excel功能扩展

张开发
2026/4/16 6:06:23 15 分钟阅读

分享文章

实时手机检测-通用教程:Gradio界面汉化+结果导出Excel功能扩展
实时手机检测-通用教程Gradio界面汉化结果导出Excel功能扩展1. 引言如果你正在寻找一个能快速、准确识别图片中手机的AI工具那么阿里巴巴开源的DAMO-YOLO手机检测模型绝对值得一试。这个模型在手机检测这个特定任务上表现非常出色准确率高达88.8%而且推理速度极快一张图片只需要3.83毫秒就能完成检测。不过当你按照官方文档部署好服务后可能会发现两个小问题一是Web界面是英文的对中文用户不太友好二是检测结果只能在线查看无法方便地保存下来进行后续分析。今天这篇文章我就来手把手教你如何解决这两个问题为这个强大的手机检测服务增加界面汉化和结果导出Excel的功能。通过本教程你将学会如何快速部署DAMO-YOLO手机检测服务如何将Gradio界面完全汉化为中文如何添加一键导出检测结果到Excel的功能如何将这些功能整合成一个完整的、用户友好的应用无论你是开发者、测试人员还是需要批量处理图片中手机检测任务的项目负责人这个增强版的服务都能让你的工作更加高效便捷。2. 环境准备与快速部署2.1 系统要求与依赖安装在开始之前我们先确保环境准备就绪。这个服务对系统要求不高主流的Linux发行版都能运行。首先如果你还没有安装必要的Python包可以运行以下命令# 进入项目目录 cd /root/cv_tinynas_object-detection_damoyolo_phone # 安装基础依赖 pip install -r requirements.txt # 安装我们新增功能需要的额外包 pip install pandas openpyxl这里解释一下几个关键包的作用pandas用于处理数据和生成Excel文件openpyxl让pandas能够读写Excel文件其他包如gradio、modelscope等在原有的requirements.txt中已经包含2.2 一键启动服务环境准备好后启动服务非常简单# 方法一使用启动脚本 ./start.sh # 方法二直接运行Python文件 python3 app.py启动成功后你会看到类似这样的输出Running on local URL: http://0.0.0.0:7860这时候打开浏览器访问http://你的服务器IP:7860就能看到原始的英文界面了。不过别急我们马上就来改造它。3. 基础功能快速上手在开始改造之前我们先快速了解一下这个服务的基本使用方法这样你就能明白我们要在哪些地方做改进。3.1 原始界面功能体验打开Web界面后你会看到以下几个主要区域图片上传区域可以拖拽上传图片或者点击选择文件示例图片区域系统提供了一些测试图片点击就能使用检测按钮大大的Detect按钮点击开始检测结果显示区域检测完成后这里会显示带框的图片使用流程很简单上传一张包含手机的图片点击Detect按钮等待几秒钟就能看到检测结果检测结果会用红色的方框标出图片中的所有手机每个框旁边还会显示一个置信度分数告诉你模型对这个检测结果有多大的把握。3.2 Python API调用除了Web界面你也可以通过Python代码来调用这个检测服务from modelscope.pipelines import pipeline from modelscope.utils.constant import Tasks # 初始化检测器 detector pipeline( Tasks.domain_specific_object_detection, modeldamo/cv_tinynas_object-detection_damoyolo_phone, cache_dir/root/ai-models, trust_remote_codeTrue ) # 检测单张图片 image_path 你的图片路径.jpg result detector(image_path) # 查看检测结果 print(f检测到 {len(result[boxes])} 个手机) for i, box in enumerate(result[boxes]): print(f手机{i1}: 位置{box}, 置信度{result[scores][i]:.2f})这个API调用方式适合批量处理图片或者集成到其他系统中。不过今天我们的重点是增强Web界面的用户体验。4. Gradio界面汉化实战现在进入正题我们来把英文界面变成中文。Gradio的界面汉化其实很简单就是找到所有显示文字的地方把英文替换成中文。4.1 理解Gradio界面结构首先我们来看看原始的app.py文件是怎么构建界面的。关键部分通常长这样import gradio as gr # 创建界面组件 with gr.Blocks() as demo: gr.Markdown(# DAMO-YOLO Phone Detection) with gr.Row(): with gr.Column(): input_image gr.Image(labelInput Image, typefilepath) examples gr.Examples(examplesexample_images, inputsinput_image) detect_btn gr.Button(Detect, variantprimary) with gr.Column(): output_image gr.Image(labelDetection Result) output_json gr.JSON(labelDetection Data)我们要汉化的就是这些label参数和按钮文字。比如Input Image要改成输入图片Detect要改成开始检测。4.2 完整汉化方案下面是我为你准备的一个完整的汉化版本。你可以直接替换原有的app.py文件或者在此基础上继续添加功能import gradio as gr import os from model_inference import detect_phones # 示例图片路径 example_images [ [assets/demo/example1.jpg], [assets/demo/example2.jpg], [assets/demo/example3.jpg] ] # 创建中文界面 with gr.Blocks(titleDAMO-YOLO 手机检测系统, themegr.themes.Soft()) as demo: # 标题和描述 gr.Markdown(# DAMO-YOLO 实时手机检测系统) gr.Markdown(基于阿里巴巴DAMO-YOLO的高性能手机检测模型 | 准确率: 88.8% | 推理速度: 3.83ms) with gr.Row(): # 左侧输入区域 with gr.Column(scale1): gr.Markdown(### 1. 上传图片) input_image gr.Image( label请上传包含手机的图片, typefilepath, height300 ) gr.Markdown(### 2. 或选择示例图片) examples gr.Examples( examplesexample_images, inputsinput_image, label点击下方图片快速测试, examples_per_page3 ) gr.Markdown(### 3. 开始检测) with gr.Row(): detect_btn gr.Button( 开始检测, variantprimary, sizelg) clear_btn gr.Button( 清空结果, variantsecondary) # 右侧输出区域 with gr.Column(scale1): gr.Markdown(### 4. 检测结果) output_image gr.Image( label检测结果可视化, height400 ) with gr.Accordion( 详细检测数据, openFalse): output_json gr.JSON(label检测数据详情) gr.Markdown(### 5. 统计信息) with gr.Row(): phone_count gr.Number(label检测到手机数量, precision0) avg_confidence gr.Number(label平均置信度, precision2) # 底部说明 gr.Markdown(---) gr.Markdown( **使用说明** 1. 上传一张包含手机的图片或点击上方示例图片 2. 点击开始检测按钮 3. 查看右侧的检测结果和统计信息 4. 红色框表示检测到的手机框上数字为置信度 ) # 绑定按钮事件 detect_btn.click( fndetect_phones, inputsinput_image, outputs[output_image, output_json, phone_count, avg_confidence] ) clear_btn.click( fnlambda: [None, None, 0, 0.0], inputs[], outputs[input_image, output_image, phone_count, avg_confidence] ) # 启动服务 if __name__ __main__: demo.launch( server_name0.0.0.0, server_port7860, shareFalse )4.3 汉化效果对比让我们看看汉化前后的对比汉化前英文界面标题DAMO-YOLO Phone Detection上传区域Input Image按钮Detect结果区域Detection Result数据区域Detection Data汉化后中文界面标题DAMO-YOLO 手机检测系统上传区域请上传包含手机的图片按钮 开始检测结果区域检测结果可视化数据区域检测数据详情除了文字翻译我还做了一些用户体验的优化添加了更明确的步骤提示1. 上传图片、2. 选择示例...增加了统计信息显示手机数量、平均置信度添加了清空按钮方便多次测试使用了更友好的主题和图标现在界面看起来是不是亲切多了接下来我们解决第二个问题如何导出检测结果。5. Excel导出功能实现检测结果只能在线查看这在实际工作中很不方便。比如你要统计一批图片中手机的数量和位置或者要把数据交给其他人分析这时候如果能导出到Excel就太好了。5.1 设计导出数据格式首先我们需要确定Excel文件中要保存哪些信息。对于手机检测任务我觉得以下信息比较有用图片信息图片文件名、检测时间检测结果每个手机的位置坐标、大小、置信度统计信息手机总数、平均置信度、最高/最低置信度基于这个思路我设计了这样的数据结构import pandas as pd from datetime import datetime def prepare_excel_data(image_path, detection_results): 准备导出到Excel的数据 参数: image_path: 图片路径 detection_results: 检测结果字典 返回: DataFrame: 整理好的数据 # 基本信息 image_name os.path.basename(image_path) detect_time datetime.now().strftime(%Y-%m-%d %H:%M:%S) # 提取检测结果 boxes detection_results.get(boxes, []) scores detection_results.get(scores, []) # 构建数据行 data_rows [] for i, (box, score) in enumerate(zip(boxes, scores)): row { 图片名称: image_name, 检测时间: detect_time, 手机编号: i 1, 左上角X: int(box[0]), 左上角Y: int(box[1]), 右下角X: int(box[2]), 右下角Y: int(box[3]), 宽度: int(box[2] - box[0]), 高度: int(box[3] - box[1]), 置信度: round(score, 4), 置信度百分比: f{score*100:.1f}% } data_rows.append(row) # 如果没有检测到手机添加一行提示 if not data_rows: data_rows.append({ 图片名称: image_name, 检测时间: detect_time, 手机编号: 0, 备注: 未检测到手机 }) return pd.DataFrame(data_rows)5.2 实现Excel导出函数有了数据结构接下来实现具体的导出函数import pandas as pd import tempfile import os def export_to_excel(image_path, detection_results): 将检测结果导出到Excel文件 参数: image_path: 图片路径 detection_results: 检测结果 返回: str: Excel文件路径 # 准备数据 df_detections prepare_excel_data(image_path, detection_results) # 创建Excel写入器 excel_file tempfile.NamedTemporaryFile( suffix_手机检测结果.xlsx, deleteFalse ) excel_path excel_file.name excel_file.close() # 使用pandas的ExcelWriter支持多个sheet with pd.ExcelWriter(excel_path, engineopenpyxl) as writer: # Sheet1: 详细检测结果 df_detections.to_excel( writer, sheet_name检测详情, indexFalse ) # Sheet2: 统计摘要 if not detection_results.get(boxes): # 没有检测到手机的情况 summary_data { 统计项: [检测状态, 图片名称, 检测时间], 数值: [未检测到手机, os.path.basename(image_path), datetime.now().strftime(%Y-%m-%d %H:%M:%S)] } else: # 检测到手机的情况 boxes detection_results[boxes] scores detection_results[scores] summary_data { 统计项: [ 检测状态, 图片名称, 检测时间, 手机总数, 平均置信度, 最高置信度, 最低置信度, 平均宽度, 平均高度 ], 数值: [ 检测成功, os.path.basename(image_path), datetime.now().strftime(%Y-%m-%d %H:%M:%S), len(boxes), f{sum(scores)/len(scores)*100:.1f}%, f{max(scores)*100:.1f}%, f{min(scores)*100:.1f}%, f{sum(b[2]-b[0] for b in boxes)/len(boxes):.0f}像素, f{sum(b[3]-b[1] for b in boxes)/len(boxes):.0f}像素 ] } df_summary pd.DataFrame(summary_data) df_summary.to_excel( writer, sheet_name统计摘要, indexFalse ) return excel_path5.3 集成到Gradio界面现在我们需要把这个导出功能集成到Web界面中。在原有的汉化界面上添加导出按钮和功能# 在原有的界面代码基础上添加导出功能 # 在输出区域添加导出按钮 with gr.Column(scale1): gr.Markdown(### 4. 检测结果) output_image gr.Image( label检测结果可视化, height400 ) with gr.Accordion( 详细检测数据, openFalse): output_json gr.JSON(label检测数据详情) gr.Markdown(### 5. 统计信息) with gr.Row(): phone_count gr.Number(label检测到手机数量, precision0) avg_confidence gr.Number(label平均置信度, precision2) # 新增导出区域 gr.Markdown(### 6. 结果导出) with gr.Row(): export_btn gr.Button( 导出到Excel, variantsecondary) export_file gr.File(label下载Excel文件, visibleFalse) # 显示导出状态 export_status gr.Textbox(label导出状态, visibleFalse) # 修改检测函数返回更多数据供导出使用 def detect_and_prepare_export(image_path): 增强的检测函数同时准备导出数据 # 调用原始检测函数 result_image, result_json detect_phones(image_path) # 计算统计信息 phone_count 0 avg_confidence 0.0 if result_json and boxes in result_json: phone_count len(result_json[boxes]) if phone_count 0 and scores in result_json: avg_confidence sum(result_json[scores]) / phone_count # 准备导出数据但不立即生成文件 export_data { image_path: image_path, detection_results: result_json, result_image: result_image } return result_image, result_json, phone_count, avg_confidence, export_data # 导出函数 def export_detection_results(export_data): 处理导出请求 if not export_data or detection_results not in export_data: return None, 错误没有可导出的数据 try: excel_path export_to_excel( export_data[image_path], export_data[detection_results] ) # 返回文件供下载 return excel_path, 导出成功点击上方文件下载 except Exception as e: return None, f导出失败{str(e)} # 更新按钮事件绑定 detect_btn.click( fndetect_and_prepare_export, inputsinput_image, outputs[output_image, output_json, phone_count, avg_confidence, gr.State()] ) # 绑定导出按钮事件 export_btn.click( fnexport_detection_results, inputsgr.State(), outputs[export_file, export_status] )6. 完整代码整合与部署现在我们把所有功能整合到一个完整的应用中。下面是完整的app_enhanced.py文件import gradio as gr import os import pandas as pd import tempfile from datetime import datetime from model_inference import detect_phones # 示例图片 example_images [ [assets/demo/example1.jpg], [assets/demo/example2.jpg], [assets/demo/example3.jpg] ] def prepare_excel_data(image_path, detection_results): 准备Excel导出数据 image_name os.path.basename(image_path) detect_time datetime.now().strftime(%Y-%m-%d %H:%M:%S) boxes detection_results.get(boxes, []) scores detection_results.get(scores, []) data_rows [] for i, (box, score) in enumerate(zip(boxes, scores)): row { 图片名称: image_name, 检测时间: detect_time, 手机编号: i 1, 左上角X: int(box[0]), 左上角Y: int(box[1]), 右下角X: int(box[2]), 右下角Y: int(box[3]), 宽度: int(box[2] - box[0]), 高度: int(box[3] - box[1]), 置信度: round(score, 4), 置信度百分比: f{score*100:.1f}% } data_rows.append(row) if not data_rows: data_rows.append({ 图片名称: image_name, 检测时间: detect_time, 手机编号: 0, 备注: 未检测到手机 }) return pd.DataFrame(data_rows) def export_to_excel(image_path, detection_results): 导出到Excel文件 df_detections prepare_excel_data(image_path, detection_results) excel_file tempfile.NamedTemporaryFile( suffix_手机检测结果.xlsx, deleteFalse ) excel_path excel_file.name excel_file.close() with pd.ExcelWriter(excel_path, engineopenpyxl) as writer: # 检测详情 df_detections.to_excel(writer, sheet_name检测详情, indexFalse) # 统计摘要 if not detection_results.get(boxes): summary_data { 统计项: [检测状态, 图片名称, 检测时间], 数值: [未检测到手机, os.path.basename(image_path), datetime.now().strftime(%Y-%m-%d %H:%M:%S)] } else: boxes detection_results[boxes] scores detection_results[scores] summary_data { 统计项: [ 检测状态, 图片名称, 检测时间, 手机总数, 平均置信度, 最高置信度, 最低置信度, 平均宽度, 平均高度 ], 数值: [ 检测成功, os.path.basename(image_path), datetime.now().strftime(%Y-%m-%d %H:%M:%S), len(boxes), f{sum(scores)/len(scores)*100:.1f}%, f{max(scores)*100:.1f}%, f{min(scores)*100:.1f}%, f{sum(b[2]-b[0] for b in boxes)/len(boxes):.0f}像素, f{sum(b[3]-b[1] for b in boxes)/len(boxes):.0f}像素 ] } df_summary pd.DataFrame(summary_data) df_summary.to_excel(writer, sheet_name统计摘要, indexFalse) return excel_path def detect_and_prepare_export(image_path): 检测并准备导出数据 result_image, result_json detect_phones(image_path) phone_count 0 avg_confidence 0.0 if result_json and boxes in result_json: phone_count len(result_json[boxes]) if phone_count 0 and scores in result_json: avg_confidence sum(result_json[scores]) / phone_count export_data { image_path: image_path, detection_results: result_json, result_image: result_image } return result_image, result_json, phone_count, avg_confidence, export_data def export_detection_results(export_data): 处理导出请求 if not export_data or detection_results not in export_data: return None, 错误没有可导出的数据 try: excel_path export_to_excel( export_data[image_path], export_data[detection_results] ) return excel_path, 导出成功点击上方文件下载 except Exception as e: return None, f导出失败{str(e)} # 创建增强版界面 with gr.Blocks(titleDAMO-YOLO 手机检测系统, themegr.themes.Soft()) as demo: gr.Markdown(# DAMO-YOLO 实时手机检测系统) gr.Markdown(基于阿里巴巴DAMO-YOLO的高性能手机检测模型 | 准确率: 88.8% | 推理速度: 3.83ms) with gr.Row(): # 输入区域 with gr.Column(scale1): gr.Markdown(### 1. 上传图片) input_image gr.Image( label请上传包含手机的图片, typefilepath, height300 ) gr.Markdown(### 2. 或选择示例图片) examples gr.Examples( examplesexample_images, inputsinput_image, label点击下方图片快速测试, examples_per_page3 ) gr.Markdown(### 3. 开始检测) with gr.Row(): detect_btn gr.Button( 开始检测, variantprimary, sizelg) clear_btn gr.Button( 清空结果, variantsecondary) # 输出区域 with gr.Column(scale1): gr.Markdown(### 4. 检测结果) output_image gr.Image(label检测结果可视化, height400) with gr.Accordion( 详细检测数据, openFalse): output_json gr.JSON(label检测数据详情) gr.Markdown(### 5. 统计信息) with gr.Row(): phone_count gr.Number(label检测到手机数量, precision0) avg_confidence gr.Number(label平均置信度, precision2) gr.Markdown(### 6. 结果导出) with gr.Row(): export_btn gr.Button( 导出到Excel, variantsecondary) export_file gr.File(label下载Excel文件, visibleFalse) export_status gr.Textbox(label导出状态, visibleFalse) # 说明区域 gr.Markdown(---) gr.Markdown( **使用说明** 1. 上传图片或使用示例图片 2. 点击开始检测按钮 3. 查看检测结果和统计信息 4. 点击导出到Excel保存检测数据 **Excel文件包含** - 检测详情表每个手机的详细位置和置信度 - 统计摘要表整体检测结果的统计信息 ) # 状态变量 export_data_state gr.State() # 事件绑定 detect_btn.click( fndetect_and_prepare_export, inputsinput_image, outputs[output_image, output_json, phone_count, avg_confidence, export_data_state] ) export_btn.click( fnexport_detection_results, inputsexport_data_state, outputs[export_file, export_status] ).then( fnlambda: gr.File(visibleTrue), outputsexport_file ).then( fnlambda: gr.Textbox(visibleTrue), outputsexport_status ) clear_btn.click( fnlambda: [None, None, 0, 0.0, None, None, None], inputs[], outputs[input_image, output_image, phone_count, avg_confidence, export_file, export_status, export_data_state] ) if __name__ __main__: demo.launch( server_name0.0.0.0, server_port7860, shareFalse )6.1 部署增强版服务保存上面的代码为app_enhanced.py然后启动服务# 确保安装了所有依赖 pip install pandas openpyxl # 启动增强版服务 python3 app_enhanced.py现在访问http://localhost:7860你就能看到完全汉化并且带有Excel导出功能的手机检测系统了。7. 使用效果与进阶技巧7.1 实际使用演示让我们通过一个完整的例子来看看这个增强版系统怎么用上传图片点击上传区域选择一张包含手机的图片开始检测点击 开始检测按钮查看结果右侧会显示带红色框的检测结果下方显示检测到3个手机平均置信度92.5%导出数据点击 导出到Excel按钮下载文件点击出现的下载链接获取手机检测结果.xlsx打开Excel文件你会看到两个工作表检测详情每个手机的精确位置、大小、置信度统计摘要整体统计信息包括手机总数、平均置信度等7.2 进阶使用技巧如果你需要进一步定制这个系统这里有几个实用的技巧批量处理图片import os from model_inference import detect_phones def batch_process_images(image_folder, output_excel): 批量处理文件夹中的所有图片 all_results [] for filename in os.listdir(image_folder): if filename.lower().endswith((.jpg, .jpeg, .png)): image_path os.path.join(image_folder, filename) result_image, result_data detect_phones(image_path) # 保存结果 all_results.append({ filename: filename, detections: len(result_data.get(boxes, [])), data: result_data }) # 导出到Excel # ... 这里可以扩展批量导出功能自定义导出格式 如果你需要其他格式的导出比如CSV或JSON可以轻松扩展def export_to_csv(image_path, detection_results): 导出到CSV文件 df prepare_excel_data(image_path, detection_results) csv_file tempfile.NamedTemporaryFile(suffix_检测结果.csv, deleteFalse) df.to_csv(csv_file.name, indexFalse, encodingutf-8-sig) return csv_file.name def export_to_json(image_path, detection_results): 导出到JSON文件 import json data { image: os.path.basename(image_path), detection_time: datetime.now().isoformat(), results: detection_results } json_file tempfile.NamedTemporaryFile(suffix_检测结果.json, deleteFalse) with open(json_file.name, w, encodingutf-8) as f: json.dump(data, f, ensure_asciiFalse, indent2) return json_file.name界面美化 Gradio支持多种主题你可以根据需要更换# 使用不同的主题 demo gr.Blocks(themegr.themes.Default()) # 默认主题 demo gr.Blocks(themegr.themes.Soft()) # 柔和主题本文使用的 demo gr.Blocks(themegr.themes.Monochrome()) # 单色主题8. 总结通过本教程我们成功将DAMO-YOLO手机检测服务从一个基础的英文界面改造成了一个功能完善、用户友好的中文应用。主要改进包括完全汉化界面所有按钮、标签、提示都翻译成了中文让中文用户使用起来更加顺手Excel导出功能一键将检测结果保存为Excel文件包含详细数据和统计摘要用户体验优化添加了统计信息显示、清空按钮、步骤提示等实用功能代码结构清晰模块化设计方便后续扩展和维护这个增强版系统特别适合以下场景质量检测生产线上的手机外观检测需要记录每个产品的检测结果安全监控公共场所的手机使用监控需要统计和分析数据学术研究收集手机检测的实验数据用于论文或报告项目演示向客户或领导展示AI检测能力有直观的界面和可导出的数据最重要的是我们所有的改进都是在不改变原有检测模型的前提下完成的。DAMO-YOLO模型依然保持着88.8%的高准确率和3.83毫秒的快速推理能力我们只是给它穿上了一件更漂亮、更实用的外衣。如果你需要进一步定制这个系统比如添加批量处理、支持视频输入、或者集成到其他系统中现在的代码结构也为你打下了良好的基础。希望这个教程对你有所帮助祝你在手机检测的应用中取得好成果获取更多AI镜像想探索更多AI镜像和应用场景访问 CSDN星图镜像广场提供丰富的预置镜像覆盖大模型推理、图像生成、视频生成、模型微调等多个领域支持一键部署。

更多文章