如何将darknet YOLOv4视频的输出保存为每帧的txt文件?

2024-05-12 22:26:23 发布

您现在位置:Python中文网/ 问答频道 /正文

我正在使用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)文件,其中包含预测的每个帧编号

我确实找到了this answer,但这会在json文件中提供输出,我需要一个.txt或.csv文件。我不太熟悉C,所以我发现很难将这个答案修改成我需要的格式


Tags: 文件csv对象txtobjdata视频video
2条回答

我遵循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()

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

关于如何使用命令行,特别是如何将结果保存为.txt格式,已经有一个解释,链接:

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

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

  • 要处理图像数据列表/train.txt并将检测结果保存到result.txt,请使用:
  • darknet.exe探测器测试cfg/coco.data cfg/yolov4.cfg yolov4.weights-不显示-外部输出<;data/train.txt>;result.txt

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

相关问题 更多 >