os讲堂 & argparse讲堂 & 代码解读deepsort 里面的genarate_video.py

百里泓
2023-12-01

generate_videos.py

# vim: expandtab:ts=4:sw=4
import os
import argparse
import show_results


def convert(filename_in, filename_out, ffmpeg_executable="ffmpeg"):
    import subprocess
    command = [ffmpeg_executable, "-i", filename_in, "-c:v", "libx264",
               "-preset", "slow", "-crf", "21", filename_out]
    subprocess.call(command)


def parse_args():
    """ Parse command line arguments.
    """
    parser = argparse.ArgumentParser(description="Siamese Tracking")
    parser.add_argument(
        "--mot_dir", help="Path to MOTChallenge directory (train or test)",
        required=True)
    parser.add_argument(
        "--result_dir", help="Path to the folder with tracking output.",
        required=True)
    parser.add_argument(
        "--output_dir", help="Folder to store the videos in. Will be created "
        "if it does not exist.",
        required=True)
    parser.add_argument(
        "--convert_h264", help="If true, convert videos to libx264 (requires "
        "FFMPEG", default=False)
    parser.add_argument(
        "--update_ms", help="Time between consecutive frames in milliseconds. "
        "Defaults to the frame_rate specified in seqinfo.ini, if available.",
        default=None)
    return parser.parse_args()


if __name__ == "__main__":
    args = parse_args()

    os.makedirs(args.output_dir, exist_ok=True)#os.makedirs()函数创建多级目录。不存在则创建
    for sequence_txt in os.listdir(args.result_dir):    #sequence_txt也可以有别的代替,os.listdir()是生成一个列表,成员是result_dir目录下的文件.
        sequence = os.path.splitext(sequence_txt)[0]    #os.path.splittext()分离文件名与扩展名.元组形式保存('文件名','扩展名')为字符串,[0]表示取文件名
        sequence_dir = os.path.join(args.mot_dir, sequence)#mot_dir是一个路径例如aa/bb,sequence是文件名MOT16-06,连接起来就是aa/bb/MOT16-06
        if not os.path.exists(sequence_dir):        #os.path.exists()存在返回True,本文是判断是否不存在,如果不存在继续??
            continue
        result_file = os.path.join(args.result_dir, sequence_txt)   #result_file='result_dir/MOT16-06.txt' 
        update_ms = args.update_ms
        video_filename = os.path.join(args.output_dir, "%s.avi" % sequence)

        print("Saving %s to %s." % (sequence_txt, video_filename))
        show_results.run(
            sequence_dir, result_file, False, None, update_ms, video_filename)
            #sequence_dir='mot_dir/hypothese'  result_file='result_dir/hypotheses.txt'
    if not args.convert_h264:
        import sys
        sys.exit()
    for sequence_txt in os.listdir(args.result_dir):
        sequence = os.path.splitext(sequence_txt)[0]
        sequence_dir = os.path.join(args.mot_dir, sequence)
        if not os.path.exists(sequence_dir):
            continue
        filename_in = os.path.join(args.output_dir, "%s.avi" % sequence)
        filename_out = os.path.join(args.output_dir, "%s.mp4" % sequence)
        convert(filename_in, filename_out)

 

show_results.py

# vim: expandtab:ts=4:sw=4
import argparse

import cv2
import numpy as np

import deep_sort_app
from deep_sort.iou_matching import iou
from application_util import visualization


DEFAULT_UPDATE_MS = 20

#sequence_dir='mot_dir/MOT16-06'  result_file='result_dir/MOT16-06.txt'
def run(sequence_dir, result_file, show_false_alarms=False, detection_file=None,
        update_ms=None, video_filename=None):
    """Run tracking result visualization.

    Parameters
    ----------
    sequence_dir : str
        Path to the MOTChallenge sequence directory.
    result_file : str
        Path to the tracking output file in MOTChallenge ground truth format.
    show_false_alarms : Optional[bool]
        If True, false alarms are highlighted as red boxes.
    detection_file : Optional[str]
        Path to the detection file.
    update_ms : Optional[int]
        Number of milliseconds between cosecutive frames. Defaults to (a) the
        frame rate specifid in the seqinfo.ini file or DEFAULT_UDPATE_MS ms if
        seqinfo.ini is not available.
    video_filename : Optional[Str]
        If not None, a video of the tracking results is written to this file.

    """
    seq_info = deep_sort_app.gather_sequence_info(sequence_dir, detection_file)
    results = np.loadtxt(result_file, delimiter=',')  #delimiter=','删掉,每一行当作一个向量输出

    if show_false_alarms and seq_info["groundtruth"] is None:
        raise ValueError("No groundtruth available. Cannot show false alarms.")

    def frame_callback(vis, frame_idx):
        print("Frame idx", frame_idx)
        image = cv2.imread(
            seq_info["image_filenames"][frame_idx], cv2.IMREAD_COLOR)

        vis.set_image(image.copy())

        if seq_info["detections"] is not None:
            detections = deep_sort_app.create_detections(
                seq_info["detections"], frame_idx)
            vis.draw_detections(detections)
                             ###对此部分深入解读\
        mask = results[:, 0].astype(np.int) == frame_idx#把第0列与当前帧编号进行判断,等是True
        track_ids = results[mask, 1].astype(np.int)
        boxes = results[mask, 2:6]
        vis.draw_groundtruth(track_ids, boxes)
                             ###对此部分深入解读/
        if show_false_alarms:
            groundtruth = seq_info["groundtruth"]
            mask = groundtruth[:, 0].astype(np.int) == frame_idx
            gt_boxes = groundtruth[mask, 2:6]
            for box in boxes:
                # NOTE(nwojke): This is not strictly correct, because we don't
                # solve the assignment problem here.
                min_iou_overlap = 0.5
                if iou(box, gt_boxes).max() < min_iou_overlap:
                    vis.viewer.color = 0, 0, 255
                    vis.viewer.thickness = 4
                    vis.viewer.rectangle(*box.astype(np.int))

    if update_ms is None:
        update_ms = seq_info["update_ms"]
    if update_ms is None:
        update_ms = DEFAULT_UPDATE_MS
    visualizer = visualization.Visualization(seq_info, update_ms)
    if video_filename is not None:
        visualizer.viewer.enable_videowriter(video_filename)
    visualizer.run(frame_callback)


def parse_args():
    """ Parse command line arguments.
    """
    parser = argparse.ArgumentParser(description="Siamese Tracking")
    parser.add_argument(
        "--sequence_dir", help="Path to the MOTChallenge sequence directory.",
        default=None, required=True)
    parser.add_argument(
        "--result_file", help="Tracking output in MOTChallenge file format.",
        default=None, required=True)
    parser.add_argument(
        "--detection_file", help="Path to custom detections (optional).",
        default=None)
    parser.add_argument(
        "--update_ms", help="Time between consecutive frames in milliseconds. "
        "Defaults to the frame_rate specified in seqinfo.ini, if available.",
        default=None)
    parser.add_argument(
        "--output_file", help="Filename of the (optional) output video.",
        default=None)
    parser.add_argument(
        "--show_false_alarms", help="Show false alarms as red bounding boxes.",
        type=bool, default=False)
    return parser.parse_args()


if __name__ == "__main__":
    args = parse_args()
    run(
        args.sequence_dir, args.result_file, args.show_false_alarms,
        args.detection_file, args.update_ms, args.output_file)

深入解读

>>> import numpy as np
>>> results=np.loadtxt('MOT16-06.txt',delimiter=',')
>>> print (results)
[[  3.00000000e+00   1.00000000e+00   2.96230000e+02 ...,  -1.00000000e+00
   -1.00000000e+00  -1.00000000e+00]
 [  3.00000000e+00   2.00000000e+00   1.46870000e+02 ...,  -1.00000000e+00
   -1.00000000e+00  -1.00000000e+00]
 [  3.00000000e+00   3.00000000e+00   3.57570000e+02 ...,  -1.00000000e+00
   -1.00000000e+00  -1.00000000e+00]
 ..., 
 [  1.19400000e+03   5.11000000e+02   4.16390000e+02 ...,  -1.00000000e+00
   -1.00000000e+00  -1.00000000e+00]
 [  1.19400000e+03   5.15000000e+02   3.37960000e+02 ...,  -1.00000000e+00
   -1.00000000e+00  -1.00000000e+00]
 [  1.19400000e+03   5.16000000e+02   5.25010000e+02 ...,  -1.00000000e+00
   -1.00000000e+00  -1.00000000e+00]]
>>> result=results.astype(np.int)
>>> print(result)
[[   3    1  296 ...,   -1   -1   -1]
 [   3    2  146 ...,   -1   -1   -1]
 [   3    3  357 ...,   -1   -1   -1]
 ..., 
 [1194  511  416 ...,   -1   -1   -1]
 [1194  515  337 ...,   -1   -1   -1]
 [1194  516  525 ...,   -1   -1   -1]]
>>> mask=result[:,0]==3
>>> print(mask)
[ True  True  True ..., False False False]
>>> track_ids=result[mask,1]
>>> print(track_ids)
[1 2 3 4 5 6 7 8]
>>> boxes=results[mask,2:6]
>>> print(boxs)
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
NameError: name 'boxs' is not defined
>>> print(boxes)
[[ 296.23  188.23   30.76   76.35]
 [ 146.87  187.25   34.65   75.82]
 [ 357.57  188.85   34.33   86.97]
 [ 216.33  195.9    29.87   63.12]
 [ 121.59  194.     28.41   67.02]
 [ 505.88  188.02   39.55   90.68]
 [ 418.91  193.02   34.12   79.24]
 [ 442.89  189.3    29.82   79.03]]
>>> 

1

 

 类似资料: