【问题标题】:Compare images Python PIL比较图像 Python PIL
【发布时间】:2021-07-23 05:59:08
【问题描述】:

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

【问题讨论】:

  • 请详细说明您的问题:您要比较什么?你尝试了什么?
  • 好吧,这没有任何意义,这就是我问的原因。图像基本上是一个数组(2D 或 3D,取决于您是否使用 RGB/灰度),并且有多种方法可以比较 2 个图像:如果您需要查看它们是否相同,image1-image2 将为您提供信息。如果您需要找到 2 张图像之间的转换,那就是另一回事了。

标签: python python-imaging-library


【解决方案1】:

要检查 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】:

    根据 Victor Ilyenko 的回答,我需要将图像转换为 RGB,因为当您尝试比较的 .png 包含 alpha 通道时,PIL 会静默失败。

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

    【讨论】:

    • 这是否意味着一个带有 Alpha 通道的图像和另一个没有该通道的图像会被视为相同,即使它们不是?
    • 是的,这会将 Alpha 通道排除在比较之外。我建议使用 imagemagick:compare -metric AE $file1 $file2 /dev/null.
    【解决方案3】:

    Viktor's answer 使用 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")
    
    

    【讨论】:

      【解决方案4】:

      看起来,当图像大小不同时,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
      

      【讨论】:

        猜你喜欢
        • 2011-02-05
        • 1970-01-01
        • 1970-01-01
        • 2015-11-29
        • 2012-08-02
        • 1970-01-01
        • 2016-04-11
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多