"""Q-23: Read a video frame by frame and save every tenth frame -- Data-Driven Athletics tutorial.

Web page: https://apopt.com/course/tutorials/q23-video-frames/
Data:     https://apopt.com/data/tutorials/q23-video-frames/ (keep raw/ next to this file)
"""

# %% [markdown]
# A video is a stack of pictures and a clock (Chapter 8, "A Video Is a Table"). Every analysis
# of a clip, by an app or by you, is the same loop: read a frame, do something with it, write
# one row, read the next. Here the "something" is small: save every tenth frame as a picture
# and measure two numbers from each frame. The clip is the short running clip from the
# Data-Driven Engineering course.
#
# The first two cells need OpenCV (`cv2`), so they run in a notebook on your computer or in
# Colab. The saved pictures show a person, so they go into `local/`, which stays on your
# computer. Only the table is published.

# %%
# Read the clip's header
import cv2

cap = cv2.VideoCapture("runner.mp4")
fps = cap.get(cv2.CAP_PROP_FPS)
n = int(cap.get(cv2.CAP_PROP_FRAME_COUNT))
w, h = int(cap.get(cv2.CAP_PROP_FRAME_WIDTH)), int(cap.get(cv2.CAP_PROP_FRAME_HEIGHT))
print(f"{n} frames at {fps:.0f} fps = {n / fps:.2f} s, {w} x {h} pixels")
print(f"one frame lasts {1000 / fps:.1f} ms")
cap.release()

# %%
# The frame loop: save every tenth, measure every one
import os
import numpy as np
import pandas as pd

os.makedirs("local/frames", exist_ok=True)
os.makedirs("clean", exist_ok=True)
cap = cv2.VideoCapture("runner.mp4")
rows, prev, i = [], None, 0
while True:
    ok, frame = cap.read()
    if not ok:
        break
    gray = cv2.cvtColor(frame, cv2.COLOR_BGR2GRAY).astype(float)
    change = np.nan if prev is None else np.abs(gray - prev).mean()   # how much the picture moved
    saved = i % 10 == 0
    if saved:
        cv2.imwrite(f"local/frames/frame_{i:03d}.jpg", frame)
    rows.append([i, round(i / fps, 3), round(gray.mean(), 1), round(change, 2), saved])
    prev, i = gray, i + 1
cap.release()
table = pd.DataFrame(rows, columns=["frame", "t_s", "brightness", "change", "saved"])
table.to_csv("clean/frames.csv", index=False)
print(f"read {i} frames, saved {table['saved'].sum()} to local/frames/")
print(table.to_string(index=False))

# %% [markdown]
# Three columns came from the clock and the counter: `frame`, `t_s` (frame divided by the
# frame rate) and `saved`. Two came from the pixels: `brightness`, the mean gray level from 0
# (black) to 255 (white), and `change`, the mean difference in gray level from the frame
# before. Open `local/frames/` on your computer to see the three saved pictures.
#
# ### Plot the table
#
# From here on, everything runs in this page, from the published table.

# %%
# What changed from frame to frame
import pandas as pd
import matplotlib.pyplot as plt

t = pd.read_csv("clean/frames.csv")
print(f"{len(t)} rows; time step {t['t_s'].diff().median() * 1000:.1f} ms; saved frames: {t.loc[t['saved'], 'frame'].tolist()}")
print(f"change per frame: median {t['change'].median():.2f}, largest {t['change'].max():.2f} at frame {int(t.loc[t['change'].idxmax(), 'frame'])}")

fig, ax = plt.subplots(figsize=(6.4, 3.2))
ax.plot(t["t_s"], t["change"], "o-", ms=4, label="change from previous frame")
for k, ts in enumerate(t.loc[t["saved"], "t_s"]):
    ax.axvline(ts, color="black", ls="--", lw=1, label="saved frame" if k == 0 else None)
ax.set(xlim=(-0.03, 0.73), xlabel="time (s)", ylabel="mean change (gray levels)")
ax.legend()
plt.tight_layout()

# %% [markdown]
# The clock checks out: 22 rows, one every 33 ms, and frames 0, 10 and 20 saved, as you
# predicted if you counted from zero. The pixels say something the header does not. The mean
# change is about 28 gray levels **every frame** (median 28.38), and it falls slowly through
# the clip while the brightness rises. A still camera filming one runner would change only
# where the runner is, a small part of the picture. Here nearly every pixel changes, because
# the camera turns to follow the runner as he runs away from it, and more sky and snow come
# into view. Look at the three saved frames: the stands swing from behind the runner to the
# right edge. A moving camera means no fixed scale and no fixed background, which is why
# Chapter 8's filming advice starts with a still camera.
#
# **For the athlete:** put the phone on something solid and let the runner cross the frame;
# don't follow them with the camera.
