torchvision.io¶
The torchvision.io
package provides functions for performing IO
operations. They are currently specific to reading and writing video and
images.
Video¶
-
torchvision.io.
read_video
(filename: str, start_pts: int = 0, end_pts: Optional[float] = None, pts_unit: str = 'pts') → Tuple[torch.Tensor, torch.Tensor, Dict[str, Any]][source]¶ Reads a video from a file, returning both the video frames as well as the audio frames
- Parameters
filename (str) – path to the video file
start_pts (int if pts_unit = 'pts', optional) – float / Fraction if pts_unit = ‘sec’, optional the start presentation time of the video
end_pts (int if pts_unit = 'pts', optional) – float / Fraction if pts_unit = ‘sec’, optional the end presentation time
pts_unit (str, optional) – unit in which start_pts and end_pts values will be interpreted, either ‘pts’ or ‘sec’. Defaults to ‘pts’.
- Returns
vframes (Tensor[T, H, W, C]) – the T video frames
aframes (Tensor[K, L]) – the audio frames, where K is the number of channels and L is the number of points
info (Dict) – metadata for the video and audio. Can contain the fields video_fps (float) and audio_fps (int)
-
torchvision.io.
read_video_timestamps
(filename: str, pts_unit: str = 'pts') → Tuple[List[int], Optional[float]][source]¶ List the video frames timestamps.
Note that the function decodes the whole video frame-by-frame.
- Parameters
- Returns
pts (List[int] if pts_unit = ‘pts’) – List[Fraction] if pts_unit = ‘sec’ presentation timestamps for each one of the frames in the video.
video_fps (float, optional) – the frame rate for the video
Fine-grained video API¶
In addition to the read_video
function, we provide a high-performance
lower-level API for more fine-grained control compared to the read_video
function.
It does all this whilst fully supporting torchscript.
-
class
torchvision.io.
VideoReader
(path, stream='video')[source]¶ Fine-grained video-reading API. Supports frame-by-frame reading of various streams from a single video container.
Example
The following examples creates a
VideoReader
object, seeks into 2s point, and returns a single frame:import torchvision video_path = "path_to_a_test_video" reader = torchvision.io.VideoReader(video_path, "video") reader.seek(2.0) frame = next(reader)
VideoReader
implements the iterable API, which makes it suitable to using it in conjunction withitertools
for more advanced reading. As such, we can use aVideoReader
instance inside for loops:reader.seek(2) for frame in reader: frames.append(frame['data']) # additionally, `seek` implements a fluent API, so we can do for frame in reader.seek(2): frames.append(frame['data'])
With
itertools
, we can read all frames between 2 and 5 seconds with the following code:for frame in itertools.takewhile(lambda x: x['pts'] <= 5, reader.seek(2)): frames.append(frame['data'])
and similarly, reading 10 frames after the 2s timestamp can be achieved as follows:
for frame in itertools.islice(reader.seek(2), 10): frames.append(frame['data'])
Note
Each stream descriptor consists of two parts: stream type (e.g. ‘video’) and a unique stream id (which are determined by the video encoding). In this way, if the video contaner contains multiple streams of the same type, users can acces the one they want. If only stream type is passed, the decoder auto-detects first stream of that type.
- Parameters
path (string) – Path to the video file in supported format
stream (string, optional) – descriptor of the required stream, followed by the stream id, in the format
{stream_type}:{stream_id}
. Defaults to"video:0"
. Currently available options include['video', 'audio']
-
__next__
()[source]¶ Decodes and returns the next frame of the current stream
- Returns
a dictionary with fields
data
andpts
containing decoded frame and corresponding timestamp- Return type
(dict)
-
get_metadata
()[source]¶ Returns video metadata
- Returns
dictionary containing duration and frame rate for every stream
- Return type
(dict)
-
seek
(time_s: float)[source]¶ Seek within current stream.
- Parameters
time_s (float) – seek time in seconds
Note
Current implementation is the so-called precise seek. This means following seek, call to
next()
will return the frame with the exact timestamp if it exists or the first frame with timestamp larger thantime_s
.
-
set_current_stream
(stream: str)[source]¶ Set current stream. Explicitly define the stream we are operating on.
- Parameters
stream (string) – descriptor of the required stream. Defaults to
"video:0"
Currently available stream types include['video', 'audio']
. Each descriptor consists of two parts: stream type (e.g. ‘video’) and a unique stream id (which are determined by video encoding). In this way, if the video contaner contains multiple streams of the same type, users can acces the one they want. If only stream type is passed, the decoder auto-detects first stream of that type and returns it.- Returns
True on succes, False otherwise
- Return type
(bool)
Example of inspecting a video:
import torchvision
video_path = "path to a test video"
# Constructor allocates memory and a threaded decoder
# instance per video. At the momet it takes two arguments:
# path to the video file, and a wanted stream.
reader = torchvision.io.VideoReader(video_path, "video")
# The information about the video can be retrieved using the
# `get_metadata()` method. It returns a dictionary for every stream, with
# duration and other relevant metadata (often frame rate)
reader_md = reader.get_metadata()
# metadata is structured as a dict of dicts with following structure
# {"stream_type": {"attribute": [attribute per stream]}}
#
# following would print out the list of frame rates for every present video stream
print(reader_md["video"]["fps"])
# we explicitly select the stream we would like to operate on. In
# the constructor we select a default video stream, but
# in practice, we can set whichever stream we would like
video.set_current_stream("video:0")
Image¶
-
torchvision.io.
read_image
(path: str) → torch.Tensor[source]¶ Reads a JPEG or PNG image into a 3 dimensional RGB Tensor. The values of the output tensor are uint8 between 0 and 255.
-
torchvision.io.
decode_image
(input: torch.Tensor) → torch.Tensor[source]¶ Detects whether an image is a JPEG or PNG and performs the appropriate operation to decode the image into a 3 dimensional RGB Tensor.
The values of the output tensor are uint8 between 0 and 255.
-
torchvision.io.
encode_jpeg
(input: torch.Tensor, quality: int = 75) → torch.Tensor[source]¶ Takes an input tensor in CHW layout and returns a buffer with the contents of its corresponding JPEG file.
- Parameters
- Returns
output – A one dimensional int8 tensor that contains the raw bytes of the JPEG file.
- Return type
Tensor[1]
-
torchvision.io.
write_jpeg
(input: torch.Tensor, filename: str, quality: int = 75)[source]¶ Takes an input tensor in CHW layout and saves it in a JPEG file.
-
torchvision.io.
encode_png
(input: torch.Tensor, compression_level: int = 6) → torch.Tensor[source]¶ Takes an input tensor in CHW layout and returns a buffer with the contents of its corresponding PNG file.
- Parameters
- Returns
output – A one dimensional int8 tensor that contains the raw bytes of the PNG file.
- Return type
Tensor[1]