Rate this Page

decode_png#

torchcodec.decoders.decode_png(source: str | Path | bytes | Tensor, *, mode: Literal['UNCHANGED', 'GRAY', 'GRAY_ALPHA', 'RGB', 'RGB_ALPHA'] | ImageReadMode = 'RGB', output_dtype: dtype | Literal['auto'] = torch.uint8) Tensor[source]#

Decode a PNG image into a CHW tensor.

Example

from torchcodec.decoders import decode_png

img = decode_png("image.png")
Parameters:
  • source (str, pathlib.Path, bytes, or torch.Tensor) – The encoded PNG data: a path (str or pathlib.Path), a bytes object, or a 1-D uint8 torch.Tensor of the raw encoded bytes.

  • mode (str or ImageReadMode, optional) – Desired color mode of the output image. Can be one of "UNCHANGED", "GRAY", "GRAY_ALPHA", "RGB", or "RGB_ALPHA". Default is "RGB".

  • output_dtype (torch.dtype or "auto", optional) – desired dtype of the output image tensor. Accepted values are torch.uint8 (default), torch.uint16, and "auto". PNG images can natively store 16-bit samples: torch.uint16 preserves that precision (8-bit sources are scaled up, 0-255 -> 0-65535), while torch.uint8 scales 16-bit sources down. "auto" keeps the source’s native bit depth, yielding uint8 for 8-bit PNGs and uint16 for 16-bit ones.

Returns:

The decoded image, of shape (C, H, W).

Return type:

torch.Tensor

Examples using decode_png:

Decoding images

Decoding images