193 lines
8.4 KiB
Python
193 lines
8.4 KiB
Python
import datetime
|
|
import json
|
|
import os
|
|
|
|
import cv2
|
|
import diskcache
|
|
import pandas as pd
|
|
import pytz
|
|
import tqdm
|
|
from pymediainfo import MediaInfo
|
|
from timezonefinder import TimezoneFinder
|
|
from astral import LocationInfo
|
|
from astral.sun import sun
|
|
|
|
CACHE = diskcache.Cache("analyzer_cache3")
|
|
|
|
tf = TimezoneFinder()
|
|
|
|
def get_daytime(lat: float, lon: float, dt: datetime.datetime):
|
|
tz_name = tf.timezone_at(lat=lat, lng=lon)
|
|
if tz_name is None:
|
|
raise ValueError("No timezone found")
|
|
dt = pytz.timezone(tz_name).localize(dt)
|
|
location = LocationInfo(latitude=lat, longitude=lon, timezone=tz_name)
|
|
s = sun(location.observer, date=dt.date(), tzinfo=location.timezone)
|
|
|
|
dawn = s['dawn']
|
|
sunrise = s['sunrise']
|
|
sunset = s['sunset']
|
|
dusk = s['dusk']
|
|
if dawn <= dt < sunrise:
|
|
return "Dawn"
|
|
elif sunrise <= dt < sunset:
|
|
return "Day"
|
|
elif sunset <= dt < dusk:
|
|
return "Dusk"
|
|
else:
|
|
return "Night"
|
|
|
|
|
|
def get_video_info(video):
|
|
media_info: MediaInfo = CACHE.get(f"mediainfo_{video}", None)
|
|
if not media_info:
|
|
media_info = MediaInfo.parse(video)
|
|
CACHE[f"mediainfo_{video}"] = media_info
|
|
|
|
camera_info_path = os.path.join(os.path.dirname(os.path.dirname(video)), "camera_info.txt")
|
|
camera_info = dict()
|
|
if os.path.exists(camera_info_path):
|
|
with open(camera_info_path, "r") as f:
|
|
camera_info = f.read()
|
|
camera_info = camera_info.replace("'", '"').replace('""', 'null').replace("True", "true").replace("False", "false")
|
|
camera_info = camera_info[camera_info.find("{"):camera_info.rfind("}")+1]
|
|
if "datetime.datetime" in camera_info:
|
|
start = camera_info.find("datetime.datetime(")
|
|
end = camera_info.find(")", start)
|
|
camera_info = camera_info[:end] + '"' + camera_info[end + 1:]
|
|
camera_info = camera_info.replace("datetime.datetime(", '"')
|
|
camera_info = json.loads(camera_info)
|
|
duration = float(max([t.duration for t in media_info.tracks])) / 1000.0 # seconds
|
|
bitrate = int(max([t.bit_rate for t in media_info.tracks if t.bit_rate is not None])) # b/s
|
|
resolution = [(t.width, t.height) for t in media_info.video_tracks]
|
|
if len(resolution) != 1:
|
|
raise ValueError()
|
|
resolution = resolution[0] # (w, h)
|
|
basename = os.path.basename(video)
|
|
date = datetime.datetime(int(basename[0:4]), int(basename[4:6]),
|
|
int(basename[6:8]), int(basename[8:10]),
|
|
int(basename[10:12]),int(basename[12:14]))
|
|
fps = float(max([t.frame_rate for t in media_info.video_tracks]))
|
|
cap = cv2.VideoCapture(video)
|
|
frame_count = int(cap.get(cv2.CAP_PROP_FRAME_COUNT))
|
|
cap.release()
|
|
return {"filename": video, "camera_info": camera_info, "length": duration,
|
|
"bitrate": bitrate, "resolution": resolution, "time": date, "fps": fps, "frames": frame_count}
|
|
|
|
|
|
def analyze_static_information():
|
|
cameras = [os.path.join("recordings", city, cam) for city in os.listdir("recordings") for cam in
|
|
os.listdir(os.path.join("recordings", city)) if city != "Las Vegas"]
|
|
days = [os.path.join(camera, day) for camera in cameras for day in os.listdir(camera)]
|
|
days = [day for day in days if os.path.isdir(day)]
|
|
videos = [os.path.join(day, video) for day in days for video in os.listdir(day)]
|
|
infos = []
|
|
for video in tqdm.tqdm(videos, desc="creating mediainfo of videos"):
|
|
info = CACHE.get(f"info_{video}", None)
|
|
if not info:
|
|
info = get_video_info(video)
|
|
CACHE.set(f"info_{video}", info)
|
|
infos.append(info)
|
|
os.makedirs("metadata", exist_ok=True)
|
|
with open(os.path.join("metadata", "video_info.csv"), "w") as f:
|
|
f.write("filename;duration;bitrate;resolution;time;fps;frames\n")
|
|
for info in infos:
|
|
f.write(f"{info["filename"]};{info["length"]};{info["bitrate"]};"
|
|
f"{info["resolution"][0]}x{info["resolution"][1]};{info["time"]};{info["fps"]};{info["frames"]}\n")
|
|
os.makedirs(os.path.join("metadata", "resolution"), exist_ok=True)
|
|
resolutions = set([i["resolution"] for i in infos])
|
|
for r in resolutions:
|
|
videos = [i["filename"] for i in infos if i["resolution"] == r]
|
|
with open(os.path.join("metadata", "resolution", f"{r[0]}x{r[1]}.txt"), "w") as f:
|
|
for video in videos:
|
|
f.write(f"{video}\n")
|
|
fps_groups = dict()
|
|
fps_groups["30"] = [i["filename"] for i in infos if int(round(i["fps"], 0)) == 30]
|
|
fps_groups["24"] = [i["filename"] for i in infos if int(round(i["fps"], 0)) == 24]
|
|
fps_groups["15"] = [i["filename"] for i in infos if int(round(i["fps"], 0)) == 15]
|
|
fps_groups["low"] = [i["filename"] for i in infos if int(round(i["fps"], 0)) < 15]
|
|
fps_groups["high"] = [i["filename"] for i in infos if int(round(i["fps"], 0)) > 30]
|
|
grouped_videos = set(fps_groups["30"]) | set(fps_groups["24"]) | set(fps_groups["15"]) | set(fps_groups["low"]) | set(fps_groups["high"])
|
|
fps_groups["medium"] = [i["filename"] for i in infos if i["filename"] not in grouped_videos]
|
|
os.makedirs(os.path.join("metadata", "fps"), exist_ok=True)
|
|
for fg in fps_groups.keys():
|
|
with open(os.path.join("metadata", "fps", f"{fg}.txt"), "w") as f:
|
|
for video in fps_groups[fg]:
|
|
f.write(f"{video}\n")
|
|
|
|
bitrates = [(i["filename"], int(i["bitrate"])) for i in infos]
|
|
df = pd.DataFrame(bitrates, columns=["filename", "bitrate"])
|
|
df["quartil"] = pd.qcut(df["bitrate"], q=4, labels=["Q1", "Q2", "Q3", "Q4"])
|
|
bitrate_groups = {group: list(videos["filename"])
|
|
for group, videos in df.groupby("quartil", observed=False)}
|
|
os.makedirs(os.path.join("metadata", "bitrate"), exist_ok=True)
|
|
for key in bitrate_groups:
|
|
with open(os.path.join("metadata", "bitrate", f"{key}.txt"), "w") as f:
|
|
for video in bitrate_groups[key]:
|
|
f.write(f"{video}\n")
|
|
duration_groups = dict()
|
|
duration_groups["short"] = [i["filename"] for i in infos if i["length"] < 300]
|
|
duration_groups["medium"] = [i["filename"] for i in infos if 300 <= i["length"] <= 600]
|
|
duration_groups["long"] = [i["filename"] for i in infos if int(round(i["fps"], 0)) > 600]
|
|
os.makedirs(os.path.join("metadata", "duration"), exist_ok=True)
|
|
for d in duration_groups.keys():
|
|
with open(os.path.join("metadata", "duration", f"{d}.txt"), "w") as f:
|
|
for video in duration_groups[d]:
|
|
f.write(f"{video}\n")
|
|
|
|
frame_counts = [(i["filename"], int(i["frames"])) for i in infos]
|
|
df = pd.DataFrame(frame_counts, columns=["filename", "frames"])
|
|
df["quartil"] = pd.qcut(df["frames"], q=4, labels=["Q1", "Q2", "Q3", "Q4"])
|
|
frame_groups = {group: list(videos["filename"])
|
|
for group, videos in df.groupby("quartil", observed=False)}
|
|
os.makedirs(os.path.join("metadata", "frame_count"), exist_ok=True)
|
|
for key in frame_groups:
|
|
with open(os.path.join("metadata", "frame_count", f"{key}.txt"), "w") as f:
|
|
for video in frame_groups[key]:
|
|
f.write(f"{video}\n")
|
|
|
|
daytime_groups = dict()
|
|
for info in infos:
|
|
filename = info["filename"]
|
|
time = info["time"]
|
|
camera_info = info["camera_info"]
|
|
if len(camera_info) == 0:
|
|
continue
|
|
lat = camera_info["latitude"]
|
|
lon = camera_info["longitude"]
|
|
daytime = get_daytime(lat, lon, time)
|
|
if daytime not in daytime_groups.keys():
|
|
daytime_groups[daytime] = []
|
|
daytime_groups[daytime].append(filename)
|
|
os.makedirs(os.path.join("metadata", "times"), exist_ok=True)
|
|
times = daytime_groups.keys()
|
|
for t in times:
|
|
videos = daytime_groups[t]
|
|
with open(os.path.join("metadata", "times", f"{t}.txt"), "w") as f:
|
|
for video in videos:
|
|
f.write(f"{video}\n")
|
|
|
|
# count = dict()
|
|
# for b in bitrate:
|
|
# count[str(b)] = count.get(str(b), 0) + 1
|
|
# values = [(i[0], i[1]) for i in count.items()]
|
|
# values = sorted(values, key=lambda x: x[1], reverse=True)
|
|
# print(values)
|
|
# keys = infos[0].keys()
|
|
# keys -= {"camera_info"}
|
|
# for k in keys:
|
|
# distinct = set([i[k] for i in infos])
|
|
# print(f"{k}: {len(distinct)}")
|
|
|
|
|
|
def analyze_car_density():
|
|
pass # TODO
|
|
|
|
|
|
def main():
|
|
analyze_static_information()
|
|
analyze_car_density()
|
|
|
|
|
|
if __name__ == "__main__":
|
|
main() |