简体   繁体   English

比较图像 Python PIL

[英]Compare images Python PIL

How can I compare two images?如何比较两张图片? I found Python's PIL library, but I do not really understand how it works.我找到了 Python 的 PIL 库,但我并不真正了解它是如何工作的。

To check does jpg files are exactly the same use pillow library:要检查 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")

based on Victor Ilyenko's answer, I needed to convert the images to RGB as PIL fails silently when the .png you're trying to compare contains a alpha channel.根据 Victor Ilyenko 的回答,我需要将图像转换为 RGB,因为当您尝试比较的 .png 包含 alpha 通道时,PIL 会静默失败。

image_one = Image.open(path_one).convert('RGB')
image_two = Image.open(path_two).convert('RGB')

It appears that Viktor's implementation can fail when the images are different sizes.当图像大小不同时,Viktor 的实现似乎会失败。

This version also compares alpha values.此版本还比较了 alpha 值。 Visually identical pixels are (I think) treated as identical, such as (0, 0, 0, 0) and (0, 255, 0, 0).视觉上相同的像素(我认为)被视为相同,例如 (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

Another implementation of Viktor 's answer using Pillow: Viktor使用 Pillow 回答的另一种实现:

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")

That did work for me, you just have to set the quantity of different pixels you accept, in my case 100, as the image diference was a complete black image but still had 25 diferent pixels.这对我有用,你只需要设置你接受的不同像素的数量,在我的例子中是 100,因为图像差异是一个完整的黑色图像,但仍然有 25 个不同的像素。 I tested other completelly diffferent images and they had diferrent pixels by thousands:我测试了其他完全不同的图像,它们的像素相差数千:

from PIL import ImageChops
if len(set(ImageChops.difference(img1, img2).getdata())) > 100:
    print("Both images are diffent!")

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM