Rate this Page

PngEncoder#

class torchcodec.encoders.PngEncoder(img: Tensor)[source]#

Encoder for PNG images.

For a tutorial, see: Encoding images.

Example

from torchcodec.encoders import PngEncoder

PngEncoder(img).to_file("image.png")
# or encode to a file-like object or to a tensor, see methods below.
Parameters:

img (torch.Tensor) – The image to encode, a 3-dimensional uint8 tensor in CHW layout with 1 (grayscale) or 3 (RGB) channels.

Examples using PngEncoder:

Encoding images

Encoding images

Migrating from TorchVision to TorchCodec

Migrating from TorchVision to TorchCodec
to_file(dest: str | Path, *, compression_level: int = 6) None[source]#

Encode the image into a PNG file.

Parameters:
  • dest (str or pathlib.Path) – The path to the output file, e.g. image.png.

  • compression_level (int, optional) – zlib compression level between 0 (no compression, fastest) and 9 (max compression, slowest). Default: 6.

to_file_like(dest: RawIOBase | BufferedIOBase, *, compression_level: int = 6) None[source]#

Encode the image into a file-like object.

Parameters:
  • dest – A writable file-like object supporting write and seek, such as io.BytesIO() or an open file in binary write mode.

  • compression_level (int, optional) – zlib compression level between 0 (no compression, fastest) and 9 (max compression, slowest). Default: 6.

to_tensor(*, compression_level: int = 6) Tensor[source]#

Encode the image into raw bytes, as a 1D uint8 tensor.

Parameters:

compression_level (int, optional) – zlib compression level between 0 (no compression, fastest) and 9 (max compression, slowest). Default: 6.

Returns:

The encoded bytes, a 1D uint8 tensor.

Return type:

torch.Tensor