• Docs >
  • [DEPRECATED] Decoding and Encoding images
Shortcuts

[DEPRECATED] Decoding and Encoding images

Warning

The image decoding and encoding capabilities of TorchVision are deprecated since torchvision 0.29 and will be removed in a future release. They are superseded by the more complete decoders and encoders of TorchCodec (from torchcodec 0.16). Please see this migration guide on how to migrate your code.

The torchvision.io module provides utilities for decoding and encoding images. For videos and audio, please use TorchCodec.

Image Decoding

Torchvision currently supports decoding JPEG, PNG, WEBP, GIF, AVIF, and HEIC 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 (except for HEIC and AVIF images, see details in decode_avif() and decode_heic()). 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_image(input[, mode, ...])

[DEPRECATED] Use TorchCodec instead.

decode_jpeg(input[, mode, device, ...])

[DEPRECATED] Use TorchCodec instead.

decode_png(input[, mode, apply_exif_orientation])

[DEPRECATED] Use TorchCodec instead.

decode_webp(input[, mode])

[DEPRECATED] Use TorchCodec instead.

decode_avif(input[, mode])

[DEPRECATED] Use TorchCodec instead.

decode_heic(input[, mode])

[DEPRECATED] Use TorchCodec instead.

decode_gif(input)

[DEPRECATED] Use TorchCodec instead.

ImageReadMode(value)

[DEPRECATED] Use TorchCodec instead.

Obsolete decoding function:

read_image(path[, mode, apply_exif_orientation])

[DEPRECATED] Use TorchCodec instead.

Image Encoding

For encoding, JPEG (cpu and CUDA) and PNG are supported.

encode_jpeg(input[, quality])

[DEPRECATED] Use TorchCodec instead.

write_jpeg(input, filename[, quality])

[DEPRECATED] Use TorchCodec instead.

encode_png(input[, compression_level])

[DEPRECATED] Use TorchCodec instead.

write_png(input, filename[, compression_level])

[DEPRECATED] Use TorchCodec instead.

IO operations

read_file(path)

[DEPRECATED] Use TorchCodec instead.

write_file(filename, data)

[DEPRECATED] Use TorchCodec instead.

Docs

Access comprehensive developer documentation for PyTorch

View Docs

Tutorials

Get in-depth tutorials for beginners and advanced developers

View Tutorials

Resources

Find development resources and get your questions answered

View Resources