diff --git a/Tests/test_image_equality.py b/Tests/test_image_equality.py new file mode 100644 index 00000000000..45f2851cfb2 --- /dev/null +++ b/Tests/test_image_equality.py @@ -0,0 +1,118 @@ +from __future__ import annotations + +import pytest + +from PIL import Image + + +def _make_rows(size: tuple[int, int]) -> list[bytes]: + # Build test image data + return [ + bytes((y * (size[0] - 1) + x) % 256 for x in range(size[0])) + for y in range(size[1]) + ] + + +@pytest.mark.parametrize("mode", Image.MODES) +def test_equal(mode: str) -> None: + num_img_bytes = len(Image.new(mode, (2, 2)).tobytes()) + data = bytes(range(num_img_bytes)) + img_a = Image.frombytes(mode, (2, 2), data) + img_b = Image.frombytes(mode, (2, 2), data) + assert img_a.tobytes() == img_b.tobytes() + assert img_a == img_b + + +def test_equal_mode_1_nonzero_values() -> None: + # 1 mode pixels are either empty (0) or not (1-255) + img_a = Image.new("1", (1, 1), 1) + img_b = Image.new("1", (1, 1), 255) + assert img_a.tobytes() == img_b.tobytes() + assert img_a == img_b + + +@pytest.mark.parametrize("mode", Image.MODES) +def test_not_equal(mode: str) -> None: + num_img_bytes = len(Image.new(mode, (2, 2)).tobytes()) + if mode == "1": + data_a = bytes((0, 255)) + data_b = bytes((255, 0)) + else: + data_a = bytes(range(num_img_bytes)) + data_b = bytes(range(255, 255 - num_img_bytes, -1)) + img_a = Image.frombytes(mode, (2, 2), data_a) + img_b = Image.frombytes(mode, (2, 2), data_b) + assert img_a.tobytes() != img_b.tobytes() + assert img_a != img_b + + +@pytest.mark.parametrize("mode", ("RGB", "YCbCr", "HSV", "LAB")) +def test_equal_three_channels_four_bytes(mode: str) -> None: + color_a = 0x00B3B231 if mode == "LAB" else 0x00333231 + color_b = color_a | 0xFF000000 + + img_a = Image.new(mode, (1, 1), color_a) + img_b = Image.new(mode, (1, 1), color_b) + assert img_a.tobytes() == img_b.tobytes() == b"123" + assert img_a == img_b + + +@pytest.mark.parametrize("mode", ("LA", "La", "PA")) +def test_equal_two_channels_four_bytes(mode: str) -> None: + # Test that for LA/La/PA modes, where the data is stored in the 1st and 4th + # byte of each pixel, the middle bytes are ignored. + img_a = Image.new(mode, (1, 1), 0x32000031) + img_b = Image.new(mode, (1, 1), 0x32FFFF31) + assert img_a.tobytes() == img_b.tobytes() == b"12" + assert img_a == img_b + + +def test_types() -> None: + im = Image.new("L", (1, 1)) + assert im.im == im.im + assert im.im != 42 + + class EqMock: + eq_called = False + + def __eq__(self, other: object) -> bool: + self.eq_called = True + return True + + x = EqMock() + assert im.im == x + assert x.eq_called + + +def _make_palette_image(mode: str, data: bytes, rawmode: str) -> Image.Image: + im = Image.new(mode, (2, 2)) + im.putpalette(data, rawmode) + return im + + +@pytest.mark.parametrize("mode", ("P", "PA")) +def test_equal_palette(mode: str) -> None: + img_a = _make_palette_image(mode, b"\x01\x02\x03" * 256, "RGB") + img_b = _make_palette_image(mode, b"\x01\x02\x03" * 256, "RGB") + assert img_a == img_b + + img_a = _make_palette_image(mode, b"\x01\x02\x03\x80" * 256, "RGBA") + img_b = _make_palette_image(mode, b"\x01\x02\x03\x80" * 256, "RGBA") + assert img_a == img_b + + +@pytest.mark.parametrize("mode", ("P", "PA")) +def test_not_equal_palette_alpha(mode: str) -> None: + # Palettes that differ only in alpha are not equal. + img_a = _make_palette_image(mode, b"\x01\x02\x03\xff" * 256, "RGBA") + img_b = _make_palette_image(mode, b"\x01\x02\x03\x00" * 256, "RGBA") + assert img_a.getpalette() == img_b.getpalette() # implicit RGB rawmode + assert img_a.getpalette(None) != img_b.getpalette(None) + assert img_a != img_b + + # An RGB palette is not the same as an otherwise identical opaque RGBA palette + img_a = _make_palette_image(mode, b"\x01\x02\x03" * 256, "RGB") + img_b = _make_palette_image(mode, b"\x01\x02\x03\xff" * 256, "RGBA") + assert img_a.getpalette() == img_b.getpalette() # implicit RGB rawmode + assert img_a.getpalette(None) != img_b.getpalette(None) + assert img_a != img_b diff --git a/src/PIL/Image.py b/src/PIL/Image.py index be8e692f828..0c3cdb8bfbd 100644 --- a/src/PIL/Image.py +++ b/src/PIL/Image.py @@ -746,13 +746,17 @@ def __eq__(self, other: object) -> bool: if self.__class__ is not other.__class__: return False assert isinstance(other, Image) - return ( - self.mode == other.mode - and self.size == other.size - and self.info == other.info - and self.getpalette() == other.getpalette() - and self.tobytes() == other.tobytes() - ) + if self is other: + return True + if ( + self.mode != other.mode + or self.size != other.size + or self.info != other.info + ): + return False + self.load() + other.load() + return self.im == other.im def __repr__(self) -> str: return ( diff --git a/src/_imaging.c b/src/_imaging.c index 68b049d589c..36270cb0146 100644 --- a/src/_imaging.c +++ b/src/_imaging.c @@ -4527,6 +4527,158 @@ static PySequenceMethods image_as_sequence = { (ssizessizeobjargproc)NULL, /*sq_ass_slice*/ }; +/** + * Compare two pixel arrays in the given mode for equality. + * + * @param mode The mode of the pixel arrays. + * @param ysize The number of rows in the pixel arrays. + * @param linesize The number of bytes in each row of the pixel arrays. + * @param pixels_a Pointer to the first array of pixel row arrays. + * @param pixels_b Pointer to the second array of pixel row arrays. + * @return 0 if the pixel arrays are equal, 1 if they are not equal. + */ +static int +_compare_pixels( + const ModeID mode, + const int ysize, + const int linesize, + const char *const *pixels_a, + const char *const *pixels_b, + const UINT32 mask +) { + if (ysize <= 0 || linesize <= 0) { + // Pixel arrays without size are always equal + return 0; + } + + if (mode == IMAGING_MODE_1) { + // 1 mode pixels are either empty (0) or not (1-255), + // so compare the truthiness of each value + for (int y = 0; y < ysize; y++) { + const UINT8 *line_a = (const UINT8 *)pixels_a[y]; + const UINT8 *line_b = (const UINT8 *)pixels_b[y]; + // Check the first pixel separately; if it's different, + // we don't need to enter the loop at all. + if ((line_a[0] == 0) != (line_b[0] == 0)) { + return 1; + } + // Autovectorizable (see the masked loop below) + UINT8 diff = 0; + for (int x = 0; x < linesize; x++) { + diff |= (line_a[x] == 0) ^ (line_b[x] == 0); + } + if (diff) { + return 1; + } + } + return 0; + } + + if (mask == 0xffffffff) { + // We aren't masking anything + for (int y = 0; y < ysize; y++) { + if (memcmp(pixels_a[y], pixels_b[y], linesize)) { + return 1; + } + } + } else { + // All modes where we use a mask store four bytes per pixel. + const int xsize = linesize / 4; + for (int y = 0; y < ysize; y++) { + const UINT32 *line_a = (const UINT32 *)pixels_a[y]; + const UINT32 *line_b = (const UINT32 *)pixels_b[y]; + // Check the first pixel separately; if it's different, + // we don't need to enter the loop at all. + if ((line_a[0] ^ line_b[0]) & mask) { + return 1; + } + // Autovectorizable form: compute one row at a time, + // and OR together all the differences in that row, + // then see if we saw any differences at all. + // This loop will not bail out in the middle of a row (the common case of + // "entirely different images, same size and mode" + // will have been taken care of above in the first-pixel check), + // but regardless, it measures to be faster on modern CPUs. + UINT32 diff = 0; + for (int x = 0; x < xsize; x++) { + diff |= (line_a[x] ^ line_b[x]) & mask; + } + if (diff) { + return 1; + } + } + } + return 0; +} + +/** + * Compare two palettes for equality. + * + * @param a Pointer to the first palette. May be NULL. + * @param b Pointer to the second palette. May be NULL. + * @return 0 if the palettes are equal, 1 if they are not equal. + */ +static int +_compare_palette(const ImagingPalette a, const ImagingPalette b) { + if (a == NULL && b == NULL) { + return 0; + } + if (a == NULL || b == NULL || a->size != b->size || a->mode != b->mode) { + return 1; + } + + const char *a_data = (const char *)a->palette; + const char *b_data = (const char *)b->palette; + return _compare_pixels(a->mode, 1, a->size * 4, &a_data, &b_data, 0xffffffff); +} + +static PyObject * +image_richcompare(PyObject *self, PyObject *other, int op) { + if (op != Py_EQ && op != Py_NE) { + Py_RETURN_NOTIMPLEMENTED; + } + + if (!PyImaging_Check(other)) { + Py_RETURN_NOTIMPLEMENTED; + } + + const Imaging a = ((ImagingObject *)self)->image; + const Imaging b = ((ImagingObject *)other)->image; + + if (a == NULL || b == NULL) { + Py_RETURN_NOTIMPLEMENTED; + } + + if (a->mode != b->mode || a->xsize != b->xsize || a->ysize != b->ysize || + _compare_palette(a->palette, b->palette) != 0) { + return op == Py_EQ ? Py_False : Py_True; + } + + // All of the modes with padding bytes use four bytes for their pixels + UINT32 mask = 0xffffffff; + if (a->bands == 3) { + // Three channels in four bytes, so ignore the last byte +#ifdef WORDS_BIGENDIAN + mask = 0xffffff00; +#else + mask = 0x00ffffff; +#endif + } else if (a->bands == 2) { + // Two channels in four bytes, so ignore the middle two bytes + mask = 0xff0000ff; + } + + const int equal = _compare_pixels( + a->mode, + a->ysize, + a->linesize, + (const char *const *)a->image, + (const char *const *)b->image, + mask + ) == 0; + return PyBool_FromLong(op == Py_EQ ? equal : !equal); +} + /* type description */ static PyTypeObject Imaging_Type = { @@ -4534,6 +4686,7 @@ static PyTypeObject Imaging_Type = { .tp_basicsize = sizeof(ImagingObject), .tp_dealloc = (destructor)_dealloc, .tp_as_sequence = &image_as_sequence, + .tp_richcompare = image_richcompare, .tp_methods = methods, .tp_getset = getsetters, };