Skip to content

Commit bdf354e

Browse files
authored
Add transparency support to webp decoder (#8610)
1 parent 4c5ae78 commit bdf354e

File tree

6 files changed

+84
-15
lines changed

6 files changed

+84
-15
lines changed

test/test_image.py

+26-1
Original file line numberDiff line numberDiff line change
@@ -875,7 +875,7 @@ def test_decode_gif_webp_errors(decode_fun):
875875
if decode_fun is decode_gif:
876876
expected_match = re.escape("DGifOpenFileName() failed - 103")
877877
elif decode_fun is decode_webp:
878-
expected_match = "WebPDecodeRGB failed."
878+
expected_match = "WebPGetFeatures failed."
879879
with pytest.raises(RuntimeError, match=expected_match):
880880
decode_fun(encoded_data)
881881

@@ -891,6 +891,31 @@ def test_decode_webp(decode_fun, scripted):
891891
assert img[None].is_contiguous(memory_format=torch.channels_last)
892892

893893

894+
# This test is skipped because it requires webp images that we're not including
895+
# within the repo. The test images were downloaded from the different pages of
896+
# https://developers.google.com/speed/webp/gallery
897+
# Note that converting an RGBA image to RGB leads to bad results because the
898+
# transparent pixels aren't necessarily set to "black" or "white", they can be
899+
# random stuff. This is consistent with PIL results.
900+
@pytest.mark.skip(reason="Need to download test images first")
901+
@pytest.mark.parametrize("decode_fun", (decode_webp, decode_image))
902+
@pytest.mark.parametrize("scripted", (False, True))
903+
@pytest.mark.parametrize(
904+
"mode, pil_mode", ((ImageReadMode.RGB, "RGB"), (ImageReadMode.RGB_ALPHA, "RGBA"), (ImageReadMode.UNCHANGED, None))
905+
)
906+
@pytest.mark.parametrize("filename", Path("/home/nicolashug/webp_samples").glob("*.webp"))
907+
def test_decode_webp_against_pil(decode_fun, scripted, mode, pil_mode, filename):
908+
encoded_bytes = read_file(filename)
909+
if scripted:
910+
decode_fun = torch.jit.script(decode_fun)
911+
img = decode_fun(encoded_bytes, mode=mode)
912+
assert img[None].is_contiguous(memory_format=torch.channels_last)
913+
914+
pil_img = Image.open(filename).convert(pil_mode)
915+
from_pil = F.pil_to_tensor(pil_img)
916+
assert_equal(img, from_pil)
917+
918+
894919
@pytest.mark.xfail(reason="AVIF support not enabled yet.")
895920
@pytest.mark.parametrize("decode_fun", (_decode_avif, decode_image))
896921
@pytest.mark.parametrize("scripted", (False, True))

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

+1-1
Original file line numberDiff line numberDiff line change
@@ -67,7 +67,7 @@ torch::Tensor decode_image(
6767
TORCH_CHECK(data.numel() >= 15, err_msg);
6868
if ((memcmp(webp_signature_begin, datap, 4) == 0) &&
6969
(memcmp(webp_signature_end, datap + 8, 7) == 0)) {
70-
return decode_webp(data);
70+
return decode_webp(data, mode);
7171
}
7272

7373
TORCH_CHECK(false, err_msg);

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

+39-7
Original file line numberDiff line numberDiff line change
@@ -8,13 +8,17 @@ namespace vision {
88
namespace image {
99

1010
#if !WEBP_FOUND
11-
torch::Tensor decode_webp(const torch::Tensor& data) {
11+
torch::Tensor decode_webp(
12+
const torch::Tensor& encoded_data,
13+
ImageReadMode mode) {
1214
TORCH_CHECK(
1315
false, "decode_webp: torchvision not compiled with libwebp support");
1416
}
1517
#else
1618

17-
torch::Tensor decode_webp(const torch::Tensor& encoded_data) {
19+
torch::Tensor decode_webp(
20+
const torch::Tensor& encoded_data,
21+
ImageReadMode mode) {
1822
TORCH_CHECK(encoded_data.is_contiguous(), "Input tensor must be contiguous.");
1923
TORCH_CHECK(
2024
encoded_data.dtype() == torch::kU8,
@@ -26,13 +30,41 @@ torch::Tensor decode_webp(const torch::Tensor& encoded_data) {
2630
encoded_data.dim(),
2731
" dims.");
2832

33+
auto encoded_data_p = encoded_data.data_ptr<uint8_t>();
34+
auto encoded_data_size = encoded_data.numel();
35+
36+
WebPBitstreamFeatures features;
37+
auto res = WebPGetFeatures(encoded_data_p, encoded_data_size, &features);
38+
TORCH_CHECK(
39+
res == VP8_STATUS_OK, "WebPGetFeatures failed with error code ", res);
40+
TORCH_CHECK(
41+
!features.has_animation, "Animated webp files are not supported.");
42+
43+
auto decoding_func = WebPDecodeRGB;
44+
int num_channels = 0;
45+
if (mode == IMAGE_READ_MODE_RGB) {
46+
decoding_func = WebPDecodeRGB;
47+
num_channels = 3;
48+
} else if (mode == IMAGE_READ_MODE_RGB_ALPHA) {
49+
decoding_func = WebPDecodeRGBA;
50+
num_channels = 4;
51+
} else {
52+
// Assume mode is "unchanged"
53+
decoding_func = features.has_alpha ? WebPDecodeRGBA : WebPDecodeRGB;
54+
num_channels = features.has_alpha ? 4 : 3;
55+
}
56+
2957
int width = 0;
3058
int height = 0;
31-
auto decoded_data = WebPDecodeRGB(
32-
encoded_data.data_ptr<uint8_t>(), encoded_data.numel(), &width, &height);
33-
TORCH_CHECK(decoded_data != nullptr, "WebPDecodeRGB failed.");
34-
auto out = torch::from_blob(decoded_data, {height, width, 3}, torch::kUInt8);
35-
return out.permute({2, 0, 1}); // return CHW, channels-last
59+
60+
auto decoded_data =
61+
decoding_func(encoded_data_p, encoded_data_size, &width, &height);
62+
TORCH_CHECK(decoded_data != nullptr, "WebPDecodeRGB[A] failed.");
63+
64+
auto out = torch::from_blob(
65+
decoded_data, {height, width, num_channels}, torch::kUInt8);
66+
67+
return out.permute({2, 0, 1});
3668
}
3769
#endif // WEBP_FOUND
3870

+4-1
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_webp(const torch::Tensor& data);
9+
C10_EXPORT torch::Tensor decode_webp(
10+
const torch::Tensor& encoded_data,
11+
ImageReadMode mode = IMAGE_READ_MODE_UNCHANGED);
912

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

torchvision/csrc/io/image/image.cpp

+2-1
Original file line numberDiff line numberDiff line change
@@ -21,7 +21,8 @@ static auto registry =
2121
.op("image::encode_png", &encode_png)
2222
.op("image::decode_jpeg(Tensor data, int mode, bool apply_exif_orientation=False) -> Tensor",
2323
&decode_jpeg)
24-
.op("image::decode_webp", &decode_webp)
24+
.op("image::decode_webp(Tensor encoded_data, int mode) -> Tensor",
25+
&decode_webp)
2526
.op("image::decode_avif", &decode_avif)
2627
.op("image::encode_jpeg", &encode_jpeg)
2728
.op("image::read_file", &read_file)

torchvision/io/image.py

+12-4
Original file line numberDiff line numberDiff line change
@@ -28,6 +28,11 @@ class ImageReadMode(Enum):
2828
``ImageReadMode.GRAY_ALPHA`` for grayscale with transparency,
2929
``ImageReadMode.RGB`` for RGB and ``ImageReadMode.RGB_ALPHA`` for
3030
RGB with transparency.
31+
32+
.. note::
33+
34+
Some decoders won't support all possible values, e.g. a decoder may only
35+
support "RGB" and "RGBA" mode.
3136
"""
3237

3338
UNCHANGED = 0
@@ -365,23 +370,26 @@ def decode_gif(input: torch.Tensor) -> torch.Tensor:
365370

366371
def decode_webp(
367372
input: torch.Tensor,
373+
mode: ImageReadMode = ImageReadMode.UNCHANGED,
368374
) -> torch.Tensor:
369375
"""
370-
Decode a WEBP image into a 3 dimensional RGB Tensor.
376+
Decode a WEBP image into a 3 dimensional RGB[A] Tensor.
371377
372-
The values of the output tensor are uint8 between 0 and 255. If the input
373-
image is RGBA, the transparency is ignored.
378+
The values of the output tensor are uint8 between 0 and 255.
374379
375380
Args:
376381
input (Tensor[1]): a one dimensional contiguous uint8 tensor containing
377382
the raw bytes of the WEBP image.
383+
mode (ImageReadMode): The read mode used for optionally
384+
converting the image color space. Default: ``ImageReadMode.UNCHANGED``.
385+
Other supported values are ``ImageReadMode.RGB`` and ``ImageReadMode.RGB_ALPHA``.
378386
379387
Returns:
380388
Decoded image (Tensor[image_channels, image_height, image_width])
381389
"""
382390
if not torch.jit.is_scripting() and not torch.jit.is_tracing():
383391
_log_api_usage_once(decode_webp)
384-
return torch.ops.image.decode_webp(input)
392+
return torch.ops.image.decode_webp(input, mode.value)
385393

386394

387395
def _decode_avif(

0 commit comments

Comments
 (0)