diff --git a/.github/workflows/build_release.yml b/.github/workflows/build_release.yml index ffbbadb..03f53b5 100644 --- a/.github/workflows/build_release.yml +++ b/.github/workflows/build_release.yml @@ -42,7 +42,7 @@ jobs: ls dist - name: Install the wheel - run: python -m pip install "$(ls dist/*.whl)" "pytest>=8" + run: python -m pip install "$(ls dist/*.whl)[all]" "pytest>=8" - name: Test the wheel outside the source tree run: | diff --git a/.github/workflows/test_package.yml b/.github/workflows/test_package.yml index 3795484..930e21f 100644 --- a/.github/workflows/test_package.yml +++ b/.github/workflows/test_package.yml @@ -34,8 +34,13 @@ jobs: python-version: ${{ matrix.python-version }} activate-environment: true + # Video tests that encode fixtures with ffmpeg skip without it; one OS is enough to run them + - name: Install ffmpeg + if: runner.os == 'Linux' + run: sudo apt-get update && sudo apt-get install -y ffmpeg + - name: Install - run: uv pip install . "pytest>=8" + run: uv pip install ".[all]" "pytest>=8" - name: Test the installed package run: pytest tests @@ -52,8 +57,11 @@ jobs: python-version: "3.10" activate-environment: true + - name: Install ffmpeg + run: sudo apt-get update && sudo apt-get install -y ffmpeg + - name: Install the lowest version each dependency declares - run: uv pip install --resolution lowest-direct . "pytest>=8" + run: uv pip install --resolution lowest-direct ".[video]" "pytest>=8" - name: Test run: pytest tests diff --git a/.github/workflows/weekly_checks.yml b/.github/workflows/weekly_checks.yml index 989d147..e708715 100644 --- a/.github/workflows/weekly_checks.yml +++ b/.github/workflows/weekly_checks.yml @@ -29,7 +29,7 @@ jobs: activate-environment: true - name: Install with pre-releases allowed - run: uv pip install --prerelease allow . "pytest>=8" + run: uv pip install --prerelease allow ".[all]" "pytest>=8" # `-o filterwarnings`, not `-W`: `-W` matches the module name exactly and would miss every submodule - name: Test diff --git a/dlccore/io/video.py b/dlccore/io/video.py new file mode 100644 index 0000000..39dcdf0 --- /dev/null +++ b/dlccore/io/video.py @@ -0,0 +1,226 @@ +# +# DeepLabCut Toolbox (deeplabcut.org) +# © A. & M.W. Mathis Labs +# https://github.com/DeepLabCut/dlccore +# +# Contributors: +# https://github.com/DeepLabCut/dlccore/graphs/contributors +# +# Licensed under GNU Lesser General Public License v3.0 +# + +"""Video frames through OpenCV, lifted from napari-deeplabcut's ``Video``: RGB ``uint8`` frames by index.""" + +from __future__ import annotations + +from collections.abc import Iterator +from pathlib import Path +from types import TracebackType + +import cv2 +import numpy as np + +_MAX_FORWARD_DECODE = 8 + + +class Video: + """Random access to a video's frames, keeping decoder state between reads. + + A forward jump of at most eight frames decodes forward instead of seeking, unless the previous read failed. Frames + are rotated by the video's rotation metadata, as video players show them, and ``width`` and ``height`` are those of + the rotated frames. + """ + + def __init__(self, video_path: str | Path) -> None: + """Open a video. + + Args: + video_path: The video file. + + Raises: + FileNotFoundError: If ``video_path`` is not a file. + OSError: If OpenCV cannot open it, or it has rotation metadata OpenCV cannot apply. + """ + + if not Path(video_path).is_file(): + raise FileNotFoundError(f'Video path "{video_path}" does not point to a file.') + + self._path = str(video_path) + self._stream = cv2.VideoCapture(self._path) + if not self._stream.isOpened(): + raise OSError(f"{self._path}: video could not be opened by OpenCV.") + # OpenCV 4.11.0 alone defaults to off; 4.10 and 4.12 onwards default to on + rotates = self._stream.set(cv2.CAP_PROP_ORIENTATION_AUTO, 1) + if not rotates and int(self._stream.get(cv2.CAP_PROP_ORIENTATION_META)) % 360 != 0: + self._stream.release() + raise OSError(f"{self._path}: OpenCV cannot rotate this video's frames by its rotation metadata.") + + self._n_frames = int(self._stream.get(cv2.CAP_PROP_FRAME_COUNT)) + self._width = int(self._stream.get(cv2.CAP_PROP_FRAME_WIDTH)) + self._height = int(self._stream.get(cv2.CAP_PROP_FRAME_HEIGHT)) + self._fps = float(self._stream.get(cv2.CAP_PROP_FPS)) + self._pos: int | None = 0 # next frame to read; None after a failure, until the next seek + + def __len__(self) -> int: + """Return the frame count the container reports. + + This uses the ``CAP_PROP_FRAME_COUNT`` estimate for some containers: frames past it cannot be + read by index, and reading a frame before it can still raise ``IndexError``. ``frames()`` reads to the + decoder's actual end. + """ + + return self._n_frames + + def __enter__(self) -> Video: + """Return this video, to close on leaving the block.""" + + return self + + def __exit__( + self, + exc_type: type[BaseException] | None, + exc: BaseException | None, + traceback: TracebackType | None, + ) -> None: + """Release the stream.""" + + self.close() + + @property + def width(self) -> int: + return self._width + + @property + def height(self) -> int: + return self._height + + @property + def fps(self) -> float: + """Frame rate the container reports.""" + + return self._fps + + def _seek(self, ind: int) -> None: + """Position the stream so the next read returns frame ``ind``, clamped to the video. + + Raises: + OSError: If OpenCV refuses the seek. + """ + + ind = max(0, min(ind, len(self) - 1)) + if ind != self._pos: + ok = self._stream.set(cv2.CAP_PROP_POS_FRAMES, ind) + if not ok: + self._pos = None + raise OSError(f"{self._path}: failed to seek to frame {ind}") + self._pos = ind + + def _known_position(self) -> int: + """Return the next frame to read; only called once a seek has set it.""" + + if self._pos is None: + raise RuntimeError(f"{self._path}: stream position unknown after a failed read; seek first.") + return self._pos + + def _read_next(self) -> np.ndarray: + """Decode the next frame as RGB. + + Raises: + IndexError: If no frame could be read. + """ + + position = self._known_position() + ok, frame = self._stream.read() + if not ok: + self._pos = None + raise IndexError(f"{self._path}: could not read frame {position}") + self._pos = position + 1 + return cv2.cvtColor(frame, cv2.COLOR_BGR2RGB) + + def _grab_next(self) -> bool: + """Advance one frame without converting it. + + Raises: + IndexError: If no frame could be grabbed. + """ + + position = self._known_position() + ok = self._stream.grab() + if not ok: + self._pos = None + raise IndexError(f"{self._path}: could not grab frame {position}") + self._pos = position + 1 + return ok + + def read_frame(self, ind: int) -> np.ndarray: + """Return frame ``ind`` as an RGB ``uint8`` array of shape ``(height, width, 3)``. + + Raises: + IndexError: If ``ind`` is outside the reported frame count, or the frame cannot be decoded. + """ + + if ind < 0 or ind >= len(self): + raise IndexError(f"Frame index {ind} out of bounds for video with {len(self)} frames.") + + if ind == self._pos: + return self._read_next() + + if self._pos is not None and self._pos < ind <= self._pos + _MAX_FORWARD_DECODE: + while self._pos < ind: + self._grab_next() + return self._read_next() + + self._seek(ind) + return self._read_next() + + def read_frames(self, start: int, stop: int) -> np.ndarray: + """Return frames ``start`` to ``stop`` (exclusive), clamped to the video, as ``(n, height, width, 3)``.""" + + start = max(0, start) + stop = min(stop, len(self)) + if stop <= start: + return np.empty((0, self.height, self.width, 3), dtype=np.uint8) + + self._seek(start) + out = np.empty((stop - start, self.height, self.width, 3), dtype=np.uint8) + + for i in range(stop - start): + out[i] = self._read_next() + + return out + + def frames(self, start: int = 0) -> Iterator[np.ndarray]: + """Yield frames from ``start`` in order, as RGB ``uint8`` arrays of shape ``(height, width, 3)``. + + Stops at the first frame the decoder cannot return, not at ``len()``: yields every frame of a video whose + reported frame count is too low, and ends early instead of raising on one that is too high. The stream is + positioned on the first ``next()``; other reads from this video during the iteration move it. + + Raises: + IndexError: If ``start`` is outside the reported frame count. + """ + + if start < 0 or start >= len(self): + raise IndexError(f"Start frame {start} out of bounds for video with {len(self)} frames.") + return self._frames_from(start) + + def _frames_from(self, start: int) -> Iterator[np.ndarray]: + self._seek(start) + while True: + position = self._known_position() + ok, frame = self._stream.read() + if not ok: + self._pos = None + return + self._pos = position + 1 + yield cv2.cvtColor(frame, cv2.COLOR_BGR2RGB) + + def __iter__(self) -> Iterator[np.ndarray]: + """Yield every frame from the first, as ``frames()`` does.""" + + return self.frames() + + def close(self) -> None: + """Release the stream.""" + + self._stream.release() diff --git a/pyproject.toml b/pyproject.toml index 9510f6d..2fab704 100644 --- a/pyproject.toml +++ b/pyproject.toml @@ -27,6 +27,8 @@ dependencies = [ "ruamel-yaml>=0.16", "typing-extensions", ] +optional-dependencies.all = [ "dlccore[video]" ] +optional-dependencies.video = [ "opencv-python-headless>=4.10.0.84" ] urls.Homepage = "https://github.com/DeepLabCut/dlccore" urls.Repository = "https://github.com/DeepLabCut/dlccore" diff --git a/tests/io/test_video.py b/tests/io/test_video.py new file mode 100644 index 0000000..c35b115 --- /dev/null +++ b/tests/io/test_video.py @@ -0,0 +1,407 @@ +# +# DeepLabCut Toolbox (deeplabcut.org) +# © A. & M.W. Mathis Labs +# https://github.com/DeepLabCut/dlccore +# +# Contributors: +# https://github.com/DeepLabCut/dlccore/graphs/contributors +# +# Licensed under GNU Lesser General Public License v3.0 +# + +from __future__ import annotations + +import shutil +import subprocess +from pathlib import Path +from typing import TYPE_CHECKING + +import numpy as np +import pytest + +cv2 = pytest.importorskip("cv2", reason="OpenCV comes with the optional 'video' extra") + +from dlccore.io.video import _MAX_FORWARD_DECODE, Video # noqa: E402 + +if TYPE_CHECKING: + from deeplabcut.utils.auxfun_videos import VideoReader + +N_FRAMES = 60 +WIDTH, HEIGHT = 128, 96 +FPS = 10 +BASE, LEVEL_OFFSET, LEVEL_STEP = 8, 16, 32 +DIGIT = 32 # side of each digit's square, in pixels + +# First, small forward jump, large forward jump to the last, backward, sequential, small forward, large forward. +# With OpenCV's mp4v writer, keyframes fall every 12 frames; in the H.264 fixture, every 30. Either way 17, 50 and 59 +# are inter frames. +ACCESS_ORDER = [0, 5, N_FRAMES - 1, 17, 18, 25, 50] + +CODECS = {"MJPG": ".avi", "mp4v": ".mp4"} +# Encoded by the ffmpeg command line from the mp4v fixture, as OpenCV's wheels cannot write it; with B-frames +H264_ARGUMENTS = ["-c:v", "libx264", "-x264-params", "keyint=30:min-keyint=30:scenecut=0", "-bf", "2", "-crf", "10"] + +# A fixed textured background keeps most of each frame static, so mp4v writes inter frames rather than all keyframes. +_BACKGROUND = cv2.GaussianBlur(np.random.default_rng(0).integers(0, 256, (HEIGHT, WIDTH, 3), dtype=np.uint8), (9, 9), 3) + + +def _encoded(index: int) -> np.ndarray: + """Frame ``index``: its two base-8 digits as flat grey squares, levels far apart to survive lossy codecs.""" + + frame = _BACKGROUND.copy() + frame[:DIGIT, :DIGIT] = LEVEL_OFFSET + LEVEL_STEP * (index // BASE) + frame[:DIGIT, DIGIT : 2 * DIGIT] = LEVEL_OFFSET + LEVEL_STEP * (index % BASE) + return frame + + +def _index_of(frame: np.ndarray) -> int: + """Map a decoded frame back to the index it was written at, reading each square away from its edges.""" + + def digit(square: np.ndarray) -> int: + return round((float(square.mean()) - LEVEL_OFFSET) / LEVEL_STEP) + + inner = slice(8, DIGIT - 8) + high = frame[inner, inner] + low = frame[inner, DIGIT + 8 : 2 * DIGIT - 8] + return BASE * digit(high) + digit(low) + + +def _write_video(path: Path, fourcc: str) -> bool: + writer = cv2.VideoWriter(str(path), cv2.VideoWriter_fourcc(*fourcc), FPS, (WIDTH, HEIGHT)) + if not writer.isOpened(): + return False + for index in range(N_FRAMES): + writer.write(_encoded(index)) + writer.release() + return _decodes_every_index(path) + + +def _decodes_every_index(path: Path) -> bool: + capture = cv2.VideoCapture(str(path)) + decoded = [] + while True: + ok, frame = capture.read() + if not ok: + break + decoded.append(_index_of(frame)) + capture.release() + return decoded == list(range(N_FRAMES)) + + +def _mp4v_video(directory: Path) -> Path: + path = directory / "indexed.mp4" + if not _write_video(path, "mp4v"): + pytest.skip("This OpenCV build cannot write and decode back a mp4v video.") + return path + + +def _ffmpeg(*arguments: str) -> None: + """Run the ffmpeg command line, skipping the test if it is missing or refuses.""" + + ffmpeg = shutil.which("ffmpeg") + if ffmpeg is None: + pytest.skip("ffmpeg is not on PATH.") + completed = subprocess.run([ffmpeg, "-y", "-v", "error", *arguments], capture_output=True, text=True, check=False) + if completed.returncode != 0: + pytest.skip(f"ffmpeg refused {arguments}: {completed.stderr.strip()}") + + +@pytest.fixture(scope="module", params=[*CODECS, "h264"]) +def video_path(request: pytest.FixtureRequest, tmp_path_factory: pytest.TempPathFactory) -> Path: + codec = request.param + directory = tmp_path_factory.mktemp(f"video_{codec}") + if codec == "h264": + path = directory / "indexed_h264.mp4" + _ffmpeg("-i", str(_mp4v_video(directory)), *H264_ARGUMENTS, str(path)) + if not _decodes_every_index(path): + pytest.skip("This OpenCV build cannot decode back the H.264 video.") + return path + path = directory / f"indexed{CODECS[codec]}" + if not _write_video(path, codec): + pytest.skip(f"This OpenCV build cannot write and decode back a {codec} video.") + return path + + +def test_the_fixture_encodes_each_index_distinctly() -> None: + # Control: without compression, every index round-trips. + assert [_index_of(_encoded(index)) for index in range(N_FRAMES)] == list(range(N_FRAMES)) + + +def test_the_mp4_fixtures_have_inter_frames_at_the_accessed_indices(video_path: Path) -> None: + # Control: otherwise the mp4v and H.264 equivalence tests would only ever land on keyframes. + if video_path.suffix != ".mp4": + pytest.skip("Only the mp4v and H.264 fixtures are meant to have inter frames.") + ffprobe = shutil.which("ffprobe") + if ffprobe is None: + pytest.skip("ffprobe is not on PATH.") + arguments = ["-v", "error", "-select_streams", "v:0", "-show_entries", "frame=pict_type", "-of", "csv=p=0"] + probed = subprocess.run( + [ffprobe, *arguments, str(video_path)], + capture_output=True, + text=True, + check=True, + ) + picture_types = [line.strip().strip(",") for line in probed.stdout.splitlines() if line.strip()] + + assert len(picture_types) == N_FRAMES + assert [index for index in ACCESS_ORDER if picture_types[index] == "I"] == [0] + + +def test_video_properties(video_path: Path) -> None: + video = Video(video_path) + + assert (len(video), video.width, video.height, video.fps) == (N_FRAMES, WIDTH, HEIGHT, FPS) + + video.close() + assert not video._stream.isOpened() + + +@pytest.fixture(scope="module") +def upright_and_rotated(tmp_path_factory: pytest.TempPathFactory) -> tuple[Path, Path]: + """The mp4v fixture, and the same stream with display-matrix metadata rotating it 90 degrees counterclockwise.""" + + directory = tmp_path_factory.mktemp("video_rotated") + upright = _mp4v_video(directory) + rotated = directory / "rotated.mp4" + _ffmpeg("-display_rotation", "90", "-i", str(upright), "-c", "copy", str(rotated)) + return upright, rotated + + +def test_frames_are_rotated_by_the_rotation_metadata( + upright_and_rotated: tuple[Path, Path], monkeypatch: pytest.MonkeyPatch +) -> None: + # Every capture opens with OpenCV 4.11.0's default, no rotation, so the test holds on any OpenCV version. + open_capture = cv2.VideoCapture + + def opened_without_rotation(*args: object) -> cv2.VideoCapture: + capture = open_capture(*args) + capture.set(cv2.CAP_PROP_ORIENTATION_AUTO, 0) + return capture + + monkeypatch.setattr(cv2, "VideoCapture", opened_without_rotation) + upright_path, rotated_path = upright_and_rotated + + with Video(upright_path) as upright, Video(rotated_path) as rotated: + assert (rotated.width, rotated.height) == (HEIGHT, WIDTH) + for index in ACCESS_ORDER: + np.testing.assert_array_equal( + rotated.read_frame(index), np.rot90(upright.read_frame(index)), err_msg=f"frame {index}" + ) + + +def test_a_context_manager_closes_the_video(video_path: Path) -> None: + with Video(video_path) as video: + assert video._stream.isOpened() + + assert not video._stream.isOpened() + + +def test_a_frame_is_rgb_uint8_of_the_video_shape(video_path: Path) -> None: + with Video(video_path) as video: + frame = video.read_frame(0) + + assert (frame.shape, frame.dtype) == ((HEIGHT, WIDTH, 3), np.uint8) + + +def test_frames_are_rgb(tmp_path: Path) -> None: + path = tmp_path / "blue.avi" + writer = cv2.VideoWriter(str(path), cv2.VideoWriter_fourcc(*"MJPG"), FPS, (WIDTH, HEIGHT)) + if not writer.isOpened(): + pytest.skip("This OpenCV build cannot write MJPG.") + bgr_blue = np.zeros((HEIGHT, WIDTH, 3), dtype=np.uint8) + bgr_blue[..., 0] = 255 + writer.write(bgr_blue) + writer.release() + + with Video(path) as video: + red, _green, blue = video.read_frame(0).reshape(-1, 3).mean(axis=0) + + assert (blue > 200, red < 50) == (True, True) + + +@pytest.mark.parametrize("index", [N_FRAMES, -1]) +def test_a_frame_outside_the_video_is_an_index_error(video_path: Path, index: int) -> None: + with Video(video_path) as video, pytest.raises(IndexError): + video.read_frame(index) + + +def test_sequential_reads_return_consecutive_frames(video_path: Path) -> None: + with Video(video_path) as video: + indices = [_index_of(video.read_frame(index)) for index in range(N_FRAMES)] + + assert indices == list(range(N_FRAMES)) + + +def test_a_block_read_returns_the_frames_in_range(video_path: Path) -> None: + with Video(video_path) as video: + video.read_frame(30) + block = video.read_frames(10, 20) + + assert (block.shape, block.dtype) == ((10, HEIGHT, WIDTH, 3), np.uint8) + assert [_index_of(frame) for frame in block] == list(range(10, 20)) + + +def test_a_block_read_is_clamped_to_the_video(video_path: Path) -> None: + with Video(video_path) as video: + assert video.read_frames(N_FRAMES - 2, N_FRAMES + 5).shape[0] == 2 + assert video.read_frames(5, 5).shape == (0, HEIGHT, WIDTH, 3) + + +def test_iterating_yields_every_frame_in_order(video_path: Path) -> None: + with Video(video_path) as video: + assert [_index_of(frame) for frame in video] == list(range(N_FRAMES)) + + +def test_frames_start_at_the_given_frame_after_other_reads(video_path: Path) -> None: + with Video(video_path) as video: + video.read_frame(50) + assert [_index_of(frame) for frame in video.frames(17)] == list(range(17, N_FRAMES)) + + +@pytest.mark.parametrize("reported", [N_FRAMES - 5, N_FRAMES + 5], ids=["too-low", "too-high"]) +def test_frames_end_where_the_decoder_ends_not_at_the_reported_count(video_path: Path, reported: int) -> None: + with Video(video_path) as video: + video._n_frames = reported + assert [_index_of(frame) for frame in video.frames()] == list(range(N_FRAMES)) + + +@pytest.mark.parametrize("start", [-1, N_FRAMES]) +def test_frames_from_outside_the_video_is_an_index_error(video_path: Path, start: int) -> None: + with Video(video_path) as video, pytest.raises(IndexError, match="out of bounds"): + video.frames(start) + + +@pytest.fixture +def damaged_path(video_path: Path, tmp_path: Path) -> Path: + """The fixture with a block of zeros mid-file, so some frames in the middle cannot be decoded.""" + + data = bytearray(video_path.read_bytes()) + middle = len(data) // 2 + data[middle : middle + 400] = bytes(400) + path = tmp_path / f"damaged{video_path.suffix}" + path.write_bytes(data) + return path + + +def _outcome(video: Video, index: int) -> int | str: + try: + return _index_of(video.read_frame(index)) + except IndexError: + return "IndexError" + + +def test_a_read_after_a_failed_read_returns_no_frame_a_fresh_seek_would_not(damaged_path: Path) -> None: + # The stream position is unknown after a failure, so a short forward jump must seek, not decode forward from it. + # A fresh seek's frame is allowed too: OpenCV's own seek can land on another frame in damage. + with Video(damaged_path) as video: + failed = next((index for index in range(N_FRAMES) if _outcome(video, index) == "IndexError"), None) + if failed is None: + pytest.skip("The damage left every frame decodable.") + ahead = range(failed + 1, min(failed + 1 + _MAX_FORWARD_DECODE, N_FRAMES)) + after_failure = [_outcome(video, index) for index in ahead] + + fresh = [] + for index in ahead: + with Video(damaged_path) as video: + fresh.append(_outcome(video, index)) + + for index, got, expected in zip(ahead, after_failure, fresh, strict=True): + assert got in (index, "IndexError", expected), f"frame {index}" + + +def test_a_path_that_is_not_a_file_is_a_file_not_found_error(tmp_path: Path) -> None: + with pytest.raises(FileNotFoundError, match="does not point to a file"): + Video(tmp_path) + + +def test_a_file_opencv_cannot_open_is_an_os_error(tmp_path: Path) -> None: + path = tmp_path / "not_a_video.mp4" + path.write_bytes(b"not a video") + + with pytest.raises(OSError, match="could not be opened") as raised: + Video(path) + + assert str(path) in str(raised.value) + + +class _Refusing: + """The real stream, with one decoder call failing as OpenCV reports it: a false ``ok``.""" + + def __init__(self, stream: cv2.VideoCapture, refused: str) -> None: + self._stream = stream + self._refused = refused + + def set(self, *args: object) -> bool: + return False if self._refused == "set" else self._stream.set(*args) + + def read(self) -> tuple[bool, np.ndarray | None]: + return (False, None) if self._refused == "read" else self._stream.read() + + def grab(self) -> bool: + return False if self._refused == "grab" else self._stream.grab() + + def release(self) -> None: + self._stream.release() + + +@pytest.mark.parametrize( + ("refused", "index", "error", "message"), + [ + ("set", N_FRAMES - 1, OSError, "seek to frame"), + ("read", 0, IndexError, "read frame"), + ("grab", 3, IndexError, "grab frame"), + ], + ids=["seek", "read", "grab"], +) +def test_a_decoder_failure_is_raised_not_returned_as_a_frame( + video_path: Path, refused: str, index: int, error: type[Exception], message: str +) -> None: + with Video(video_path) as video: + video._stream = _Refusing(video._stream, refused) + + with pytest.raises(error, match=message): + video.read_frame(index) + + +def test_read_frame_decodes_the_requested_frame(video_path: Path) -> None: + with Video(video_path) as video: + decoded = [_index_of(video.read_frame(index)) for index in ACCESS_ORDER] + + assert decoded == ACCESS_ORDER + + +def test_read_frame_equals_deeplabcut_opencv_extraction(video_path: Path) -> None: + # DeepLabCut's extract_frames(opencv=True): set_to_frame, then read_frame(crop=True); it returns RGB. + auxfun_videos = pytest.importorskip("deeplabcut.utils.auxfun_videos") + reader = auxfun_videos.VideoReader(str(video_path)) + try: + expected = [_extract_with_deeplabcut(reader, index) for index in ACCESS_ORDER] + finally: + reader.close() + + with Video(video_path) as video: + for index, frame in zip(ACCESS_ORDER, expected, strict=True): + np.testing.assert_array_equal(video.read_frame(index), frame, err_msg=f"frame {index}") + + +def test_read_frame_equals_moviepy_extraction(video_path: Path) -> None: + # DeepLabCut's extract_frames(opencv=False): VideoFileClip.get_frame(index / fps), moviepy 1.x. + editor = pytest.importorskip("moviepy.editor") + + clip = editor.VideoFileClip(str(video_path)) + try: + expected = [_index_of(clip.get_frame(index * 1.0 / clip.fps)) for index in ACCESS_ORDER] + finally: + clip.close() + + with Video(video_path) as video: + decoded = [_index_of(video.read_frame(index)) for index in ACCESS_ORDER] + + assert decoded == expected == ACCESS_ORDER + + +def _extract_with_deeplabcut(reader: VideoReader, index: int) -> np.ndarray: + reader.set_to_frame(index) + frame = reader.read_frame(crop=True) + assert frame is not None, f"DeepLabCut read no frame at {index}" + return frame