如何将暗网 YOLOv4 视频的输出保存在每一帧的 txt 文件中?

How to save output of darknet YOLOv4 video in a txt file for each frame?

我正在使用 darknet 在我的自定义数据集上使用 YOLOv4 检测对象。对于我使用的视频检测:

./darknet detector demo data/obj.data yolo-obj.cfg yolo-obj_best.weights -ext_output video.mp4 -out-filename video_results.mp4

这为我的视频提供了为每次检测打印的边界框。但是,我想为每个帧编号创建一个 .txt(或 .csv)文件预测。

我确实找到了 ,但这在 json 文件中给出了输出,我需要一个 .txt 或 .csv 文件。我对C不是很熟悉,所以我很难把这个答案修改成我需要的格式。

已经有关于如何使用命令行的说明,特别是如何以 .txt 格式保存结果,link:

https://github.com/AlexeyAB/darknet#how-to-use-on-the-command-line

为了节省时间,我会提供可能有用的观点:

  • 要处理图像列表 data/train.txt 并将检测结果保存到 result.txt,请使用:
  • darknet.exe 检测器测试 cfg/coco.data cfg/yolov4.cfg yolov4.weights -dont_show -ext_output < data/train.txt > result.txt

可能会迟到,但可能对其他人有帮助。

我听从了 Rafael 的建议,写了一些代码从 JSON 转移到 cvs。我会把它放在这里,以防有人想使用它。这是针对分析视频的情况,所以每个“图像”都是视频中的一帧。

import json
import csv

# with and height of the video
WIDTH = 1920
HEIGHT = 1080


with open('~/detection_results.json', encoding='latin-1') as json_file:
    data = json.load(json_file)
    
# open csv file
csv_file_to_make = open('~/detection_results.csv', 'w', newline='\n')

csv_file = csv.writer(csv_file_to_make)

# write the header 
# NB x and y values are relative
csv_file.writerow(['Frame ID',
                   'class',
                   'x_center',
                   'y_center',
                   'bb_width',
                   'bb_heigth',
                   'confidence'])


for frame in data:
    frame_id = frame['frame_id']
    instrument = ""
    center_x = ""
    center_y = ""
    bb_width = ""
    bb_height = ""
    confidence = ""

    if frame['objects'] == []:
        csv_file.writerow([frame_id,
                              class,
                              center_x,
                              center_y,
                              bb_width,
                              bb_height,
                              confidence
                               ])
    else:
        for single_detection in frame['objects']:
            instrument = single_detection['name']
            center_x = WIDTH*single_detection['relative_coordinates']['center_x']
            center_y = HEIGHT*single_detection['relative_coordinates']['center_y']
            bb_width = WIDTH*single_detection['relative_coordinates']['width']
            bb_height = HEIGHT*single_detection['relative_coordinates']['height']
            confidence = single_detection['confidence']
        
            csv_file.writerow([frame_id,
                              class,
                              center_x,
                              center_y,
                              bb_width,
                              bb_height,
                              confidence
                               ])
    
csv_file_to_make.close()

希望对您有所帮助!如果您看到优化此代码的解决方案,当然也欢迎 :)