Repository navigation
Expand file tree
/
Copy pathmain.py
More file actions
299 lines (252 loc) · 13.6 KB
/
Copy pathmain.py
File metadata and controls
299 lines (252 loc) · 13.6 KB
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
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
# Object detection and tracking
# YOLOv8 finds the objects in each frame and SORT (sort.py) gives every object an id that stays the same.
# Extras: presets (fast / balanced / accurate), a line counter (people or cars crossing a line) and a report.
import argparse
import colorsys
import csv
import json
import os
import time
from collections import Counter, defaultdict
import cv2
import numpy as np
from sort import Sort
FONT = cv2.FONT_HERSHEY_SIMPLEX
WINDOW = "Object Detection and Tracking (YOLO + SORT)"
# fast = for a normal laptop, accurate = slower but finds more (smaller / farther) objects
PRESETS = {
"fast": dict(model="yolov8n.pt", imgsz=480, size=800, detect_every=3),
"balanced": dict(model="yolov8s.pt", imgsz=640, size=960, detect_every=2),
"accurate": dict(model="yolov8m.pt", imgsz=960, size=1280, detect_every=1),
}
def get_color(track_id):
# different bright colour for every id
r, g, b = colorsys.hsv_to_rgb((track_id * 0.618033988749895) % 1.0, 0.75, 1.0)
return int(b * 255), int(g * 255), int(r * 255)
def draw_box(frame, box, track_id, name, conf, color, trail, scale):
x1, y1, x2, y2 = map(int, box)
# path of the object
for i in range(1, len(trail)):
thickness = max(1, int(2.5 * scale * i / len(trail)))
cv2.line(frame, trail[i - 1], trail[i], color, thickness, cv2.LINE_AA)
# box with thick corners
cv2.rectangle(frame, (x1, y1), (x2, y2), color, 1, cv2.LINE_AA)
length = max(6, min(x2 - x1, y2 - y1) // 5)
t = max(2, int(2.5 * scale))
for px, py, dx, dy in [(x1, y1, 1, 1), (x2, y1, -1, 1), (x1, y2, 1, -1), (x2, y2, -1, -1)]:
cv2.line(frame, (px, py), (px + dx * length, py), color, t, cv2.LINE_AA)
cv2.line(frame, (px, py), (px, py + dy * length), color, t, cv2.LINE_AA)
# label above the box (below it if there is no space)
label = f"{name} #{track_id} {conf:.0%}"
font_size = 0.45 * scale
(tw, th), _ = cv2.getTextSize(label, FONT, font_size, 1)
pad = int(4 * scale)
ty = y1 - pad - 2 if y1 - th - 2 * pad - 2 > 0 else y1 + th + 2 * pad
cv2.rectangle(frame, (x1, ty - th - pad), (x1 + tw + 2 * pad, ty + pad), color, -1)
cv2.putText(frame, label, (x1 + pad, ty), FONT, font_size, (20, 20, 20), 1, cv2.LINE_AA)
def draw_info(frame, fps, in_frame, counts, line_counts, scale):
# small panel in the top left corner
total = sum(len(ids) for ids in counts.values())
lines = [f"FPS {fps:.1f}", f"In frame {in_frame}", f"Total tracked {total}"]
if line_counts is not None:
lines.append(f"Line in {sum(line_counts['in'].values())} out {sum(line_counts['out'].values())}")
top = sorted(counts.items(), key=lambda kv: -len(kv[1]))[:4]
lines += [f" {name}: {len(ids)}" for name, ids in top]
line_h = int(20 * scale)
font_size = 0.45 * scale
w = int(max(cv2.getTextSize(t, FONT, font_size, 1)[0][0] for t in lines) + 24 * scale)
h = line_h * len(lines) + int(14 * scale)
overlay = frame.copy()
cv2.rectangle(overlay, (8, 8), (8 + w, 8 + h), (25, 20, 15), -1)
cv2.addWeighted(overlay, 0.6, frame, 0.4, 0, frame)
for i, text in enumerate(lines):
y = 8 + int(8 * scale) + line_h * (i + 1) - int(4 * scale)
color = (255, 255, 255) if i < 3 + (line_counts is not None) else (210, 210, 210)
cv2.putText(frame, text, (8 + int(10 * scale), y), FONT, font_size, color, 1, cv2.LINE_AA)
def side(p, a, b):
# > 0 on one side of the line a-b, < 0 on the other side
return (b[0] - a[0]) * (p[1] - a[1]) - (b[1] - a[1]) * (p[0] - a[0])
def crossed_line(prev, cur, a, b):
"""1 or -1 if the move prev -> cur crosses the line segment a-b (the sign is the direction), else 0."""
# a point exactly on the line counts as the negative side, so a crossing is never missed
s1, s2 = side(prev, a, b) > 0, side(cur, a, b) > 0
if s1 == s2:
return 0 # still on the same side
if (side(a, prev, cur) > 0) == (side(b, prev, cur) > 0):
return 0 # crossed the extended line, but not between the two ends
return 1 if s2 else -1
def get_args():
p = argparse.ArgumentParser(description="Object detection and tracking with YOLO + SORT")
p.add_argument("--source", default="0", help="0 for webcam or path of a video file")
p.add_argument("--preset", choices=list(PRESETS), default="fast", help="fast (default), balanced or accurate")
p.add_argument("--model", default=None, help="YOLO weights, downloaded automatically (default depends on the preset)")
p.add_argument("--conf", type=float, default=0.35, help="confidence threshold")
p.add_argument("--classes", nargs="*", help="only these classes, e.g. --classes person car")
p.add_argument("--line", default=None, help='counting line as fractions of the frame: "x1,y1,x2,y2", e.g. "0,0.6,1,0.6" = horizontal line at 60%% of the height')
p.add_argument("--output", default="output/result.mp4", help="where to save the video (the report is saved next to it)")
p.add_argument("--no-save", action="store_true", help="don't save the video")
p.add_argument("--no-report", action="store_true", help="don't save tracks.csv and summary.json")
p.add_argument("--no-show", action="store_true", help="don't open the preview window")
p.add_argument("--size", type=int, default=None, help="longest side of the frame in pixels, 0 = original size")
p.add_argument("--imgsz", type=int, default=None, help="YOLO input size (bigger = finds smaller objects, but slower)")
p.add_argument("--detect-every", type=int, default=None, help="run YOLO on every Nth frame, the tracker fills the rest")
p.add_argument("--skip", type=int, default=0, help="frames to drop completely")
p.add_argument("--max-age", type=int, default=30, help="frames to keep a lost track")
p.add_argument("--min-hits", type=int, default=3, help="detections needed before showing a track")
p.add_argument("--iou", type=float, default=0.3, help="IoU threshold for matching")
args = p.parse_args()
for key, value in PRESETS[args.preset].items(): # the preset fills everything that was not set by hand
if getattr(args, key) is None:
setattr(args, key, value)
return args
def main():
args = get_args()
from ultralytics import YOLO
model = YOLO(args.model)
names = model.names
wanted = None
if args.classes:
wanted = {i for i, n in names.items() if n in args.classes}
if not wanted:
raise SystemExit("Wrong class names. Available: " + ", ".join(names.values()))
source = int(args.source) if args.source.isdigit() else args.source
cap = cv2.VideoCapture(source)
if not cap.isOpened():
raise SystemExit(f"Could not open video: {args.source}")
width = int(cap.get(cv2.CAP_PROP_FRAME_WIDTH))
height = int(cap.get(cv2.CAP_PROP_FRAME_HEIGHT))
src_fps = cap.get(cv2.CAP_PROP_FPS) or 30.0
# shrink big videos so they fit on the screen and run faster
resize = min(1.0, args.size / max(width, height)) if args.size > 0 else 1.0
width = int(width * resize) // 2 * 2
height = int(height * resize) // 2 * 2
line_pts = None
if args.line:
try:
x1, y1, x2, y2 = [float(v) for v in args.line.split(",")]
except ValueError:
raise SystemExit('--line needs 4 numbers like "0,0.6,1,0.6"')
line_pts = ((int(x1 * width), int(y1 * height)), (int(x2 * width), int(y2 * height)))
out_dir = os.path.dirname(args.output) or "."
writer = None
if not args.no_save:
os.makedirs(out_dir, exist_ok=True)
fourcc = cv2.VideoWriter_fourcc(*"mp4v")
writer = cv2.VideoWriter(args.output, fourcc, src_fps / (args.skip + 1), (width, height))
ui = min(1.4, max(0.6, max(width, height) / 1100)) # text size depends on the frame size
tracker = Sort(max(3, args.max_age // args.detect_every), args.min_hits, args.iou)
counts = defaultdict(set) # class name -> ids seen so far
info = {} # id -> class, first frame, last frame, line crossing
last_pos = {} # id -> last position, used for the line counter
counted = set() # ids that already crossed the line (every object is counted once)
line_counts = {"in": Counter(), "out": Counter()} if line_pts else None
total_frames = int(cap.get(cv2.CAP_PROP_FRAME_COUNT) or 0) // (args.skip + 1)
frame_no = 0
done = 0
fps = 0.0
paused = False
last = started = time.time()
if not args.no_show:
cv2.namedWindow(WINDOW, cv2.WINDOW_NORMAL)
cv2.resizeWindow(WINDOW, width, height)
print(f"Running with preset '{args.preset}' ({args.model}, imgsz {args.imgsz}, YOLO on every {args.detect_every}. frame).")
print("Press Q or Esc to quit, P to pause.")
while True:
if not paused:
start = time.time()
for _ in range(args.skip):
cap.grab()
ok, frame = cap.read()
if not ok:
break
if resize < 1.0:
frame = cv2.resize(frame, (width, height), interpolation=cv2.INTER_AREA)
if frame_no % args.detect_every == 0:
# detection frame
result = model(frame, conf=args.conf, imgsz=args.imgsz, verbose=False)[0]
boxes = result.boxes.xyxy.cpu().numpy()
classes = result.boxes.cls.cpu().numpy().astype(int)
confs = result.boxes.conf.cpu().numpy()
if wanted is not None:
keep = np.array([c in wanted for c in classes], dtype=bool)
boxes, classes, confs = boxes[keep], classes[keep], confs[keep]
tracks = tracker.update(boxes, classes, confs)
else:
# no detection, just move the tracks
tracks = tracker.coast()
frame_no += 1
if line_pts:
cv2.line(frame, line_pts[0], line_pts[1], (0, 220, 255), max(2, int(2 * ui)), cv2.LINE_AA)
for x1, y1, x2, y2, track_id, cls, conf in tracks:
track_id, cls = int(track_id), int(cls)
name = names[cls]
counts[name].add(track_id)
record = info.setdefault(track_id, {"class": name, "first": frame_no, "last": frame_no, "crossed": ""})
record["last"] = frame_no
pos = (int((x1 + x2) / 2), int(y2)) # bottom centre = where the object stands
if line_pts and track_id in last_pos and track_id not in counted:
direction = crossed_line(last_pos[track_id], pos, *line_pts)
if direction:
counted.add(track_id)
key = "in" if direction > 0 else "out"
line_counts[key][name] += 1
record["crossed"] = key
last_pos[track_id] = pos
draw_box(frame, (x1, y1, x2, y2), track_id, name, conf,
get_color(track_id), tracker.get_trail(track_id), ui)
now = time.time()
current = 1 / max(now - last, 1e-6)
fps = 0.9 * fps + 0.1 * current if fps else current
last = now
draw_info(frame, fps, len(tracks), counts, line_counts, ui)
if writer:
writer.write(frame)
done += 1
if done % 25 == 0:
total = f" / ~{total_frames}" if total_frames > 0 else ""
eta = ""
if total_frames > done:
left = (total_frames - done) / (done / (time.time() - started))
eta = f", about {int(left)} s left" if left < 90 else f", about {int(left / 60) + 1} min left"
print(f"Processed {done}{total} frames ({fps:.1f} FPS{eta})", flush=True)
if not args.no_show:
cv2.imshow(WINDOW, frame)
# try to play at the speed of the original video
wait = int(1000 * (args.skip + 1) / src_fps - (time.time() - start) * 1000)
key = cv2.waitKey(max(1, wait)) & 0xFF
if key in (ord("q"), 27):
break
if key == ord("p"):
paused = not paused
cap.release()
if writer:
writer.release()
print("Saved:", args.output)
if not args.no_show:
cv2.destroyAllWindows()
unique = {name: len(ids) for name, ids in counts.items()}
print("Unique objects tracked:", unique)
if line_counts:
print("Line counter: in", dict(line_counts["in"]), "| out", dict(line_counts["out"]))
if not args.no_report and done:
os.makedirs(out_dir, exist_ok=True)
seconds_per_frame = (args.skip + 1) / src_fps
with open(os.path.join(out_dir, "tracks.csv"), "w", newline="") as f:
w = csv.writer(f)
w.writerow(["id", "class", "first_frame", "last_frame", "seconds_visible", "crossed_line"])
for track_id, r in sorted(info.items()):
w.writerow([track_id, r["class"], r["first"], r["last"],
round((r["last"] - r["first"] + 1) * seconds_per_frame, 1), r["crossed"]])
summary = {
"source": args.source, "preset": args.preset, "model": args.model,
"frames_processed": done, "average_fps": round(done / (time.time() - started), 1),
"unique_objects": unique, "unique_total": sum(unique.values()),
}
if line_counts:
summary["line_in"] = dict(line_counts["in"])
summary["line_out"] = dict(line_counts["out"])
with open(os.path.join(out_dir, "summary.json"), "w") as f:
json.dump(summary, f, indent=2)
print(f"Report saved: {out_dir}/tracks.csv and {out_dir}/summary.json")
if __name__ == "__main__":
main()