You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何将TensorFlow摄像头/视频检测的边界框坐标保存至CSV文件?

TensorFlow目标检测结果导出到CSV/Excel

要把检测到的对象、边界框和时间记录到CSV或Excel,我们可以借助pandas库实现,以下是修改后的完整代码及关键说明:

修改后的完整代码

import cv2
import numpy as np
import tensorflow as tf
from object_detection.utils import visualization_utils as viz_utils
import pandas as pd
from datetime import datetime

# 初始化视频捕获(0为摄像头,替换为视频路径即可处理本地视频)
cap = cv2.VideoCapture(0)
width = int(cap.get(cv2.CAP_PROP_FRAME_WIDTH))
height = int(cap.get(cv2.CAP_PROP_FRAME_HEIGHT))

# 初始化用于存储检测结果的DataFrame
columns = ["检测时间", "类别名称", "左上角x", "左上角y", "右下角x", "右下角y"]
detection_results = pd.DataFrame(columns=columns)

while cap.isOpened(): 
    ret, frame = cap.read()
    if not ret:
        break  # 视频读取完毕或出错时退出
    
    image_np = np.array(frame)
    input_tensor = tf.convert_to_tensor(np.expand_dims(image_np, 0), dtype=tf.float32)
    detections = detect_fn(input_tensor)

    num_detections = int(detections.pop('num_detections'))
    detections = {key: value[0, :num_detections].numpy()
                  for key, value in detections.items()}
    detections['num_detections'] = num_detections
    detections['detection_classes'] = detections['detection_classes'].astype(np.int64)

    label_id_offset = 1
    image_np_with_detections = image_np.copy()

    # 可视化检测结果(保留原逻辑)
    viz_utils.visualize_boxes_and_labels_on_image_array(
                image_np_with_detections,
                detections['detection_boxes'],
                detections['detection_classes']+label_id_offset,
                detections['detection_scores'],
                category_index,
                use_normalized_coordinates=True,
                max_boxes_to_draw=1,
                min_score_thresh=.75,
                agnostic_mode=False)

    cv2.imshow('object detection', cv2.resize(image_np_with_detections, (800, 600)))

    # ------------------- 核心:记录检测结果 -------------------
    current_time = datetime.now().strftime("%Y-%m-%d %H:%M:%S.%f")[:-3]  # 精确到毫秒
    min_score = 0.75  # 和可视化阈值保持一致
    
    # 遍历所有检测结果,筛选符合置信度要求的条目
    for i in range(num_detections):
        score = detections['detection_scores'][i]
        if score >= min_score:
            # 获取类别名称
            class_id = detections['detection_classes'][i] + label_id_offset
            class_name = category_index[class_id]['name']
            
            # 转换边界框坐标:从归一化值转为实际像素值(注意detection_boxes格式是[ymin, xmin, ymax, xmax])
            ymin, xmin, ymax, xmax = detections['detection_boxes'][i]
            x1 = int(xmin * width)
            y1 = int(ymin * height)
            x2 = int(xmax * width)
            y2 = int(ymax * height)
            
            # 将结果添加到DataFrame
            new_row = pd.DataFrame([{
                "检测时间": current_time,
                "类别名称": class_name,
                "左上角x": x1,
                "左上角y": y1,
                "右下角x": x2,
                "右下角y": y2
            }])
            detection_results = pd.concat([detection_results, new_row], ignore_index=True)

    # 退出逻辑
    if cv2.waitKey(10) & 0xFF == ord('q'):
        cap.release()
        cv2.destroyAllWindows()
        break

# 退出后将结果保存到CSV和Excel
detection_results.to_csv("检测结果.csv", index=False, encoding="utf-8-sig")
detection_results.to_excel("检测结果.xlsx", index=False, engine="openpyxl")
print("检测结果已保存到 检测结果.csv 和 检测结果.xlsx")

关键说明

  1. 依赖安装:确保已安装所需库,执行以下命令:

    pip install pandas openpyxl
    
    • pandas用于数据管理和导出
    • openpyxl是pandas写入Excel文件的依赖引擎
  2. 坐标转换:TensorFlow目标检测返回的detection_boxes是归一化坐标(范围0-1),格式为[ymin, xmin, ymax, xmax],需乘以视频/摄像头的宽高得到实际像素位置。

  3. 数据筛选:只记录置信度≥0.75的结果,和可视化阈值保持一致,避免无效数据。

  4. 时间精度:记录到毫秒级,方便精准对应每帧的检测结果。

  5. 视频适配:如果处理本地视频,只需将cv2.VideoCapture(0)替换为视频文件路径,比如cv2.VideoCapture("your_video.mp4")。

内容的提问来源于stack exchange,提问作者Niklas Gutheil

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.15 18:05:25