Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
23 changes: 23 additions & 0 deletions Tests/test_compare_images.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,23 @@
from __future__ import annotations

from PIL import Image, ImageChops


def test_compare_identical_images():
im1 = Image.new("RGB", (10, 10), "red")
im2 = Image.new("RGB", (10, 10), "red")

result = ImageChops.compare_images(im1, im2)

assert result["different_pixels"] == 0
assert result["percent_difference"] == 0.0


def test_compare_different_images():
im1 = Image.new("RGB", (10, 10), "red")
im2 = Image.new("RGB", (10, 10), "blue")

result = ImageChops.compare_images(im1, im2)

assert result["different_pixels"] > 0
assert result["percent_difference"] > 0.0
38 changes: 38 additions & 0 deletions src/PIL/ImageChops.py
Original file line number Diff line number Diff line change
Expand Up @@ -293,6 +293,44 @@ def composite(
return Image.composite(image1, image2, mask)


def compare_images(image1, image2):
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Suggested change
def compare_images(image1, image2):
def compare_images(image1: Image.Image, image2: Image.Image) -> dict[str, float]:

"""
Compare two images pixel by pixel.

:param image1: The first image.
:param image2: The second image.
:returns: A dictionary containing:

- ``different_pixels`` – the number of pixels that differ
- ``percent_difference`` – the percentage of differing pixels

:raises ValueError: If the images have different sizes or modes.
"""
if image1.mode != image2.mode:
raise ValueError("Images must have the same mode")
if image1.size != image2.size:
raise ValueError("Images must have the same size")

# Use ImageChops.difference to detect pixel differences
diff = difference(image1, image2).convert("L")

# If identical, diff is entirely zero
if diff.getbbox() is None:
return {
"different_pixels": 0,
"percent_difference": 0.0,
}

# Count non-zero (different) pixels
nonzero = sum(1 for px in diff.getdata() if px != 0)
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Suggested change
nonzero = sum(1 for px in diff.getdata() if px != 0)
nonzero = sum(1 for px in tuple(diff.getdata()) if px != 0)

Another type hint.

total = image1.size[0] * image1.size[1]

return {
"different_pixels": nonzero,
"percent_difference": nonzero * 100.0 / total,
}


def offset(image: Image.Image, xoffset: int, yoffset: int | None = None) -> Image.Image:
"""Returns a copy of the image where data has been offset by the given
distances. Data wraps around the edges. If ``yoffset`` is omitted, it
Expand Down
Loading