Files
2025-08-13 08:51:37 +02:00

226 lines
8.0 KiB
Python

import datetime
import os
import pandas as pd
import cv2
import diskcache
import psutil
from matplotlib import pyplot as plt
import matplotlib.dates as mdates
from tqdm import tqdm
from detection import YoloDetector
CACHE = diskcache.Cache("evaluation_cache")
DETECTOR = YoloDetector()
DEBUG_MODE = False
SCALE = 1
sample_interval_sec = 120.0
plt.rcParams.update({
'font.size': 14, # Basisgröße
'axes.titlesize': 16, # Titel
'axes.labelsize': 16, # Achsenbeschriftungen
'xtick.labelsize': 14, # X-Achsen-Beschriftungen
'ytick.labelsize': 14, # Y-Achsen-Beschriftungen
'legend.fontsize': 14, # Legende
# 'text.usetex': True,
'font.family': 'serif'
})
def count_cars(frame):
if SCALE != 1:
frame = cv2.resize(frame, (0, 0), fx=SCALE, fy=SCALE)
cars_list = DETECTOR.detect(frame)
if DEBUG_MODE:
img = frame.copy()
centers = [((x1 + x2) // 2, (y1 + y2) // 2) for (x1, y1, x2, y2) in cars_list]
for cx, cy in centers:
cv2.circle(img, (cx, cy), 3, (255, 0, 0), -1)
cv2.imshow('Detected Cars', img)
cv2.waitKey(1)
return len(cars_list)
def clear_crashed_process(key):
count = 0
for pid in psutil.pids():
try:
p = psutil.Process(pid)
if "python" in p.name().lower():
cmd = p.cmdline()
script = cmd[1]
if script.endswith(os.path.basename(__file__)):
count += 1
except psutil.NoSuchProcess:
pass
if count > 1:
return
if key in CACHE:
print(f"no other processes are running, clearing {key}")
CACHE.pop(key, None)
def evaluate_camera(city, camera, camera_name, videos):
print(city, camera)
filename = os.path.join("results", city, f"{camera}_graph.png")
if os.path.isfile(filename):
return
videos_per_day = dict()
for video in videos:
day = os.path.basename(os.path.dirname(video))
videos_day = videos_per_day.get(day, [])
videos_day = list(videos_day)
videos_day.append(video)
videos_per_day[day] = sorted(videos_day)
for day in videos_per_day.keys():
if f"{city}/{camera}/{day}" not in CACHE or len(CACHE[f"{city}/{camera}/{day}"]) == 0:
clear_crashed_process(f"{city}/{camera}/{day}")
for day in videos_per_day.keys():
if f"{city}/{camera}/{day}" in CACHE:
continue
CACHE[f"{city}/{camera}/{day}"] = []
videos = sorted(videos_per_day[day])
car_timeline = []
for video in videos:
name = os.path.basename(video)
date = datetime.datetime(int(name[0:4]), int(name[4:6]), int(name[6:8]), int(name[8:10]), int(name[10:12]),
int(name[12:14]))
cap = cv2.VideoCapture(video)
length = int(cap.get(cv2.CAP_PROP_FRAME_COUNT))
fps = cap.get(cv2.CAP_PROP_FPS)
if fps == 0 or fps is None:
raise IOError(f"Could not get fps from video {video}")
if not cap.isOpened():
raise IOError("Error opening video stream or file")
if length > 0:
pbar = tqdm(total=length, desc=f"Processing {camera}, recorded on {date}")
else:
pbar = tqdm(desc=f"Processing {camera}, recorded on {date}")
frame_count = 0
video_timeline = []
last_sample_time = None
while cap.isOpened():
ret, frame = cap.read()
if not ret:
break
ms = cap.get(cv2.CAP_PROP_POS_MSEC)
if ms < 0:
raise IOError("Error reading frame timestamp")
frame_timestamp = date + datetime.timedelta(milliseconds=ms)
if (last_sample_time is None) or (
(frame_timestamp - last_sample_time).total_seconds() >= sample_interval_sec):
cars = count_cars(frame)
video_timeline.append((frame_timestamp, cars))
last_sample_time = frame_timestamp
pbar.update(1)
frame_count += 1
cap.release()
car_timeline.extend(video_timeline)
CACHE[f"{city}/{camera}/{day}"] = car_timeline
data = dict()
for day in videos_per_day.keys():
if f"{city}/{camera}/{day}" not in CACHE or len(CACHE[f"{city}/{camera}/{day}"]) == 0:
return
data[day] = CACHE[f"{city}/{camera}/{day}"]
all_values = [item for values in data.values() for item in values]
df = pd.DataFrame(all_values, columns=["datetime", "value"])
print(df)
df["time_slot"] = df["datetime"].apply(round_datetime)
agg_df = df.groupby("time_slot").agg(
min_val=("value", "min"),
mean_val=("value", "mean"),
max_val=("value", "max"),
std_val=("value", "std"),
)
full_slots = [datetime.time(h, m) for h in range(24) for m in [0]] # , 30)]
agg_df = agg_df.reindex(full_slots)
agg_df = agg_df.fillna(0)
print(agg_df)
time_index = [datetime.datetime.combine(datetime.date(1900, 1, 1), t) for t in agg_df.index]
plt.figure(figsize=(12, 6))
mean = agg_df["mean_val"]
std = agg_df["std_val"]
plt.plot(time_index, mean, label="avg", color="blue")
# plt.plot(time_index, agg_df["min_val"], label="min", color="green", linestyle="--")
plt.plot(time_index, agg_df["max_val"], label="max", color="red", linestyle="--")
plt.fill_between(time_index, mean - std, mean + std, color="blue", alpha=0.2, label=r"$\sigma$")
plt.gca().xaxis.set_major_formatter(mdates.DateFormatter("%H"))
plt.xlim(time_index[0], time_index[-1])
# Layout
plt.xlabel("Hour")
plt.ylabel("Cars")
plt.title(f"Cars counted at {camera_name}")
plt.legend(
loc="upper left",
bbox_to_anchor=(1.02, 1)
)
plt.grid(True)
plt.tight_layout()
filename = os.path.join("results", city, f"{camera}_graph.png")
os.makedirs(os.path.dirname(filename), exist_ok=True)
plt.savefig(filename)
def round_datetime(dt):
return datetime.time(dt.hour, 0)
# minute = 0 if dt.minute < 30 else 30
# return datetime.time(dt.hour, minute)
def evaluate(city, camera, videos):
name = camera
camera_info = os.path.join("recordings", city, camera, 'camera_info.txt')
if os.path.isfile(camera_info):
with open(camera_info, 'r') as f:
camera_str = f.read()
start = camera_str.find("'", camera_str.find(':', camera_str.find('name'))) + 1
end = camera_str.find("'", start)
name = camera_str[start:end]
print("Evaluating", city, camera)
print(name)
evaluate_camera(city, camera, name, videos)
def main():
# if DEBUG_MODE:
# CACHE.clear()
all_cameras = {}
cities = os.listdir("recordings")
for city in cities:
all_cameras[city] = {}
cameras = os.listdir(os.path.join("recordings", city))
for camera in cameras:
days = [d for d in os.listdir(os.path.join("recordings", city, camera))
if os.path.isdir(os.path.join("recordings", city, camera, d))]
days = sorted(days)
videos = []
for day in days:
videos_of_day = sorted(os.listdir(os.path.join("recordings", city, camera, day)))
videos.extend([os.path.join("recordings", city, camera, day, f) for f in videos_of_day])
all_cameras[city][camera] = videos
cameras_to_analyze = [# ("San Francisco", "TV403 -- US-101 Just North of Lagoon Way"),
# ("San Francisco", "TV521 -- I-580 Cutting Blvd"),
# ("Sacramento", "Hwy 5 At Arena Blvd 2"),
# ("Sacramento", "Hwy 5 at Pocket"),
("Los Angeles", "I-405 336 Carson St"),
("Los Angeles", "I-10 81 Overland Ave On-Ramp")]
for city, camera in cameras_to_analyze:
evaluate(city, camera, all_cameras[city][camera])
if __name__ == "__main__":
main()