Skip to content

Commit a59c939

Browse files
authored
Add transparency and >8bits images support to AVIF decoder (#8613)
1 parent 4d6f0c0 commit a59c939

File tree

6 files changed

+122
-14
lines changed

6 files changed

+122
-14
lines changed

test/test_image.py

Lines changed: 60 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -928,5 +928,65 @@ def test_decode_avif(decode_fun, scripted):
928928
assert img[None].is_contiguous(memory_format=torch.channels_last)
929929

930930

931+
@pytest.mark.xfail(reason="AVIF support not enabled yet.")
932+
# Note: decode_image fails because some of these files have a (valid) signature
933+
# we don't recognize. We should probably use libmagic....
934+
# @pytest.mark.parametrize("decode_fun", (_decode_avif, decode_image))
935+
@pytest.mark.parametrize("decode_fun", (_decode_avif,))
936+
@pytest.mark.parametrize("scripted", (False, True))
937+
@pytest.mark.parametrize(
938+
"mode, pil_mode",
939+
(
940+
(ImageReadMode.RGB, "RGB"),
941+
(ImageReadMode.RGB_ALPHA, "RGBA"),
942+
(ImageReadMode.UNCHANGED, None),
943+
),
944+
)
945+
@pytest.mark.parametrize("filename", Path("/home/nicolashug/dev/libavif/tests/data/").glob("*.avif"))
946+
def test_decode_avif_against_pil(decode_fun, scripted, mode, pil_mode, filename):
947+
if "reversed_dimg_order" in str(filename):
948+
# Pillow properly decodes this one, but we don't (order of parts of the
949+
# image is wrong). This is due to a bug that was recently fixed in
950+
# libavif. Hopefully this test will end up passing soon with a new
951+
# libavif version https://github.com/AOMediaCodec/libavif/issues/2311
952+
pytest.xfail()
953+
import pillow_avif # noqa
954+
955+
encoded_bytes = read_file(filename)
956+
if scripted:
957+
decode_fun = torch.jit.script(decode_fun)
958+
try:
959+
img = decode_fun(encoded_bytes, mode=mode)
960+
except RuntimeError as e:
961+
if any(
962+
s in str(e)
963+
for s in ("BMFF parsing failed", "avifDecoderParse failed: ", "file contains more than one image")
964+
):
965+
pytest.skip(reason="Expected failure, that's OK")
966+
else:
967+
raise e
968+
assert img[None].is_contiguous(memory_format=torch.channels_last)
969+
if mode == ImageReadMode.RGB:
970+
assert img.shape[0] == 3
971+
if mode == ImageReadMode.RGB_ALPHA:
972+
assert img.shape[0] == 4
973+
if img.dtype == torch.uint16:
974+
img = F.to_dtype(img, dtype=torch.uint8, scale=True)
975+
976+
from_pil = F.pil_to_tensor(Image.open(filename).convert(pil_mode))
977+
if False:
978+
from torchvision.utils import make_grid
979+
980+
g = make_grid([img, from_pil])
981+
F.to_pil_image(g).save((f"/home/nicolashug/out_images/{filename.name}.{pil_mode}.png"))
982+
if mode != ImageReadMode.RGB:
983+
# We don't compare against PIL for RGB because results look pretty
984+
# different on RGBA images (other images are fine). The result on
985+
# torchvision basically just plainly ignores the alpha channel, resuting
986+
# in transparent pixels looking dark. PIL seems to be using a sort of
987+
# k-nn thing, looking at the output. Take a look at the resuting images.
988+
torch.testing.assert_close(img, from_pil, rtol=0, atol=3)
989+
990+
931991
if __name__ == "__main__":
932992
pytest.main([__file__])

torchvision/csrc/io/image/cpu/decode_avif.cpp

Lines changed: 33 additions & 10 deletions
Original file line numberDiff line numberDiff line change
@@ -8,7 +8,9 @@ namespace vision {
88
namespace image {
99

1010
#if !AVIF_FOUND
11-
torch::Tensor decode_avif(const torch::Tensor& data) {
11+
torch::Tensor decode_avif(
12+
const torch::Tensor& encoded_data,
13+
ImageReadMode mode) {
1214
TORCH_CHECK(
1315
false, "decode_avif: torchvision not compiled with libavif support");
1416
}
@@ -23,7 +25,9 @@ struct UniquePtrDeleter {
2325
};
2426
using DecoderPtr = std::unique_ptr<avifDecoder, UniquePtrDeleter>;
2527

26-
torch::Tensor decode_avif(const torch::Tensor& encoded_data) {
28+
torch::Tensor decode_avif(
29+
const torch::Tensor& encoded_data,
30+
ImageReadMode mode) {
2731
// This is based on
2832
// https://github.com/AOMediaCodec/libavif/blob/main/examples/avif_example_decode_memory.c
2933
// Refer there for more detail about what each function does, and which
@@ -58,24 +62,43 @@ torch::Tensor decode_avif(const torch::Tensor& encoded_data) {
5862
avifResultToString(result));
5963
TORCH_CHECK(
6064
decoder->imageCount == 1, "Avif file contains more than one image");
61-
TORCH_CHECK(
62-
decoder->image->depth <= 8,
63-
"avif images with bitdepth > 8 are not supported");
6465

6566
result = avifDecoderNextImage(decoder.get());
6667
TORCH_CHECK(
6768
result == AVIF_RESULT_OK,
6869
"avifDecoderNextImage failed:",
6970
avifResultToString(result));
7071

71-
auto out = torch::empty(
72-
{decoder->image->height, decoder->image->width, 3}, torch::kUInt8);
73-
7472
avifRGBImage rgb;
7573
memset(&rgb, 0, sizeof(rgb));
7674
avifRGBImageSetDefaults(&rgb, decoder->image);
77-
rgb.format = AVIF_RGB_FORMAT_RGB;
78-
rgb.pixels = out.data_ptr<uint8_t>();
75+
76+
// images encoded as 10 or 12 bits will be decoded as uint16. The rest are
77+
// decoded as uint8.
78+
auto use_uint8 = (decoder->image->depth <= 8);
79+
rgb.depth = use_uint8 ? 8 : 16;
80+
81+
if (mode != IMAGE_READ_MODE_UNCHANGED && mode != IMAGE_READ_MODE_RGB &&
82+
mode != IMAGE_READ_MODE_RGB_ALPHA) {
83+
// Other modes aren't supported, but we don't error or even warn because we
84+
// have generic entry points like decode_image which may support all modes,
85+
// it just depends on the underlying decoder.
86+
mode = IMAGE_READ_MODE_UNCHANGED;
87+
}
88+
89+
// If return_rgb is false it means we return rgba - nothing else.
90+
auto return_rgb =
91+
(mode == IMAGE_READ_MODE_RGB ||
92+
(mode == IMAGE_READ_MODE_UNCHANGED && !decoder->alphaPresent));
93+
94+
auto num_channels = return_rgb ? 3 : 4;
95+
rgb.format = return_rgb ? AVIF_RGB_FORMAT_RGB : AVIF_RGB_FORMAT_RGBA;
96+
rgb.ignoreAlpha = return_rgb ? AVIF_TRUE : AVIF_FALSE;
97+
98+
auto out = torch::empty(
99+
{rgb.height, rgb.width, num_channels},
100+
use_uint8 ? torch::kUInt8 : at::kUInt16);
101+
rgb.pixels = (uint8_t*)out.data_ptr();
79102
rgb.rowBytes = rgb.width * avifRGBImagePixelSize(&rgb);
80103

81104
result = avifImageYUVToRGB(decoder->image, &rgb);
Lines changed: 4 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1,11 +1,14 @@
11
#pragma once
22

33
#include <torch/types.h>
4+
#include "../image_read_mode.h"
45

56
namespace vision {
67
namespace image {
78

8-
C10_EXPORT torch::Tensor decode_avif(const torch::Tensor& data);
9+
C10_EXPORT torch::Tensor decode_avif(
10+
const torch::Tensor& encoded_data,
11+
ImageReadMode mode = IMAGE_READ_MODE_UNCHANGED);
912

1013
} // namespace image
1114
} // namespace vision

torchvision/csrc/io/image/cpu/decode_image.cpp

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -58,7 +58,7 @@ torch::Tensor decode_image(
5858
0x66, 0x74, 0x79, 0x70, 0x61, 0x76, 0x69, 0x66}; // == "ftypavif"
5959
TORCH_CHECK(data.numel() >= 12, err_msg);
6060
if ((memcmp(avif_signature, datap + 4, 8) == 0)) {
61-
return decode_avif(data);
61+
return decode_avif(data, mode);
6262
}
6363

6464
const uint8_t webp_signature_begin[4] = {0x52, 0x49, 0x46, 0x46}; // == "RIFF"

torchvision/csrc/io/image/image.cpp

Lines changed: 2 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -23,7 +23,8 @@ static auto registry =
2323
&decode_jpeg)
2424
.op("image::decode_webp(Tensor encoded_data, int mode) -> Tensor",
2525
&decode_webp)
26-
.op("image::decode_avif", &decode_avif)
26+
.op("image::decode_avif(Tensor encoded_data, int mode) -> Tensor",
27+
&decode_avif)
2728
.op("image::encode_jpeg", &encode_jpeg)
2829
.op("image::read_file", &read_file)
2930
.op("image::write_file", &write_file)

torchvision/io/image.py

Lines changed: 22 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -394,7 +394,28 @@ def decode_webp(
394394

395395
def _decode_avif(
396396
input: torch.Tensor,
397+
mode: ImageReadMode = ImageReadMode.UNCHANGED,
397398
) -> torch.Tensor:
399+
"""
400+
Decode an AVIF image into a 3 dimensional RGB[A] Tensor.
401+
402+
The values of the output tensor are in uint8 in [0, 255] for most images. If
403+
the image has a bit-depth of more than 8, then the output tensor is uint16
404+
in [0, 65535]. Since uint16 support is limited in pytorch, we recommend
405+
calling :func:`torchvision.transforms.v2.functional.to_dtype()` with
406+
``scale=True`` after this function to convert the decoded image into a uint8
407+
or float tensor.
408+
409+
Args:
410+
input (Tensor[1]): a one dimensional contiguous uint8 tensor containing
411+
the raw bytes of the AVIF image.
412+
mode (ImageReadMode): The read mode used for optionally
413+
converting the image color space. Default: ``ImageReadMode.UNCHANGED``.
414+
Other supported values are ``ImageReadMode.RGB`` and ``ImageReadMode.RGB_ALPHA``.
415+
416+
Returns:
417+
Decoded image (Tensor[image_channels, image_height, image_width])
418+
"""
398419
if not torch.jit.is_scripting() and not torch.jit.is_tracing():
399420
_log_api_usage_once(decode_webp)
400-
return torch.ops.image.decode_avif(input)
421+
return torch.ops.image.decode_avif(input, mode.value)

0 commit comments

Comments
 (0)