Pillow/Tests/test_image_access.py

464 lines
14 KiB
Python
Raw Normal View History

import os
import subprocess
import sys
2020-09-01 20:16:46 +03:00
import sysconfig
2014-01-05 22:41:25 +04:00
import pytest
2020-09-01 20:16:46 +03:00
from setuptools.command.build_ext import new_compiler
2014-06-10 13:10:47 +04:00
from PIL import Image
2020-03-02 17:02:19 +03:00
from .helper import assert_image_equal, hopper, is_win32, on_ci
2014-01-05 22:41:25 +04:00
# CFFI imports pycparser which doesn't support PYTHONOPTIMIZE=2
# https://github.com/eliben/pycparser/pull/198#issuecomment-317001670
if os.environ.get("PYTHONOPTIMIZE") == "2":
cffi = None
else:
try:
import cffi
2020-09-01 20:16:46 +03:00
from PIL import PyAccess
except ImportError:
cffi = None
try:
import numpy
except ImportError:
numpy = None
2018-03-03 12:54:00 +03:00
2020-03-02 17:02:19 +03:00
class AccessTest:
# initial value
_init_cffi_access = Image.USE_CFFI_ACCESS
_need_cffi_access = False
@classmethod
2020-03-04 13:31:50 +03:00
def setup_class(cls):
Image.USE_CFFI_ACCESS = cls._need_cffi_access
@classmethod
2020-03-04 13:31:50 +03:00
def teardown_class(cls):
Image.USE_CFFI_ACCESS = cls._init_cffi_access
class TestImagePutPixel(AccessTest):
def test_sanity(self):
im1 = hopper()
im2 = Image.new(im1.mode, im1.size, 0)
for y in range(im1.size[1]):
for x in range(im1.size[0]):
pos = x, y
im2.putpixel(pos, im1.getpixel(pos))
assert_image_equal(im1, im2)
im2 = Image.new(im1.mode, im1.size, 0)
im2.readonly = 1
for y in range(im1.size[1]):
for x in range(im1.size[0]):
pos = x, y
im2.putpixel(pos, im1.getpixel(pos))
assert not im2.readonly
assert_image_equal(im1, im2)
im2 = Image.new(im1.mode, im1.size, 0)
pix1 = im1.load()
pix2 = im2.load()
for x, y in ((0, "0"), ("0", 0)):
with pytest.raises(TypeError):
pix1[x, y]
for y in range(im1.size[1]):
for x in range(im1.size[0]):
pix2[x, y] = pix1[x, y]
assert_image_equal(im1, im2)
def test_sanity_negative_index(self):
im1 = hopper()
im2 = Image.new(im1.mode, im1.size, 0)
2018-10-15 14:06:08 +03:00
width, height = im1.size
assert im1.getpixel((0, 0)) == im1.getpixel((-width, -height))
assert im1.getpixel((-1, -1)) == im1.getpixel((width - 1, height - 1))
2019-06-13 18:54:24 +03:00
for y in range(-1, -im1.size[1] - 1, -1):
for x in range(-1, -im1.size[0] - 1, -1):
pos = x, y
im2.putpixel(pos, im1.getpixel(pos))
assert_image_equal(im1, im2)
im2 = Image.new(im1.mode, im1.size, 0)
im2.readonly = 1
2019-06-13 18:54:24 +03:00
for y in range(-1, -im1.size[1] - 1, -1):
for x in range(-1, -im1.size[0] - 1, -1):
pos = x, y
im2.putpixel(pos, im1.getpixel(pos))
assert not im2.readonly
assert_image_equal(im1, im2)
im2 = Image.new(im1.mode, im1.size, 0)
pix1 = im1.load()
pix2 = im2.load()
2019-06-13 18:54:24 +03:00
for y in range(-1, -im1.size[1] - 1, -1):
for x in range(-1, -im1.size[0] - 1, -1):
pix2[x, y] = pix1[x, y]
assert_image_equal(im1, im2)
@pytest.mark.skipif(numpy is None, reason="NumPy not installed")
def test_numpy(self):
im = hopper()
pix = im.load()
assert pix[numpy.int32(1), numpy.int32(2)] == (18, 20, 59)
class TestImageGetPixel(AccessTest):
@staticmethod
def color(mode):
bands = Image.getmodebands(mode)
if bands == 1:
return 1
else:
return tuple(range(1, bands + 1))
def check(self, mode, c=None):
if not c:
c = self.color(mode)
# check putpixel
im = Image.new(mode, (1, 1), None)
im.putpixel((0, 0), c)
assert (
im.getpixel((0, 0)) == c
), f"put/getpixel roundtrip failed for mode {mode}, color {c}"
# check putpixel negative index
im.putpixel((-1, -1), c)
assert (
im.getpixel((-1, -1)) == c
), f"put/getpixel roundtrip negative index failed for mode {mode}, color {c}"
# Check 0
im = Image.new(mode, (0, 0), None)
2022-03-03 14:10:19 +03:00
assert im.load() is not None
error = ValueError if self._need_cffi_access else IndexError
with pytest.raises(error):
im.putpixel((0, 0), c)
2022-03-03 14:10:19 +03:00
with pytest.raises(error):
im.getpixel((0, 0))
# Check 0 negative index
2022-03-03 14:10:19 +03:00
with pytest.raises(error):
im.putpixel((-1, -1), c)
2022-03-03 14:10:19 +03:00
with pytest.raises(error):
im.getpixel((-1, -1))
2017-03-01 12:20:18 +03:00
2016-10-02 13:31:53 +03:00
# check initial color
im = Image.new(mode, (1, 1), c)
assert (
im.getpixel((0, 0)) == c
), f"initial color failed for mode {mode}, color {c} "
# check initial color negative index
assert (
im.getpixel((-1, -1)) == c
), f"initial color failed with negative index for mode {mode}, color {c} "
# Check 0
im = Image.new(mode, (0, 0), c)
2022-03-03 14:10:19 +03:00
with pytest.raises(error):
im.getpixel((0, 0))
# Check 0 negative index
2022-03-03 14:10:19 +03:00
with pytest.raises(error):
im.getpixel((-1, -1))
2022-08-23 14:41:32 +03:00
@pytest.mark.parametrize(
"mode",
(
2019-06-13 18:54:24 +03:00
"1",
"L",
"LA",
"I",
"I;16",
"I;16B",
"F",
"P",
"PA",
"RGB",
"RGBA",
"RGBX",
"CMYK",
"YCbCr",
2022-08-23 14:41:32 +03:00
),
)
def test_basic(self, mode):
self.check(mode)
2022-08-23 14:41:32 +03:00
@pytest.mark.parametrize("mode", ("I;16", "I;16B"))
def test_signedness(self, mode):
# see https://github.com/python-pillow/Pillow/issues/452
# pixelaccess is using signed int* instead of uint*
2022-08-23 14:41:32 +03:00
self.check(mode, 2**15 - 1)
self.check(mode, 2**15)
self.check(mode, 2**15 + 1)
self.check(mode, 2**16 - 1)
2014-01-05 22:41:25 +04:00
@pytest.mark.parametrize("mode", ("P", "PA"))
2022-08-23 14:41:32 +03:00
@pytest.mark.parametrize("color", ((255, 0, 0), (255, 0, 0, 255)))
2022-08-31 13:56:38 +03:00
def test_p_putpixel_rgb_rgba(self, mode, color):
im = Image.new(mode, (1, 1))
2022-08-23 14:41:32 +03:00
im.putpixel((0, 0), color)
2022-08-31 13:56:38 +03:00
alpha = color[3] if len(color) == 4 and mode == "PA" else 255
assert im.convert("RGBA").getpixel((0, 0)) == (255, 0, 0, alpha)
2018-12-31 03:35:15 +03:00
2014-06-10 13:10:47 +04:00
2020-03-02 17:02:19 +03:00
@pytest.mark.skipif(cffi is None, reason="No CFFI")
2014-06-10 13:10:47 +04:00
class TestCffiPutPixel(TestImagePutPixel):
_need_cffi_access = True
2014-06-10 13:10:47 +04:00
2020-03-02 17:02:19 +03:00
@pytest.mark.skipif(cffi is None, reason="No CFFI")
2014-06-10 13:10:47 +04:00
class TestCffiGetPixel(TestImageGetPixel):
_need_cffi_access = True
2014-06-10 13:10:47 +04:00
2020-03-02 17:02:19 +03:00
@pytest.mark.skipif(cffi is None, reason="No CFFI")
class TestCffi(AccessTest):
_need_cffi_access = True
2014-06-10 13:10:47 +04:00
def _test_get_access(self, im):
2015-04-02 11:57:24 +03:00
"""Do we get the same thing as the old pixel access
2014-06-10 13:10:47 +04:00
2015-04-02 11:57:24 +03:00
Using private interfaces, forcing a capi access and
a pyaccess for the same image"""
2014-06-10 13:10:47 +04:00
caccess = im.im.pixel_access(False)
access = PyAccess.new(im, False)
w, h = im.size
for x in range(0, w, 10):
for y in range(0, h, 10):
assert access[(x, y)] == caccess[(x, y)]
2014-06-10 13:10:47 +04:00
2015-07-03 08:03:25 +03:00
# Access an out-of-range pixel
2020-02-22 19:07:04 +03:00
with pytest.raises(ValueError):
access[(access.xsize + 1, access.ysize + 1)]
2015-07-03 08:03:25 +03:00
2014-06-10 13:10:47 +04:00
def test_get_vs_c(self):
2019-06-13 18:54:24 +03:00
rgb = hopper("RGB")
2014-06-10 13:10:47 +04:00
rgb.load()
self._test_get_access(rgb)
2019-06-13 18:54:24 +03:00
self._test_get_access(hopper("RGBA"))
self._test_get_access(hopper("L"))
self._test_get_access(hopper("LA"))
self._test_get_access(hopper("1"))
self._test_get_access(hopper("P"))
2015-07-03 09:22:56 +03:00
# self._test_get_access(hopper('PA')) # PA -- how do I make a PA image?
2019-06-13 18:54:24 +03:00
self._test_get_access(hopper("F"))
2014-06-10 13:10:47 +04:00
2019-06-13 18:54:24 +03:00
im = Image.new("I;16", (10, 10), 40000)
2014-06-10 13:10:47 +04:00
self._test_get_access(im)
2019-06-13 18:54:24 +03:00
im = Image.new("I;16L", (10, 10), 40000)
2014-06-10 13:10:47 +04:00
self._test_get_access(im)
2019-06-13 18:54:24 +03:00
im = Image.new("I;16B", (10, 10), 40000)
2014-06-10 13:10:47 +04:00
self._test_get_access(im)
2019-06-13 18:54:24 +03:00
im = Image.new("I", (10, 10), 40000)
2014-06-10 13:10:47 +04:00
self._test_get_access(im)
# These don't actually appear to be modes that I can actually make,
# as unpack sets them directly into the I mode.
# im = Image.new('I;32L', (10, 10), -2**10)
# self._test_get_access(im)
# im = Image.new('I;32B', (10, 10), 2**10)
# self._test_get_access(im)
def _test_set_access(self, im, color):
2015-04-02 11:57:24 +03:00
"""Are we writing the correct bits into the image?
2014-06-10 13:10:47 +04:00
2015-04-02 11:57:24 +03:00
Using private interfaces, forcing a capi access and
a pyaccess for the same image"""
2014-06-10 13:10:47 +04:00
caccess = im.im.pixel_access(False)
access = PyAccess.new(im, False)
w, h = im.size
for x in range(0, w, 10):
for y in range(0, h, 10):
access[(x, y)] = color
assert color == caccess[(x, y)]
2014-06-10 13:10:47 +04:00
2015-07-03 08:03:25 +03:00
# Attempt to set the value on a read-only image
access = PyAccess.new(im, True)
with pytest.raises(ValueError):
2015-07-03 08:03:25 +03:00
access[(0, 0)] = color
2014-06-10 13:10:47 +04:00
def test_set_vs_c(self):
2019-06-13 18:54:24 +03:00
rgb = hopper("RGB")
2014-06-10 13:10:47 +04:00
rgb.load()
self._test_set_access(rgb, (255, 128, 0))
2019-06-13 18:54:24 +03:00
self._test_set_access(hopper("RGBA"), (255, 192, 128, 0))
self._test_set_access(hopper("L"), 128)
self._test_set_access(hopper("LA"), (128, 128))
self._test_set_access(hopper("1"), 255)
self._test_set_access(hopper("P"), 128)
2014-06-10 13:10:47 +04:00
# self._test_set_access(i, (128, 128)) #PA -- undone how to make
2019-06-13 18:54:24 +03:00
self._test_set_access(hopper("F"), 1024.0)
2014-06-10 13:10:47 +04:00
2019-06-13 18:54:24 +03:00
im = Image.new("I;16", (10, 10), 40000)
2014-06-10 13:10:47 +04:00
self._test_set_access(im, 45000)
2019-06-13 18:54:24 +03:00
im = Image.new("I;16L", (10, 10), 40000)
2014-06-10 13:10:47 +04:00
self._test_set_access(im, 45000)
2019-06-13 18:54:24 +03:00
im = Image.new("I;16B", (10, 10), 40000)
2014-06-10 13:10:47 +04:00
self._test_set_access(im, 45000)
2019-06-13 18:54:24 +03:00
im = Image.new("I", (10, 10), 40000)
2014-06-10 13:10:47 +04:00
self._test_set_access(im, 45000)
# im = Image.new('I;32L', (10, 10), -(2**10))
# self._test_set_access(im, -(2**13)+1)
# im = Image.new('I;32B', (10, 10), 2**10)
# self._test_set_access(im, 2**13-1)
2017-03-01 12:20:18 +03:00
def test_not_implemented(self):
assert PyAccess.new(hopper("BGR;15")) is None
2017-03-01 12:20:18 +03:00
2016-07-04 13:42:45 +03:00
# ref https://github.com/python-pillow/Pillow/pull/2009
def test_reference_counting(self):
size = 10
for _ in range(10):
# Do not save references to the image, only to the access object
2019-06-13 18:54:24 +03:00
px = Image.new("L", (size, 1), 0).load()
2016-07-04 13:42:45 +03:00
for i in range(size):
2016-08-13 05:32:13 +03:00
# pixels can contain garbage if image is released
assert px[i, 0] == 0
2016-07-04 13:42:45 +03:00
@pytest.mark.parametrize("mode", ("P", "PA"))
def test_p_putpixel_rgb_rgba(self, mode):
2022-10-10 03:46:33 +03:00
for color in ((255, 0, 0), (255, 0, 0, 127 if mode == "PA" else 255)):
im = Image.new(mode, (1, 1))
2018-12-31 05:37:04 +03:00
access = PyAccess.new(im, False)
access.putpixel((0, 0), color)
2022-10-10 03:46:33 +03:00
if len(color) == 3:
color += (255,)
assert im.convert("RGBA").getpixel((0, 0)) == color
2018-12-31 03:35:15 +03:00
2014-06-10 13:10:47 +04:00
class TestImagePutPixelError(AccessTest):
2020-09-22 06:06:52 +03:00
IMAGE_MODES1 = ["L", "LA", "RGB", "RGBA"]
IMAGE_MODES2 = ["I", "I;16", "BGR;15"]
INVALID_TYPES = ["foo", 1.0, None]
2020-08-21 00:16:19 +03:00
2020-09-22 06:06:52 +03:00
@pytest.mark.parametrize("mode", IMAGE_MODES1)
def test_putpixel_type_error1(self, mode):
2020-08-21 00:16:19 +03:00
im = hopper(mode)
for v in self.INVALID_TYPES:
2020-08-21 00:16:19 +03:00
with pytest.raises(TypeError, match="color must be int or tuple"):
im.putpixel((0, 0), v)
@pytest.mark.parametrize(
("mode", "band_numbers", "match"),
(
("L", (0, 2), "color must be int or single-element tuple"),
("LA", (0, 3), "color must be int, or tuple of one or two elements"),
(
"RGB",
(0, 2, 5),
"color must be int, or tuple of one, three or four elements",
),
),
)
def test_putpixel_invalid_number_of_bands(self, mode, band_numbers, match):
im = hopper(mode)
for band_number in band_numbers:
with pytest.raises(TypeError, match=match):
im.putpixel((0, 0), (0,) * band_number)
2020-09-22 06:06:52 +03:00
@pytest.mark.parametrize("mode", IMAGE_MODES2)
def test_putpixel_type_error2(self, mode):
im = hopper(mode)
for v in self.INVALID_TYPES:
with pytest.raises(
TypeError, match="color must be int or single-element tuple"
):
im.putpixel((0, 0), v)
@pytest.mark.parametrize("mode", IMAGE_MODES1 + IMAGE_MODES2)
2020-08-21 00:16:19 +03:00
def test_putpixel_overflow_error(self, mode):
im = hopper(mode)
with pytest.raises(OverflowError):
2022-03-04 08:42:24 +03:00
im.putpixel((0, 0), 2**80)
2020-08-21 00:16:19 +03:00
def test_putpixel_unrecognized_mode(self):
im = hopper("BGR;15")
with pytest.raises(ValueError, match="unrecognized image mode"):
im.putpixel((0, 0), 0)
2020-03-02 17:02:19 +03:00
class TestEmbeddable:
@pytest.mark.skipif(
2019-09-25 12:46:54 +03:00
not is_win32() or on_ci(),
2020-03-02 17:02:19 +03:00
reason="Failing on AppVeyor / GitHub Actions when run from subprocess, "
"not from shell",
2019-06-13 18:54:24 +03:00
)
def test_embeddable(self):
import ctypes
2019-06-13 18:54:24 +03:00
with open("embed_pil.c", "w") as fh:
fh.write(
"""
#include "Python.h"
int main(int argc, char* argv[])
{
2017-01-12 01:12:31 +03:00
char *home = "%s";
wchar_t *whome = Py_DecodeLocale(home, NULL);
Py_SetPythonHome(whome);
Py_InitializeEx(0);
Py_DECREF(PyImport_ImportModule("PIL.Image"));
Py_Finalize();
2017-01-12 01:12:31 +03:00
Py_InitializeEx(0);
Py_DECREF(PyImport_ImportModule("PIL.Image"));
Py_Finalize();
2017-01-12 01:12:31 +03:00
PyMem_RawFree(whome);
return 0;
2017-01-12 01:12:31 +03:00
}
2019-06-13 18:54:24 +03:00
"""
% sys.prefix.replace("\\", "\\\\")
)
2020-09-01 20:16:46 +03:00
compiler = new_compiler()
compiler.add_include_dir(sysconfig.get_config_var("INCLUDEPY"))
2020-09-01 20:16:46 +03:00
libdir = sysconfig.get_config_var("LIBDIR") or sysconfig.get_config_var(
"INCLUDEPY"
).replace("include", "libs")
2017-01-12 02:45:19 +03:00
compiler.add_library_dir(libdir)
2019-06-13 18:54:24 +03:00
objects = compiler.compile(["embed_pil.c"])
compiler.link_executable(objects, "embed_pil")
2017-01-12 02:45:19 +03:00
env = os.environ.copy()
2019-06-13 18:54:24 +03:00
env["PATH"] = sys.prefix + ";" + env["PATH"]
2017-01-12 01:12:31 +03:00
# do not display the Windows Error Reporting dialog
ctypes.windll.kernel32.SetErrorMode(0x0002)
2019-06-13 18:54:24 +03:00
process = subprocess.Popen(["embed_pil.exe"], env=env)
2017-01-12 01:12:31 +03:00
process.communicate()
assert process.returncode == 0