-
Notifications
You must be signed in to change notification settings - Fork 11
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
Add video writing #129
Add video writing #129
Changes from all commits
File filter
Filter by extension
Conversations
Jump to
Diff view
Diff view
There are no files selected for viewing
Original file line number | Diff line number | Diff line change |
---|---|---|
|
@@ -6,6 +6,8 @@ | |
|
||
::: sleap_io.load_video | ||
|
||
::: sleap_io.save_video | ||
|
||
::: sleap_io.load_slp | ||
|
||
::: sleap_io.save_slp | ||
|
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -1 +1,3 @@ | ||
"""This sub-package contains I/O-related modules such as specific format backends.""" | ||
|
||
from . import video_reading as video |
Original file line number | Diff line number | Diff line change | ||||||||||||||||||||||||||||||||||||||||||||||||||||||||
---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
@@ -1,4 +1,4 @@ | ||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
"""Backends for reading and writing videos.""" | ||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
"""Backends for reading videos.""" | ||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
|
||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
from __future__ import annotations | ||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
from pathlib import Path | ||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
|
@@ -193,6 +193,17 @@ def __len__(self) -> int: | |||||||||||||||||||||||||||||||||||||||||||||||||||||||||
"""Return number of frames in the video.""" | ||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
return self.shape[0] | ||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
|
||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
def has_frame(self, frame_idx: int) -> bool: | ||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
"""Check if a frame index is contained in the video. | ||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
|
||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
Args: | ||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
frame_idx: Index of frame to check. | ||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
|
||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
Returns: | ||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
`True` if the index is contained in the video, otherwise `False`. | ||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
""" | ||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
return frame_idx < len(self) | ||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
|
||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
def get_frame(self, frame_idx: int) -> np.ndarray: | ||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
"""Read a single frame from the video. | ||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
|
||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
|
@@ -212,6 +223,9 @@ def get_frame(self, frame_idx: int) -> np.ndarray: | |||||||||||||||||||||||||||||||||||||||||||||||||||||||||
|
||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
See also: `get_frames` | ||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
""" | ||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
if not self.has_frame(frame_idx): | ||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
raise IndexError(f"Frame index {frame_idx} out of range.") | ||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
|
||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
img = self._read_frame(frame_idx) | ||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
|
||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
if self.grayscale is None: | ||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
|
@@ -620,6 +634,20 @@ def decode_embedded(self, img_string: np.ndarray) -> np.ndarray: | |||||||||||||||||||||||||||||||||||||||||||||||||||||||||
img = np.expand_dims(img, axis=-1) | ||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
return img | ||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
|
||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
def has_frame(self, frame_idx: int) -> bool: | ||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
"""Check if a frame index is contained in the video. | ||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
|
||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
Args: | ||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
frame_idx: Index of frame to check. | ||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
|
||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
Returns: | ||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
`True` if the index is contained in the video, otherwise `False`. | ||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
""" | ||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
if self.frame_map: | ||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
return frame_idx in self.frame_map | ||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
else: | ||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
return frame_idx < len(self) | ||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
|
||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
def _read_frame(self, frame_idx: int) -> np.ndarray: | ||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
Comment on lines
+637
to
+650
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. Handle Negative Frame Indices in In the Consider modifying the method to ensure that def has_frame(self, frame_idx: int) -> bool:
"""Check if a frame index is contained in the video.
Args:
frame_idx: Index of frame to check.
Returns:
`True` if the index is contained in the video, otherwise `False`.
"""
+ if frame_idx < 0:
+ return False
if self.frame_map:
return frame_idx in self.frame_map
else:
return frame_idx < len(self) 📝 Committable suggestion
Suggested change
|
||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
"""Read a single frame from the video. | ||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
|
||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
|
Original file line number | Diff line number | Diff line change | ||||||||||||||||||||||||||||||||||||||||||||||||||||||
---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
@@ -0,0 +1,119 @@ | ||||||||||||||||||||||||||||||||||||||||||||||||||||||||
"""Utilities for writing videos.""" | ||||||||||||||||||||||||||||||||||||||||||||||||||||||||
|
||||||||||||||||||||||||||||||||||||||||||||||||||||||||
from __future__ import annotations | ||||||||||||||||||||||||||||||||||||||||||||||||||||||||
from typing import Type, Optional | ||||||||||||||||||||||||||||||||||||||||||||||||||||||||
from types import TracebackType | ||||||||||||||||||||||||||||||||||||||||||||||||||||||||
import numpy as np | ||||||||||||||||||||||||||||||||||||||||||||||||||||||||
import imageio | ||||||||||||||||||||||||||||||||||||||||||||||||||||||||
import imageio.v2 as iio_v2 | ||||||||||||||||||||||||||||||||||||||||||||||||||||||||
import attrs | ||||||||||||||||||||||||||||||||||||||||||||||||||||||||
from pathlib import Path | ||||||||||||||||||||||||||||||||||||||||||||||||||||||||
|
||||||||||||||||||||||||||||||||||||||||||||||||||||||||
|
||||||||||||||||||||||||||||||||||||||||||||||||||||||||
@attrs.define | ||||||||||||||||||||||||||||||||||||||||||||||||||||||||
class VideoWriter: | ||||||||||||||||||||||||||||||||||||||||||||||||||||||||
"""Simple video writer using imageio and FFMPEG. | ||||||||||||||||||||||||||||||||||||||||||||||||||||||||
|
||||||||||||||||||||||||||||||||||||||||||||||||||||||||
Attributes: | ||||||||||||||||||||||||||||||||||||||||||||||||||||||||
filename: Path to output video file. | ||||||||||||||||||||||||||||||||||||||||||||||||||||||||
fps: Frames per second. Defaults to 30. | ||||||||||||||||||||||||||||||||||||||||||||||||||||||||
pixelformat: Pixel format for video. Defaults to "yuv420p". | ||||||||||||||||||||||||||||||||||||||||||||||||||||||||
codec: Codec to use for encoding. Defaults to "libx264". | ||||||||||||||||||||||||||||||||||||||||||||||||||||||||
crf: Constant rate factor to control lossiness of video. Values go from 2 to 32, | ||||||||||||||||||||||||||||||||||||||||||||||||||||||||
with numbers in the 18 to 30 range being most common. Lower values mean less | ||||||||||||||||||||||||||||||||||||||||||||||||||||||||
compressed/higher quality. Defaults to 25. No effect if codec is not | ||||||||||||||||||||||||||||||||||||||||||||||||||||||||
"libx264". | ||||||||||||||||||||||||||||||||||||||||||||||||||||||||
preset: H264 encoding preset. Defaults to "superfast". No effect if codec is not | ||||||||||||||||||||||||||||||||||||||||||||||||||||||||
"libx264". | ||||||||||||||||||||||||||||||||||||||||||||||||||||||||
output_params: Additional output parameters for FFMPEG. This should be a list of | ||||||||||||||||||||||||||||||||||||||||||||||||||||||||
strings corresponding to command line arguments for FFMPEG and libx264. Use | ||||||||||||||||||||||||||||||||||||||||||||||||||||||||
`ffmpeg -h encoder=libx264` to see all options for libx264 output_params. | ||||||||||||||||||||||||||||||||||||||||||||||||||||||||
|
||||||||||||||||||||||||||||||||||||||||||||||||||||||||
Notes: | ||||||||||||||||||||||||||||||||||||||||||||||||||||||||
This class can be used as a context manager to ensure the video is properly | ||||||||||||||||||||||||||||||||||||||||||||||||||||||||
closed after writing. For example: | ||||||||||||||||||||||||||||||||||||||||||||||||||||||||
|
||||||||||||||||||||||||||||||||||||||||||||||||||||||||
```python | ||||||||||||||||||||||||||||||||||||||||||||||||||||||||
with VideoWriter("output.mp4") as writer: | ||||||||||||||||||||||||||||||||||||||||||||||||||||||||
for frame in frames: | ||||||||||||||||||||||||||||||||||||||||||||||||||||||||
writer(frame) | ||||||||||||||||||||||||||||||||||||||||||||||||||||||||
``` | ||||||||||||||||||||||||||||||||||||||||||||||||||||||||
""" | ||||||||||||||||||||||||||||||||||||||||||||||||||||||||
|
||||||||||||||||||||||||||||||||||||||||||||||||||||||||
filename: Path = attrs.field(converter=Path) | ||||||||||||||||||||||||||||||||||||||||||||||||||||||||
fps: float = 30 | ||||||||||||||||||||||||||||||||||||||||||||||||||||||||
pixelformat: str = "yuv420p" | ||||||||||||||||||||||||||||||||||||||||||||||||||||||||
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. The The Apply this diff to include self._writer = iio_v2.get_writer(
self.filename.as_posix(),
format="FFMPEG",
fps=self.fps,
codec=self.codec,
+ pixelformat=self.pixelformat,
output_params=self.build_output_params(),
)
|
||||||||||||||||||||||||||||||||||||||||||||||||||||||||
codec: str = "libx264" | ||||||||||||||||||||||||||||||||||||||||||||||||||||||||
crf: int = 25 | ||||||||||||||||||||||||||||||||||||||||||||||||||||||||
preset: str = "superfast" | ||||||||||||||||||||||||||||||||||||||||||||||||||||||||
output_params: list[str] = attrs.field(factory=list) | ||||||||||||||||||||||||||||||||||||||||||||||||||||||||
_writer: "imageio.plugins.ffmpeg.FfmpegFormat.Writer" | None = None | ||||||||||||||||||||||||||||||||||||||||||||||||||||||||
|
||||||||||||||||||||||||||||||||||||||||||||||||||||||||
def build_output_params(self) -> list[str]: | ||||||||||||||||||||||||||||||||||||||||||||||||||||||||
"""Build the output parameters for FFMPEG.""" | ||||||||||||||||||||||||||||||||||||||||||||||||||||||||
output_params = [] | ||||||||||||||||||||||||||||||||||||||||||||||||||||||||
if self.codec == "libx264": | ||||||||||||||||||||||||||||||||||||||||||||||||||||||||
output_params.extend( | ||||||||||||||||||||||||||||||||||||||||||||||||||||||||
[ | ||||||||||||||||||||||||||||||||||||||||||||||||||||||||
"-crf", | ||||||||||||||||||||||||||||||||||||||||||||||||||||||||
str(self.crf), | ||||||||||||||||||||||||||||||||||||||||||||||||||||||||
"-preset", | ||||||||||||||||||||||||||||||||||||||||||||||||||||||||
self.preset, | ||||||||||||||||||||||||||||||||||||||||||||||||||||||||
] | ||||||||||||||||||||||||||||||||||||||||||||||||||||||||
) | ||||||||||||||||||||||||||||||||||||||||||||||||||||||||
return output_params + self.output_params | ||||||||||||||||||||||||||||||||||||||||||||||||||||||||
|
||||||||||||||||||||||||||||||||||||||||||||||||||||||||
Comment on lines
+52
to
+65
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. 🛠️ Refactor suggestion Refactor Currently, For example: def build_output_params(self) -> list[str]:
"""Build the output parameters for FFMPEG."""
output_params = []
- if self.codec == "libx264":
+ if self.codec in ("libx264", "h264"):
output_params.extend(
[
"-crf",
str(self.crf),
"-preset",
self.preset,
]
)
+ # Add additional codec-specific parameters here
return output_params + self.output_params 📝 Committable suggestion
Suggested change
|
||||||||||||||||||||||||||||||||||||||||||||||||||||||||
def open(self): | ||||||||||||||||||||||||||||||||||||||||||||||||||||||||
"""Open the video writer.""" | ||||||||||||||||||||||||||||||||||||||||||||||||||||||||
self.close() | ||||||||||||||||||||||||||||||||||||||||||||||||||||||||
|
||||||||||||||||||||||||||||||||||||||||||||||||||||||||
self.filename.parent.mkdir(parents=True, exist_ok=True) | ||||||||||||||||||||||||||||||||||||||||||||||||||||||||
self._writer = iio_v2.get_writer( | ||||||||||||||||||||||||||||||||||||||||||||||||||||||||
self.filename.as_posix(), | ||||||||||||||||||||||||||||||||||||||||||||||||||||||||
format="FFMPEG", | ||||||||||||||||||||||||||||||||||||||||||||||||||||||||
fps=self.fps, | ||||||||||||||||||||||||||||||||||||||||||||||||||||||||
codec=self.codec, | ||||||||||||||||||||||||||||||||||||||||||||||||||||||||
pixelformat=self.pixelformat, | ||||||||||||||||||||||||||||||||||||||||||||||||||||||||
output_params=self.build_output_params(), | ||||||||||||||||||||||||||||||||||||||||||||||||||||||||
) | ||||||||||||||||||||||||||||||||||||||||||||||||||||||||
|
||||||||||||||||||||||||||||||||||||||||||||||||||||||||
def close(self): | ||||||||||||||||||||||||||||||||||||||||||||||||||||||||
"""Close the video writer.""" | ||||||||||||||||||||||||||||||||||||||||||||||||||||||||
if self._writer is not None: | ||||||||||||||||||||||||||||||||||||||||||||||||||||||||
self._writer.close() | ||||||||||||||||||||||||||||||||||||||||||||||||||||||||
self._writer = None | ||||||||||||||||||||||||||||||||||||||||||||||||||||||||
|
||||||||||||||||||||||||||||||||||||||||||||||||||||||||
def write_frame(self, frame: np.ndarray): | ||||||||||||||||||||||||||||||||||||||||||||||||||||||||
"""Write a frame to the video. | ||||||||||||||||||||||||||||||||||||||||||||||||||||||||
|
||||||||||||||||||||||||||||||||||||||||||||||||||||||||
Args: | ||||||||||||||||||||||||||||||||||||||||||||||||||||||||
frame: Frame to write to video. Should be a 2D or 3D numpy array with | ||||||||||||||||||||||||||||||||||||||||||||||||||||||||
dimensions (height, width) or (height, width, channels). | ||||||||||||||||||||||||||||||||||||||||||||||||||||||||
""" | ||||||||||||||||||||||||||||||||||||||||||||||||||||||||
if self._writer is None: | ||||||||||||||||||||||||||||||||||||||||||||||||||||||||
self.open() | ||||||||||||||||||||||||||||||||||||||||||||||||||||||||
|
||||||||||||||||||||||||||||||||||||||||||||||||||||||||
self._writer.append_data(frame) | ||||||||||||||||||||||||||||||||||||||||||||||||||||||||
Comment on lines
+86
to
+96
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. 🛠️ Refactor suggestion Add input validation for To enhance robustness, consider validating that You might include checks like: def write_frame(self, frame: np.ndarray):
"""Write a frame to the video.
Args:
frame: Frame to write to video. Should be a 2D or 3D numpy array with
dimensions (height, width) or (height, width, channels).
"""
if self._writer is None:
self.open()
+ if not isinstance(frame, np.ndarray):
+ raise TypeError("Frame must be a NumPy ndarray.")
+ if frame.ndim not in (2, 3):
+ raise ValueError("Frame must be a 2D or 3D array.")
self._writer.append_data(frame) 📝 Committable suggestion
Suggested change
|
||||||||||||||||||||||||||||||||||||||||||||||||||||||||
|
||||||||||||||||||||||||||||||||||||||||||||||||||||||||
def __enter__(self): | ||||||||||||||||||||||||||||||||||||||||||||||||||||||||
"""Context manager entry.""" | ||||||||||||||||||||||||||||||||||||||||||||||||||||||||
return self | ||||||||||||||||||||||||||||||||||||||||||||||||||||||||
|
||||||||||||||||||||||||||||||||||||||||||||||||||||||||
def __exit__( | ||||||||||||||||||||||||||||||||||||||||||||||||||||||||
self, | ||||||||||||||||||||||||||||||||||||||||||||||||||||||||
exc_type: Optional[Type[BaseException]], | ||||||||||||||||||||||||||||||||||||||||||||||||||||||||
exc_value: Optional[BaseException], | ||||||||||||||||||||||||||||||||||||||||||||||||||||||||
traceback: Optional[TracebackType], | ||||||||||||||||||||||||||||||||||||||||||||||||||||||||
) -> Optional[bool]: | ||||||||||||||||||||||||||||||||||||||||||||||||||||||||
"""Context manager exit.""" | ||||||||||||||||||||||||||||||||||||||||||||||||||||||||
self.close() | ||||||||||||||||||||||||||||||||||||||||||||||||||||||||
return False | ||||||||||||||||||||||||||||||||||||||||||||||||||||||||
|
||||||||||||||||||||||||||||||||||||||||||||||||||||||||
def __call__(self, frame: np.ndarray): | ||||||||||||||||||||||||||||||||||||||||||||||||||||||||
"""Write a frame to the video. | ||||||||||||||||||||||||||||||||||||||||||||||||||||||||
|
||||||||||||||||||||||||||||||||||||||||||||||||||||||||
Args: | ||||||||||||||||||||||||||||||||||||||||||||||||||||||||
frame: Frame to write to video. Should be a 2D or 3D numpy array with | ||||||||||||||||||||||||||||||||||||||||||||||||||||||||
dimensions (height, width) or (height, width, channels). | ||||||||||||||||||||||||||||||||||||||||||||||||||||||||
""" | ||||||||||||||||||||||||||||||||||||||||||||||||||||||||
self.write_frame(frame) |
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,15 @@ | ||
"""Tests for the sleap_io.io.video_writing module.""" | ||
|
||
import sleap_io as sio | ||
from sleap_io.io.video_writing import VideoWriter | ||
|
||
|
||
def test_video_writer(centered_pair_low_quality_video, tmp_path): | ||
imgs = centered_pair_low_quality_video[:4] | ||
with VideoWriter(tmp_path / "output.mp4") as writer: | ||
for img in imgs: | ||
writer.write_frame(img) | ||
|
||
assert (tmp_path / "output.mp4").exists() | ||
vid = sio.load_video(tmp_path / "output.mp4") | ||
assert vid.shape == (4, 384, 384, 1) |
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.
Handle Negative Frame Indices in
has_frame
MethodThe
has_frame
method (lines 196-206) inVideoBackend
does not account for negative frame indices. Since negative indices can lead to unexpected behavior or errors when accessing frames, it's important to ensure that only valid, non-negative indices are considered.Consider updating the condition to include a check for non-negative indices:
📝 Committable suggestion