Pillow/Tests/test_file_jpeg2k.py

Ignoring revisions in .git-blame-ignore-revs. Click here to bypass and see the normal blame view.

467 lines
13 KiB
Python
Raw Normal View History

from __future__ import annotations
2024-01-20 14:23:03 +03:00
import os
2020-02-22 19:07:04 +03:00
import re
from io import BytesIO
from pathlib import Path
2024-02-07 11:16:28 +03:00
from typing import Any
2014-03-19 16:17:14 +04:00
import pytest
2023-01-31 14:31:52 +03:00
from PIL import (
Image,
ImageFile,
Jpeg2KImagePlugin,
UnidentifiedImageError,
_binary,
features,
)
from .helper import (
assert_image_equal,
assert_image_similar,
assert_image_similar_tofile,
skip_unless_feature,
2023-01-31 13:49:12 +03:00
skip_unless_feature_version,
)
2014-03-19 16:17:14 +04:00
EXTRA_DIR = "Tests/images/jpeg2000"
2020-03-02 17:02:19 +03:00
pytestmark = skip_unless_feature("jpg_2000")
2019-06-13 18:54:11 +03:00
test_card = Image.open("Tests/images/test-card.png")
2014-03-19 16:17:14 +04:00
test_card.load()
2014-06-10 13:10:47 +04:00
# OpenJPEG 2.0.0 outputs this debugging message sometimes; we should
# ignore it---it doesn't represent a test failure.
# 'Not enough memory to handle tile data'
2024-02-07 11:16:28 +03:00
def roundtrip(im: Image.Image, **options: Any) -> Image.Image:
2020-03-02 17:02:19 +03:00
out = BytesIO()
im.save(out, "JPEG2000", **options)
out.seek(0)
2021-11-25 15:16:07 +03:00
with Image.open(out) as im:
im.load()
2020-03-02 17:02:19 +03:00
return im
def test_sanity() -> None:
2020-03-02 17:02:19 +03:00
# Internal version number
2024-05-30 05:00:50 +03:00
version = features.version_codec("jpg_2000")
assert version is not None
assert re.search(r"\d+\.\d+\.\d+$", version)
2020-03-02 17:02:19 +03:00
with Image.open("Tests/images/test-card-lossless.jp2") as im:
px = im.load()
assert px[0, 0] == (0, 0, 0)
assert im.mode == "RGB"
assert im.size == (640, 480)
assert im.format == "JPEG2000"
assert im.get_format_mimetype() == "image/jp2"
def test_jpf() -> None:
2020-03-02 17:02:19 +03:00
with Image.open("Tests/images/balloon.jpf") as im:
assert im.format == "JPEG2000"
assert im.get_format_mimetype() == "image/jpx"
def test_invalid_file() -> None:
2020-03-02 17:02:19 +03:00
invalid_file = "Tests/images/flower.jpg"
with pytest.raises(SyntaxError):
Jpeg2KImagePlugin.Jpeg2KImageFile(invalid_file)
def test_bytesio() -> None:
2020-03-02 17:02:19 +03:00
with open("Tests/images/test-card-lossless.jp2", "rb") as f:
data = BytesIO(f.read())
2024-03-02 05:12:17 +03:00
with Image.open(data) as im:
im.load()
assert_image_similar(im, test_card, 1.0e-3)
2014-06-10 13:10:47 +04:00
2020-03-02 17:02:19 +03:00
# These two test pre-written JPEG 2000 files that were not written with
# PIL (they were made using Adobe Photoshop)
2014-06-10 13:10:47 +04:00
def test_lossless(tmp_path: Path) -> None:
2020-03-02 17:02:19 +03:00
with Image.open("Tests/images/test-card-lossless.jp2") as im:
im.load()
outfile = str(tmp_path / "temp_test-card.png")
im.save(outfile)
assert_image_similar(im, test_card, 1.0e-3)
def test_lossy_tiled() -> None:
assert_image_similar_tofile(
test_card, "Tests/images/test-card-lossy-tiled.jp2", 2.0
)
2014-06-10 13:10:47 +04:00
def test_lossless_rt() -> None:
2020-03-02 17:02:19 +03:00
im = roundtrip(test_card)
assert_image_equal(im, test_card)
2014-06-10 13:10:47 +04:00
2019-07-13 06:50:13 +03:00
def test_lossy_rt() -> None:
2020-03-02 17:02:19 +03:00
im = roundtrip(test_card, quality_layers=[20])
assert_image_similar(im, test_card, 2.0)
2014-06-10 13:10:47 +04:00
def test_tiled_rt() -> None:
2020-03-02 17:02:19 +03:00
im = roundtrip(test_card, tile_size=(128, 128))
assert_image_equal(im, test_card)
def test_tiled_offset_rt() -> None:
2020-03-02 17:02:19 +03:00
im = roundtrip(test_card, tile_size=(128, 128), tile_offset=(0, 0), offset=(32, 32))
assert_image_equal(im, test_card)
def test_tiled_offset_too_small() -> None:
2020-03-02 17:02:19 +03:00
with pytest.raises(ValueError):
roundtrip(test_card, tile_size=(128, 128), tile_offset=(0, 0), offset=(128, 32))
2014-06-10 13:10:47 +04:00
def test_irreversible_rt() -> None:
2020-03-02 17:02:19 +03:00
im = roundtrip(test_card, irreversible=True, quality_layers=[20])
assert_image_similar(im, test_card, 2.0)
def test_prog_qual_rt() -> None:
2020-03-02 17:02:19 +03:00
im = roundtrip(test_card, quality_layers=[60, 40, 20], progression="LRCP")
assert_image_similar(im, test_card, 2.0)
def test_prog_res_rt() -> None:
2020-03-02 17:02:19 +03:00
im = roundtrip(test_card, num_resolutions=8, progression="RLCP")
assert_image_equal(im, test_card)
2022-10-03 08:57:42 +03:00
@pytest.mark.parametrize("num_resolutions", range(2, 6))
2024-02-07 11:16:28 +03:00
def test_default_num_resolutions(num_resolutions: int) -> None:
2022-10-03 08:57:42 +03:00
d = 1 << (num_resolutions - 1)
im = test_card.resize((d - 1, d - 1))
with pytest.raises(OSError):
roundtrip(im, num_resolutions=num_resolutions)
reloaded = roundtrip(im)
assert_image_equal(im, reloaded)
def test_reduce() -> None:
2020-03-02 17:02:19 +03:00
with Image.open("Tests/images/test-card-lossless.jp2") as im:
2020-03-24 11:19:46 +03:00
assert callable(im.reduce)
2020-03-02 17:02:19 +03:00
im.reduce = 2
2020-03-24 11:19:46 +03:00
assert im.reduce == 2
2020-03-02 17:02:19 +03:00
im.load()
assert im.size == (160, 120)
2014-06-10 13:10:47 +04:00
2020-03-29 08:29:34 +03:00
im.thumbnail((40, 40))
assert im.size == (40, 30)
2020-03-24 11:19:46 +03:00
2020-03-02 17:02:19 +03:00
def test_load_dpi() -> None:
with Image.open("Tests/images/test-card-lossless.jp2") as im:
assert im.info["dpi"] == (71.9836, 71.9836)
with Image.open("Tests/images/zero_dpi.jp2") as im:
assert "dpi" not in im.info
def test_restricted_icc_profile() -> None:
ImageFile.LOAD_TRUNCATED_IMAGES = True
try:
# JPEG2000 image with a restricted ICC profile and a known colorspace
with Image.open("Tests/images/balloon_eciRGBv2_aware.jp2") as im:
assert im.mode == "RGB"
finally:
ImageFile.LOAD_TRUNCATED_IMAGES = False
def test_header_errors() -> None:
2021-08-01 12:01:43 +03:00
for path in (
"Tests/images/invalid_header_length.jp2",
"Tests/images/not_enough_data.jp2",
):
with pytest.raises(UnidentifiedImageError):
with Image.open(path):
pass
with pytest.raises(OSError):
with Image.open("Tests/images/expected_to_read.jp2"):
pass
def test_layers_type(tmp_path: Path) -> None:
2020-03-02 17:02:19 +03:00
outfile = str(tmp_path / "temp_layers.jp2")
for quality_layers in [[100, 50, 10], (100, 50, 10), None]:
test_card.save(outfile, quality_layers=quality_layers)
2024-02-07 11:16:28 +03:00
for quality_layers_str in ["quality_layers", ("100", "50", "10")]:
2020-03-02 17:02:19 +03:00
with pytest.raises(ValueError):
2024-02-07 11:16:28 +03:00
test_card.save(outfile, quality_layers=quality_layers_str)
2018-11-16 15:31:42 +03:00
def test_layers() -> None:
2020-03-02 17:02:19 +03:00
out = BytesIO()
test_card.save(out, "JPEG2000", quality_layers=[100, 50, 10], progression="LRCP")
out.seek(0)
with Image.open(out) as im:
im.layers = 1
im.load()
assert_image_similar(im, test_card, 13)
out.seek(0)
with Image.open(out) as im:
im.layers = 3
im.load()
assert_image_similar(im, test_card, 0.4)
2021-05-27 12:02:04 +03:00
@pytest.mark.parametrize(
"name, args, offset, data",
(
("foo.j2k", {}, 0, b"\xff\x4f"),
("foo.jp2", {}, 4, b"jP"),
(None, {"no_jp2": True}, 0, b"\xff\x4f"),
("foo.j2k", {"no_jp2": True}, 0, b"\xff\x4f"),
("foo.jp2", {"no_jp2": True}, 0, b"\xff\x4f"),
("foo.j2k", {"no_jp2": False}, 0, b"\xff\x4f"),
("foo.jp2", {"no_jp2": False}, 4, b"jP"),
("foo.jp2", {"no_jp2": False}, 4, b"jP"),
),
)
2024-02-07 11:16:28 +03:00
def test_no_jp2(name: str, args: dict[str, bool], offset: int, data: bytes) -> None:
2021-05-16 03:46:43 +03:00
out = BytesIO()
2021-05-27 12:02:04 +03:00
if name:
out.name = name
test_card.save(out, "JPEG2000", **args)
out.seek(offset)
assert out.read(2) == data
2021-05-16 03:46:43 +03:00
def test_mct() -> None:
# Three component
for val in (0, 1):
out = BytesIO()
2021-05-16 03:46:43 +03:00
test_card.save(out, "JPEG2000", mct=val, no_jp2=True)
assert out.getvalue()[59] == val
with Image.open(out) as im:
assert_image_similar(im, test_card, 1.0e-3)
2021-05-16 03:46:43 +03:00
# Single component should have MCT disabled
for val in (0, 1):
out = BytesIO()
with Image.open("Tests/images/16bit.cropped.jp2") as jp2:
2021-05-16 03:46:43 +03:00
jp2.save(out, "JPEG2000", mct=val, no_jp2=True)
assert out.getvalue()[53] == 0
with Image.open(out) as im:
assert_image_similar(im, jp2, 1.0e-3)
def test_sgnd(tmp_path: Path) -> None:
outfile = str(tmp_path / "temp.jp2")
im = Image.new("L", (1, 1))
im.save(outfile)
with Image.open(outfile) as reloaded:
assert reloaded.getpixel((0, 0)) == 0
im = Image.new("L", (1, 1))
im.save(outfile, signed=True)
with Image.open(outfile) as reloaded_signed:
assert reloaded_signed.getpixel((0, 0)) == 128
2023-07-22 13:00:42 +03:00
@pytest.mark.parametrize("ext", (".j2k", ".jp2"))
2024-02-07 11:16:28 +03:00
def test_rgba(ext: str) -> None:
2020-03-02 17:02:19 +03:00
# Arrange
2023-07-22 13:00:42 +03:00
with Image.open("Tests/images/rgb_trns_ycbc" + ext) as im:
# Act
im.load()
# Assert
assert im.mode == "RGBA"
2024-04-06 05:40:39 +03:00
@pytest.mark.skipif(
not os.path.exists(EXTRA_DIR), reason="Extra image files not installed"
)
@skip_unless_feature_version("jpg_2000", "2.5.1")
def test_cmyk() -> None:
with Image.open(f"{EXTRA_DIR}/issue205.jp2") as im:
assert im.mode == "CMYK"
assert im.getpixel((0, 0)) == (185, 134, 0, 0)
2022-10-03 08:57:42 +03:00
@pytest.mark.parametrize("ext", (".j2k", ".jp2"))
2024-02-07 11:16:28 +03:00
def test_16bit_monochrome_has_correct_mode(ext: str) -> None:
2022-10-03 08:57:42 +03:00
with Image.open("Tests/images/16bit.cropped" + ext) as im:
im.load()
assert im.mode == "I;16"
2020-03-02 17:02:19 +03:00
def test_16bit_monochrome_jp2_like_tiff() -> None:
2020-03-02 17:02:19 +03:00
with Image.open("Tests/images/16bit.cropped.tif") as tiff_16bit:
assert_image_similar_tofile(tiff_16bit, "Tests/images/16bit.cropped.jp2", 1e-3)
2020-03-02 17:02:19 +03:00
def test_16bit_monochrome_j2k_like_tiff() -> None:
2020-03-02 17:02:19 +03:00
with Image.open("Tests/images/16bit.cropped.tif") as tiff_16bit:
assert_image_similar_tofile(tiff_16bit, "Tests/images/16bit.cropped.j2k", 1e-3)
2020-03-02 17:02:19 +03:00
def test_16bit_j2k_roundtrips() -> None:
2020-03-02 17:02:19 +03:00
with Image.open("Tests/images/16bit.cropped.j2k") as j2k:
im = roundtrip(j2k)
assert_image_equal(im, j2k)
def test_16bit_jp2_roundtrips() -> None:
2020-03-02 17:02:19 +03:00
with Image.open("Tests/images/16bit.cropped.jp2") as jp2:
im = roundtrip(jp2)
assert_image_equal(im, jp2)
def test_issue_6194() -> None:
with Image.open("Tests/images/issue_6194.j2k") as im:
assert im.getpixel((5, 5)) == 31
def test_unbound_local() -> None:
2020-03-02 17:02:19 +03:00
# prepatch, a malformed jp2 file could cause an UnboundLocalError exception.
with pytest.raises(OSError):
2021-02-11 13:43:54 +03:00
with Image.open("Tests/images/unbound_variable.jp2"):
pass
2020-03-02 17:02:19 +03:00
def test_parser_feed() -> None:
2020-03-02 17:02:19 +03:00
# Arrange
with open("Tests/images/test-card-lossless.jp2", "rb") as f:
data = f.read()
# Act
p = ImageFile.Parser()
p.feed(data)
# Assert
2024-03-02 05:12:17 +03:00
assert p.image is not None
2020-03-02 17:02:19 +03:00
assert p.image.size == (640, 480)
@pytest.mark.skipif(
not os.path.exists(EXTRA_DIR), reason="Extra image files not installed"
)
@pytest.mark.parametrize("name", ("subsampling_1", "subsampling_2", "zoo1", "zoo2"))
2024-02-07 11:16:28 +03:00
def test_subsampling_decode(name: str) -> None:
test = f"{EXTRA_DIR}/{name}.jp2"
reference = f"{EXTRA_DIR}/{name}.ppm"
with Image.open(test) as im:
2024-02-07 11:16:28 +03:00
epsilon = 3.0 # for YCbCr images
with Image.open(reference) as im2:
width, height = im2.size
if name[-1] == "2":
# RGB reference images are downscaled
epsilon = 3e-3
width, height = width * 2, height * 2
2022-01-15 01:02:31 +03:00
expected = im2.resize((width, height), Image.Resampling.NEAREST)
assert_image_similar(im, expected, epsilon)
2024-03-12 11:30:23 +03:00
@pytest.mark.skipif(
not os.path.exists(EXTRA_DIR), reason="Extra image files not installed"
)
def test_pclr() -> None:
with Image.open(f"{EXTRA_DIR}/issue104_jpxstream.jp2") as im:
assert im.mode == "P"
assert len(im.palette.colors) == 256
assert im.palette.colors[(255, 255, 255)] == 0
def test_comment() -> None:
2023-03-09 05:36:22 +03:00
with Image.open("Tests/images/comment.jp2") as im:
assert im.info["comment"] == b"Created by OpenJPEG version 2.5.0"
# Test an image that is truncated partway through a codestream
with open("Tests/images/comment.jp2", "rb") as fp:
b = BytesIO(fp.read(130))
with Image.open(b) as im:
pass
def test_save_comment() -> None:
2023-03-24 01:45:51 +03:00
for comment in ("Created by Pillow", b"Created by Pillow"):
out = BytesIO()
test_card.save(out, "JPEG2000", comment=comment)
2023-03-24 01:45:51 +03:00
with Image.open(out) as im:
assert im.info["comment"] == b"Created by Pillow"
out = BytesIO()
long_comment = b" " * 65531
test_card.save(out, "JPEG2000", comment=long_comment)
with Image.open(out) as im:
assert im.info["comment"] == long_comment
with pytest.raises(ValueError):
test_card.save(out, "JPEG2000", comment=long_comment + b" ")
@pytest.mark.parametrize(
"test_file",
[
"Tests/images/crash-4fb027452e6988530aa5dabee76eecacb3b79f8a.j2k",
"Tests/images/crash-7d4c83eb92150fb8f1653a697703ae06ae7c4998.j2k",
"Tests/images/crash-ccca68ff40171fdae983d924e127a721cab2bd50.j2k",
"Tests/images/crash-d2c93af851d3ab9a19e34503626368b2ecde9c03.j2k",
],
)
2024-02-07 11:16:28 +03:00
def test_crashes(test_file: str) -> None:
with open(test_file, "rb") as f:
with Image.open(f) as im:
# Valgrind should not complain here
2021-04-03 01:34:56 +03:00
try:
im.load()
except OSError:
pass
2023-01-31 13:49:12 +03:00
@skip_unless_feature_version("jpg_2000", "2.4.0")
def test_plt_marker() -> None:
# Search the start of the codesteam for PLT
2023-01-31 13:49:12 +03:00
out = BytesIO()
2023-03-27 14:38:29 +03:00
test_card.save(out, "JPEG2000", no_jp2=True, plt=True)
2023-01-31 13:49:12 +03:00
out.seek(0)
while True:
marker = out.read(2)
if not marker:
pytest.fail("End of stream without PLT")
2023-01-31 13:49:12 +03:00
jp2_boxid = _binary.i16be(marker)
2023-01-31 13:49:12 +03:00
if jp2_boxid == 0xFF4F:
# SOC has no length
2023-01-31 13:49:12 +03:00
continue
elif jp2_boxid == 0xFF58:
# PLT
2023-01-31 13:49:12 +03:00
return
elif jp2_boxid == 0xFF93:
pytest.fail("SOD without finding PLT first")
2023-01-31 13:49:12 +03:00
hdr = out.read(2)
length = _binary.i16be(hdr)
out.seek(length - 2, os.SEEK_CUR)
2024-06-18 16:03:03 +03:00
def test_9bit() -> None:
with Image.open("Tests/images/9bit.j2k") as im:
assert im.mode == "I;16"
assert im.size == (128, 128)