|
| 1 | +# Copyright (c) Meta Platforms, Inc. and affiliates. |
| 2 | +# All rights reserved. |
| 3 | +# |
| 4 | +# This source code is licensed under the BSD-style license found in the |
| 5 | +# LICENSE file in the root directory of this source tree. |
| 6 | + |
| 7 | +""" |
| 8 | +=============== |
| 9 | +Encoding images |
| 10 | +=============== |
| 11 | +
|
| 12 | +In this example, we'll learn how to encode an image tensor to JPEG or PNG using |
| 13 | +the :class:`~torchcodec.encoders.JpegEncoder` and |
| 14 | +:class:`~torchcodec.encoders.PngEncoder` classes. |
| 15 | +""" |
| 16 | + |
| 17 | +# %% |
| 18 | +# First, a bit of boilerplate: we'll download an image from the web and define a |
| 19 | +# plotting utility. You can ignore that part and jump right below to |
| 20 | +# :ref:`encoding_image`. |
| 21 | + |
| 22 | +import requests |
| 23 | +import torch |
| 24 | + |
| 25 | +from torchcodec.decoders import decode_image |
| 26 | + |
| 27 | +url = "https://raw.githubusercontent.com/meta-pytorch/torchcodec/refs/heads/main/docs/source/_static/thumbnails/cat_encoding.jpeg" |
| 28 | +response = requests.get(url, headers={"User-Agent": ""}) |
| 29 | +if response.status_code != 200: |
| 30 | + raise RuntimeError(f"Failed to download image. {response.status_code = }.") |
| 31 | + |
| 32 | +# The image to encode, a CHW uint8 tensor. It could come from anywhere (e.g. a |
| 33 | +# model output); here we just decode one. |
| 34 | +image = decode_image(response.content) |
| 35 | + |
| 36 | + |
| 37 | +def plot(image: torch.Tensor): |
| 38 | + try: |
| 39 | + import matplotlib.pyplot as plt |
| 40 | + from torchvision.transforms.v2.functional import to_pil_image |
| 41 | + except ImportError: |
| 42 | + print("Cannot plot, please run `pip install torchvision matplotlib`") |
| 43 | + return |
| 44 | + |
| 45 | + pil_image = to_pil_image(image) |
| 46 | + fig = plt.figure(figsize=(pil_image.width / 100, pil_image.height / 100)) |
| 47 | + ax = fig.add_axes([0, 0, 1, 1]) |
| 48 | + ax.imshow(pil_image) |
| 49 | + ax.axis("off") |
| 50 | + |
| 51 | + |
| 52 | +# %% |
| 53 | +# .. _encoding_image: |
| 54 | +# |
| 55 | +# Encoding an image |
| 56 | +# ----------------- |
| 57 | +# |
| 58 | +# Encoders expect a 3D uint8 tensor in CHW layout (1 or 3 channels), which is |
| 59 | +# exactly what our image is: |
| 60 | +print(f"{image.shape = }, {image.dtype = }") |
| 61 | +plot(image) |
| 62 | + |
| 63 | +# %% |
| 64 | +# We instantiate a :class:`~torchcodec.encoders.JpegEncoder` with the image, and |
| 65 | +# encode it. Three destinations are supported: a file with |
| 66 | +# :meth:`~torchcodec.encoders.JpegEncoder.to_file`, a file-like object with |
| 67 | +# :meth:`~torchcodec.encoders.JpegEncoder.to_file_like`, or a 1D uint8 tensor of |
| 68 | +# raw bytes with :meth:`~torchcodec.encoders.JpegEncoder.to_tensor`. |
| 69 | +import io |
| 70 | + |
| 71 | +from torchcodec.encoders import JpegEncoder |
| 72 | + |
| 73 | +encoder = JpegEncoder(image) |
| 74 | + |
| 75 | +encoder.to_file("image.jpg") # to a file |
| 76 | +encoder.to_file_like(io.BytesIO()) # to a file-like object |
| 77 | +encoded = encoder.to_tensor() # to a tensor |
| 78 | + |
| 79 | +print(f"{encoded.shape = }, {encoded.dtype = }") |
| 80 | + |
| 81 | +# %% |
| 82 | +# That's it! We can decode the encoded bytes back to make sure everything worked: |
| 83 | +from torchcodec.decoders import decode_jpeg |
| 84 | + |
| 85 | +decoded = decode_jpeg(encoded) |
| 86 | +print(f"{decoded.shape = }") |
| 87 | +plot(decoded) |
| 88 | + |
| 89 | +# %% |
| 90 | +# :class:`~torchcodec.encoders.PngEncoder` works exactly the same way, and PNG is |
| 91 | +# lossless (unlike JPEG): |
| 92 | +from torchcodec.encoders import PngEncoder |
| 93 | + |
| 94 | +encoded = PngEncoder(image).to_tensor() |
| 95 | +print(f"{encoded.shape = }") |
| 96 | + |
| 97 | +# %% |
| 98 | +# Both encoders support encoding options: ``JpegEncoder`` takes a ``quality`` |
| 99 | +# (1-100), and ``PngEncoder`` takes a ``compression_level`` (0-9). For example, a |
| 100 | +# lower JPEG quality yields a smaller output: |
| 101 | +small = JpegEncoder(image).to_tensor(quality=10) |
| 102 | +large = JpegEncoder(image).to_tensor(quality=95) |
| 103 | +print(f"{small.numel() = }, {large.numel() = }") |
| 104 | + |
| 105 | +# %% |
| 106 | +# Encoding JPEGs on GPU |
| 107 | +# --------------------- |
| 108 | +# |
| 109 | +# ``JpegEncoder`` can encode directly on a CUDA device with nvJPEG: just pass it |
| 110 | +# an image that already lives on the GPU, and the encoding happens there. Only |
| 111 | +# 3-channel RGB images are supported on CUDA. With :meth:`to_tensor |
| 112 | +# <torchcodec.encoders.JpegEncoder.to_tensor>`, the encoded bytes stay on the GPU |
| 113 | +# (call ``.cpu()`` to bring them back to the host). |
| 114 | +# |
| 115 | +# .. code-block:: python |
| 116 | +# |
| 117 | +# from torchcodec.encoders import JpegEncoder |
| 118 | +# |
| 119 | +# encoded = JpegEncoder(image.cuda()).to_tensor() # encoded bytes on the GPU |
| 120 | +# # you can still use to_file and to_file_like, but the encoded bytes will |
| 121 | +# # be copied back to the CPU first. |
| 122 | +# |
| 123 | +# PNG encoding is CPU-only. |
| 124 | + |
| 125 | +# %% |
| 126 | +# Check the docstrings of the encoding methods to learn about the different |
| 127 | +# encoding options. |
| 128 | + |
| 129 | +# sphinx_gallery_thumbnail_path = '_static/thumbnails/cat_encoding.jpeg' |
0 commit comments