File size: 4,556 Bytes
de2b807
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
# SPDX-License-Identifier: MIT
# Copyright (C) Intel Corporation
#
# Motion Tracking: DLStreamer pipeline sample.
# See README.md for prerequisites and inputs. Run: python3 dlstreamer_sample.py

import subprocess
from collections import defaultdict

import numpy as np
import gi

gi.require_version("Gst", "1.0")
gi.require_version("GstAnalytics", "1.0")
gi.require_version("GstVideo", "1.0")
from gi.repository import Gst, GLib, GstAnalytics, GstVideo

Gst.init([])

# Import cv2 after Gst.init to avoid GStreamer re-initialization conflicts.
import cv2

# Select the model: "yolo26n" (default) or "detr-resnet-50".
MODEL = "yolo26n"

# For CPU: change device=GPU to device=CPU.
# For NPU: change device=GPU to device=NPU (batch-size=1, nireq=4 recommended).
pipeline_str = (
    "filesrc location=test_video.mp4 ! decodebin3 ! "
    "videoconvert ! "
    f"gvadetect model={MODEL}_openvino_model/{MODEL}.xml "
    "device=GPU "
    "threshold=0.4 ! queue ! "
    "gvatrack tracking-type=short-term-imageless ! queue ! "
    "gvawatermark ! videoconvert ! video/x-raw,format=BGR ! "
    "appsink name=sink emit-signals=false sync=false"
)
pipeline = Gst.parse_launch(pipeline_str)
appsink = pipeline.get_by_name("sink")

# Distinct colors for trajectory lines (one per track ID).
COLORS = [
    (255, 0, 0), (0, 255, 0), (0, 0, 255), (255, 255, 0),
    (255, 0, 255), (0, 255, 255), (128, 0, 255), (255, 128, 0),
]
track_history: dict[int, list[tuple[int, int]]] = defaultdict(list)

pipeline.set_state(Gst.State.PLAYING)

proc = None

while True:
    sample = appsink.emit("pull-sample")
    if sample is None:
        break

    buf = sample.get_buffer()
    caps = sample.get_caps()
    struct = caps.get_structure(0)
    width = struct.get_value("width")
    height = struct.get_value("height")

    # Start ffmpeg encoder on the first frame.
    if proc is None:
        ok, fps_num, fps_den = struct.get_fraction("framerate")
        fps = fps_num / fps_den if ok and fps_den > 0 else 30.0
        proc = subprocess.Popen(
            ["ffmpeg", "-y", "-f", "rawvideo", "-pix_fmt", "bgr24",
             "-s", f"{width}x{height}", "-r", str(fps),
             "-i", "pipe:0", "-c:v", "libx264", "-pix_fmt", "yuv420p",
             "-movflags", "+faststart", "output_dlstreamer.mp4"],
            stdin=subprocess.PIPE, stderr=subprocess.DEVNULL,
        )

    # Read detection / tracking metadata via GstAnalytics.
    rmeta = GstAnalytics.buffer_get_analytics_relation_meta(buf)
    regions_data = []
    if rmeta is not None:
        od_entries = []
        trk_map = {}  # metadata_id -> tracking_id
        idx = 1
        while True:
            ok_od, od = rmeta.get_od_mtd(idx)
            ok_trk, trk = rmeta.get_tracking_mtd(idx)
            if not ok_od and not ok_trk:
                break
            if ok_od:
                label = GLib.quark_to_string(od.get_obj_type())
                _, x, y, w, h, conf = od.get_location()
                od_entries.append((idx, label, int(x + w / 2), int(y + h / 2)))
            if ok_trk:
                ok2, tid, _, _, _ = trk.get_info()
                if ok2:
                    trk_map[idx] = tid
            idx += 1
        for od_id, label, cx, cy in od_entries:
            tid = 0
            for trk_meta_id, tracking_id in trk_map.items():
                if rmeta.get_relation(od_id, trk_meta_id) != GstAnalytics.RelTypes.NONE:
                    tid = tracking_id
                    break
            regions_data.append((tid, label, cx, cy))

    # Map buffer read-only and copy pixels to a writable numpy array.
    success, map_info = buf.map(Gst.MapFlags.READ)
    if not success:
        continue
    video_info = GstVideo.VideoInfo.new_from_caps(caps)
    stride = video_info.stride[0]
    arr = np.ndarray((height, width, 3), dtype=np.uint8,
                     buffer=map_info.data, strides=(stride, 3, 1)).copy()
    buf.unmap(map_info)

    # Draw per-track trajectory polylines on the frame copy.
    for tid, label, cx, cy in regions_data:
        track = track_history[tid]
        track.append((cx, cy))
        if len(track) > 30:
            track.pop(0)
        color = COLORS[tid % len(COLORS)]
        pts = np.array(track, dtype=np.int32).reshape((-1, 1, 2))
        cv2.polylines(arr, [pts], False, color, 2)
        print(f"  Track {tid}: {label} center=({cx},{cy})", flush=True)

    proc.stdin.write(arr.tobytes())

pipeline.set_state(Gst.State.NULL)
if proc:
    proc.stdin.close()
    proc.wait()
print("Wrote output_dlstreamer.mp4", flush=True)