Skip to content
Draft
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 1 addition & 1 deletion .github/workflows/build_release.yml
Original file line number Diff line number Diff line change
Expand Up @@ -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: |
Expand Down
12 changes: 10 additions & 2 deletions .github/workflows/test_package.yml
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand All @@ -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
Expand Down
2 changes: 1 addition & 1 deletion .github/workflows/weekly_checks.yml
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down
226 changes: 226 additions & 0 deletions dlccore/io/video.py
Original file line number Diff line number Diff line change
@@ -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))

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Apparently it is risky to trust CAP_PROP_FRAME_COUNT (which is an estimate), because, read_frame can then refuse valid frames, or raise "Could not read frame" near the end.

Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Made it a bit clearer, not sure what would be best save for decoding the whole video as fallback

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)

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

CAP_PROP_POS_FRAMES could land on the nearest keyframe for some codecs. Only mp4v is tested.

Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Added an H264 test

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()
2 changes: 2 additions & 0 deletions pyproject.toml
Original file line number Diff line number Diff line change
Expand Up @@ -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"

Expand Down
Loading
Loading