如何在python中比较两个图像文件的内容?

2024-09-30 08:34:44 发布

您现在位置:Python中文网/ 问答频道 /正文

我想比较两个图像文件(.png),基本上读取两个.png文件,并断言内容是否相等。你知道吗

我在下面试过了

def read_file_contents(file1, file2):
     with open(file1, 'r', errors='ignore') as f:
        contents1 = f.readlines()
        f.close()
     with open(file1, 'r', errors='ignore') as f:
        contents2 = f.readlines()
        f.close()
     return {contents1, contents2}

如果两个内容相等,我就用

 assert contents1 == contents2

但这给了我一个错误。有人能帮我一下吗。谢谢。你知道吗


Tags: 文件内容closepngas图像文件with断言
3条回答

我不认为使用硒作为标签在这里是一个正确的选择,但w/e

图像可以也可以表示为一堆像素(基本上是数字),它们的排列方式使它们成为现实。 我们的想法是把这些数字和它们的排列方式结合起来,然后计算它们之间的距离,有多种方法可以像MSE一样做到这一点。 对于代码本身和进一步的解释,请查看下面的链接。你知道吗

https://www.pyimagesearch.com/2014/09/15/python-compare-two-images/

祝你好运伙计!(:

如果您只需要一个精确的匹配,您可以直接比较字节:

def validate_file_contents(file1, file2):
    with open(file1, 'rb', errors='ignore') as f1, open(file2, 'rb', errors='ignore') as f2:
        contents1 = f1.read()
        contents2 = f2.read()
    return contents1 == contents2     

如果需要,可以使用assert,但我个人会检查True/False条件。你知道吗

您的代码中也有一些错误:

  1. with块中的内容没有缩进。你知道吗
  2. with块中,您不需要close()文件。你知道吗
  3. 返回content1content2set,如果它们实际上相等,则只返回1项。您可能想要return (content1, content2)作为一个元组。你知道吗

有多种方法可以使用各种Python库来完成此任务,包括numpy&math、imagehash和pillow。你知道吗

这里有一种方法(我修改为只比较两个图像)。你知道吗

# This module is used to load images
from PIL import Image
# This module contains a number of arithmetical image operations
from PIL import ImageChops

def image_pixel_differences(base_image, compare_image):
  """
  Calculates the bounding box of the non-zero regions in the image.
  :param base_image: target image to find
  :param compare_image:  set of images containing the target image
  :return: The bounding box is returned as a 4-tuple defining the
           left, upper, right, and lower pixel coordinate. If the image
           is completely empty, this method returns None.
  """
  # Returns the absolute value of the pixel-by-pixel
  # difference between two images.

  diff = ImageChops.difference(base_image, compare_image)
  if diff.getbbox():
    return False
  else:
    return True

base_image = Image.open('image01.jpeg')
compare_image = Image.open('image02.jpeg')
results = image_pixel_differences (base_image, compare_image)

我有额外的例子,所以请让我知道,如果这个不适合你。你知道吗

相关问题 更多 >

    热门问题