如何将TensorFlow API目标检测的对象名称保存至文本文件?
嘿,我来帮你搞定这个问题!结合TensorFlow Object Detection API的常规使用流程,你只需要在检测推理的代码逻辑里加几行,就能轻松把检测到的类别名称和对应的准确率(置信度)写入文本文件。下面是具体的操作步骤和代码示例:
步骤1:定位检测结果处理的代码位置
不管你用的是官方的Jupyter Notebook教程还是自定义的推理脚本,核心是找到**处理模型输出(detections)**的代码段。比如在官方的tutorial.ipynb里,有一段专门循环处理检测框、类别和置信度的逻辑,我们就从这里入手。
步骤2:添加文本文件写入逻辑
根据你的使用场景(单图片/多帧视频),可以选择两种写入方式:
方式一:单图片检测 - 覆盖写入
如果只处理单张图片,用'w'模式打开文件会覆盖之前的内容,适合单次检测的结果保存:
# 假设你已经获取了以下核心变量: # category_index:从label_map加载的类别索引字典 # detections:模型输出的检测结果字典 # min_score_thresh:自定义的置信度阈值(比如0.5,过滤低准确率结果) # 打开文本文件,指定编码避免乱码 with open('detection_results.txt', 'w', encoding='utf-8') as f: # 筛选出符合置信度要求的检测结果索引 valid_indices = np.where(detections['detection_scores'] > min_score_thresh)[0] for idx in valid_indices: # 获取检测对象的类别名称 class_name = category_index[detections['detection_classes'][idx]]['name'] # 提取并格式化准确率(保留两位小数) accuracy = round(detections['detection_scores'][idx].item(), 2) # 写入文件,每行一条结果 f.write(f"检测对象:{class_name},准确率:{accuracy}\n")
方式二:视频/多图片检测 - 追加写入
如果处理视频流或者批量图片,想要保留所有检测记录,把打开模式改成'a'(追加),还可以加上时间戳区分不同批次的检测结果:
from datetime import datetime # 获取当前时间作为检测批次标识 current_batch_time = datetime.now().strftime("%Y-%m-%d %H:%M:%S") with open('detection_results.txt', 'a', encoding='utf-8') as f: f.write(f"=== 检测批次:{current_batch_time} ===\n") valid_indices = np.where(detections['detection_scores'] > min_score_thresh)[0] for idx in valid_indices: class_name = category_index[detections['detection_classes'][idx]]['name'] accuracy = round(detections['detection_scores'][idx].item(), 2) f.write(f"检测对象:{class_name},准确率:{accuracy}\n")
步骤3:确保类别索引正确加载
别忘了,category_index是从你的label_map文件生成的,官方代码里通常会有这段初始化逻辑,你需要替换成自己的label_map路径:
from object_detection.utils import label_map_util # 替换为你的label_map.pbtxt文件路径 label_map_path = 'path/to/your/label_map.pbtxt' label_map = label_map_util.load_labelmap(label_map_path) categories = label_map_util.convert_label_map_to_categories(label_map, max_num_classes=90, use_display_name=True) category_index = label_map_util.create_category_index(categories)
额外小技巧:直接联动语音输出
既然你最终要做语音播报,其实可以在写入文件的同时直接调用语音合成库(比如pyttsx3),不用后续再读取文件:
import pyttsx3 # 初始化语音引擎 engine = pyttsx3.init() valid_indices = np.where(detections['detection_scores'] > min_score_thresh)[0] for idx in valid_indices: class_name = category_index[detections['detection_classes'][idx]]['name'] accuracy = round(detections['detection_scores'][idx].item(), 2) result_text = f"检测到{class_name},准确率{accuracy}" # 写入文件 with open('detection_results.txt', 'a', encoding='utf-8') as f: f.write(result_text + "\n") # 语音播报 engine.say(result_text) engine.runAndWait()
内容的提问来源于stack exchange,提问作者Nishajith .A
相关产品推荐
相关产品推荐

