比较图像Python PIL

时间:2016-02-03 12:07:22

标签: python python-imaging-library

如何比较两张图片?我找到了Python的PIL库,但我真的不明白它是如何工作的。

4 个答案:

答案 0 :(得分:4)

根据Victor Ilyenko的回答,我需要将图像转换为RGB,因为当您要比较的.png包含Alpha通道时,PIL会无声地失败。

{{1}}

答案 1 :(得分:0)

要检查jpg文件是否与枕头库完全相同:

from PIL import Image
from PIL import ImageChops

image_one = Image.open(path_one)
image_two = Image.open(path_two)

diff = ImageChops.difference(image_one, image_two)

if diff.getbbox():
    print("images are different")
else:
    print("images are the same")

答案 2 :(得分:0)

当图像大小不同时,Viktor 的实现似乎会失败。

此版本还比较了 alpha 值。视觉上相同的像素(我认为)被视为相同,例如 (0, 0, 0, 0) 和 (0, 255, 0, 0)。

from PIL import ImageChops

def are_images_equal(img1, img2):
    equal_size = img1.height == img2.height and img1.width == img2.width

    if img1.mode == img2.mode == "RGBA":
        img1_alphas = [pixel[3] for pixel in img1.getdata()]
        img2_alphas = [pixel[3] for pixel in img2.getdata()]
        equal_alphas = img1_alphas == img2_alphas
    else:
        equal_alphas = True

    equal_content = not ImageChops.difference(
        img1.convert("RGB"), img2.convert("RGB")
    ).getbbox()

    return equal_size and equal_alphas and equal_content

答案 3 :(得分:0)

另一种使用 Pillow 实现 Viktor 的答案:

from PIL import Image

im1 = Image.open('image1.jpg')
im2 = Image.open('image2.jpg')

if list(im1.getdata()) == list(im2.getdata()):
    print("Identical")
else:
    print ("Different")