Decoding / Encoding images and videos¶
The torchvision.io
module provides utilities for decoding and encoding
images and videos.
Image Decoding¶
Torchvision currently supports decoding JPEG, PNG, WEBP and GIF images. JPEG decoding can also be done on CUDA GPUs.
The main entry point is the decode_image()
function, which
you can use as an alternative to PIL.Image.open()
. It will decode images
straight into image Tensors, thus saving you the conversion and allowing you to
run transforms/preproc natively on tensors.
from torchvision.io import decode_image
img = decode_image("path_to_image", mode="RGB")
img.dtype # torch.uint8
# Or
raw_encoded_bytes = ... # read encoded bytes from your file system
img = decode_image(raw_encoded_bytes, mode="RGB")
decode_image()
will automatically detect the image format,
and call the corresponding decoder. You can also use the lower-level
format-specific decoders which can be more powerful, e.g. if you want to
encode/decode JPEGs on CUDA.
|
Decode an image into a uint8 tensor, from a path or from raw encoded bytes. |
|
Decode JPEG image(s) into 3D RGB or grayscale Tensor(s), on CPU or CUDA. |
|
Takes an input tensor in CHW layout and returns a buffer with the contents of its corresponding PNG file. |
|
Decode a GIF image into a 3 or 4 dimensional RGB Tensor. |
|
Decode a WEBP image into a 3 dimensional RGB[A] Tensor. |
|
Allow automatic conversion to RGB, RGBA, etc while decoding. |
Obsolete decoding function:
|
[OBSOLETE] Use |
Image Encoding¶
For encoding, JPEG (cpu and CUDA) and PNG are supported.
|
Encode RGB tensor(s) into raw encoded jpeg bytes, on CPU or CUDA. |
|
Takes an input tensor in CHW layout and saves it in a JPEG file. |
|
Takes an input tensor in CHW layout and returns a buffer with the contents of its corresponding PNG file. |
|
Takes an input tensor in CHW layout (or HW in the case of grayscale images) and saves it in a PNG file. |
IO operations¶
|
Return the bytes contents of a file as a uint8 1D Tensor. |
|
Write the content of an uint8 1D tensor to a file. |
Video¶
Warning
Torchvision supports video decoding through different APIs listed below, some of which are still in BETA stage. In the near future, we intend to centralize PyTorch’s video decoding capabilities within the torchcodec project. We encourage you to try it out and share your feedback, as the torchvision video decoders will eventually be deprecated.
|
Reads a video from a file, returning both the video frames and the audio frames |
|
List the video frames timestamps. |
|
Writes a 4d tensor in [T, H, W, C] format in a video file. |
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.
|
Fine-grained video-reading API. |