Repository navigation
Add the video reader and the video extra #12
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Draft
Draft
Changes from all commits
Commits
Show all changes
8 commits
Select commit
Hold shift + click to select a range
3f36883
Copy video reader
C-Achard fc8d96f
Adapt video reader to dlccore
C-Achard c3d5122
Adjust OpenCV version
C-Achard 098db9f
Improve video error types and diagnostics
C-Achard 5e1feda
Honor video rotation metadata
C-Achard 90a015b
Add sequential video frame iteration
C-Achard b00b2b3
Reset video position after decoder failures
C-Achard f03ecbc
Add ffmpeg to CI
C-Achard File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| 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)) | ||
| 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) | ||
|
Collaborator
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more.
Member
Author
There was a problem hiding this comment. Choose a reason for hiding this commentThe 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() | ||
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Oops, something went wrong.
Oops, something went wrong.
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
There was a problem hiding this comment.
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_framecan then refuse valid frames, or raise "Could not read frame" near the end.There was a problem hiding this comment.
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