Spaces:
Sleeping
Sleeping
File size: 2,621 Bytes
29088fd | 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 | """
Run the engine on images or a video from the command line.
python tools/run_engine.py path/to/img_or_dir_or_video --out tmp/out [--scene configs/scenes/x.json]
"""
from __future__ import annotations
import argparse
import json
import sys
import time
from pathlib import Path
import cv2
ROOT = Path(__file__).resolve().parent.parent
sys.path.insert(0, str(ROOT))
from core.detection_engine import EngineConfig, TrafficEnforcementEngine # noqa: E402
from core.scene import SceneConfig # noqa: E402
IMAGE_EXT = {".jpg", ".jpeg", ".png", ".bmp", ".webp"}
def main() -> None:
ap = argparse.ArgumentParser()
ap.add_argument("source")
ap.add_argument("--out", default=str(ROOT / "tmp" / "engine_out"))
ap.add_argument("--scene", default=None)
ap.add_argument("--limit", type=int, default=0)
ap.add_argument("--all-plates", action="store_true")
args = ap.parse_args()
scene = SceneConfig.from_json(Path(args.scene).read_text()) if args.scene else SceneConfig()
engine = TrafficEnforcementEngine(EngineConfig(read_all_plates=args.all_plates))
out = Path(args.out)
out.mkdir(parents=True, exist_ok=True)
src = Path(args.source)
if src.is_dir() or src.suffix.lower() in IMAGE_EXT:
files = sorted(p for p in (src.iterdir() if src.is_dir() else [src]) if p.suffix.lower() in IMAGE_EXT)
if args.limit:
files = files[: args.limit]
for f in files:
img = cv2.imread(str(f))
t0 = time.time()
res, incidents = engine.process_image(img, scene)
cv2.imwrite(str(out / (f.stem + ".jpg")), res.annotated)
print(f.name, f"{(time.time() - t0) * 1000:.0f}ms", res.counts,
json.dumps([i.summary() for i in incidents]))
return
cap = cv2.VideoCapture(str(src))
fps = cap.get(cv2.CAP_PROP_FPS) or 25
ok, frame = cap.read()
engine.reset(scene, fps=fps, frame_shape=frame.shape)
writer = cv2.VideoWriter(str(out / (src.stem + "_annotated.mp4")), cv2.VideoWriter_fourcc(*"mp4v"), fps,
(frame.shape[1], frame.shape[0]))
n = 0
while ok:
res = engine.process_frame(frame, timestamp=n / fps)
writer.write(res.annotated)
for e in res.new_violations:
print(f"t={e['time_s']}s", e["type"], "track", e["track_id"], e["reason"])
n += 1
if args.limit and n >= args.limit:
break
ok, frame = cap.read()
writer.release()
for inc in engine.finalize_all():
print(json.dumps(inc.summary()))
if __name__ == "__main__":
main()
|