Skip to content

Commit fcca6ff

Browse files
authored
Warn when webp is asked to decode into grayscale (#9101)
1 parent 904dad4 commit fcca6ff

File tree

2 files changed

+34
-0
lines changed

2 files changed

+34
-0
lines changed

test/test_image.py

Lines changed: 27 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1,4 +1,5 @@
11
import concurrent.futures
2+
import contextlib
23
import glob
34
import io
45
import os
@@ -934,6 +935,32 @@ def test_decode_webp(decode_fun, scripted):
934935
img += 123 # make sure image buffer wasn't freed by underlying decoding lib
935936

936937

938+
@pytest.mark.parametrize("decode_fun", (decode_webp, decode_image))
939+
def test_decode_webp_grayscale(decode_fun, capfd):
940+
encoded_bytes = read_file(next(get_images(FAKEDATA_DIR, ".webp")))
941+
942+
# We warn at the C++ layer because for decode_image(), we don't do the image
943+
# type dispatch until we get to the C++ version of decode_image(). We could
944+
# warn at the Python layer in decode_webp(), but then users would get a
945+
# double wanring: one from the Python layer and one from the C++ layer.
946+
#
947+
# Because we use the TORCH_WARN_ONCE macro, we need to do this dance to
948+
# temporarily always warn so we can test.
949+
@contextlib.contextmanager
950+
def set_always_warn():
951+
torch._C._set_warnAlways(True)
952+
yield
953+
torch._C._set_warnAlways(False)
954+
955+
with set_always_warn():
956+
img = decode_fun(encoded_bytes, mode=ImageReadMode.GRAY)
957+
assert "Webp does not support grayscale conversions" in capfd.readouterr().err
958+
959+
# Note that because we do not support grayscale conversions, we expect
960+
# that the number of color channels is still 3.
961+
assert img.shape == (3, 100, 100)
962+
963+
937964
# This test is skipped by default because it requires webp images that we're not
938965
# including within the repo. The test images were downloaded manually from the
939966
# different pages of https://developers.google.com/speed/webp/gallery

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

Lines changed: 7 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -33,6 +33,13 @@ torch::Tensor decode_webp(
3333
TORCH_CHECK(
3434
!features.has_animation, "Animated webp files are not supported.");
3535

36+
if (mode == IMAGE_READ_MODE_GRAY ||
37+
mode == IMAGE_READ_MODE_GRAY_ALPHA) {
38+
TORCH_WARN_ONCE(
39+
"Webp does not support grayscale conversions. "
40+
"The returned tensor will be in the colorspace of the original image.");
41+
}
42+
3643
auto return_rgb =
3744
should_this_return_rgb_or_rgba_let_me_know_in_the_comments_down_below_guys_see_you_in_the_next_video(
3845
mode, features.has_alpha);

0 commit comments

Comments
 (0)