用python实现对比两张图片的不同

yipeiwu_com5年前Python基础

from PIL import Image
from PIL import ImageChops 
def compare_images(path_one, path_two, diff_save_location):
  """
  比较图片,如果有不同则生成展示不同的图片
  @参数一: path_one: 第一张图片的路径
  @参数二: path_two: 第二张图片的路径
  @参数三: diff_save_location: 不同图的保存路径
  """
  image_one = Image.open(path_one)
  image_two = Image.open(path_two)
  try: 
    diff = ImageChops.difference(image_one, image_two)
    if diff.getbbox() is None:
    # 图片间没有任何不同则直接退出
      print("【+】We are the same!")
    else:
      diff.save(diff_save_location)
  except ValueError as e:
    text = ("表示图片大小和box对应的宽度不一致,参考API说明:Pastes another image into this image."
        "The box argument is either a 2-tuple giving the upper left corner, a 4-tuple defining the left, upper, "
        "right, and lower pixel coordinate, or None (same as (0, 0)). If a 4-tuple is given, the size of the pasted "
        "image must match the size of the region.使用2纬的box避免上述问题")
    print("【{0}】{1}".format(e,text))
if __name__ == '__main__':
  compare_images('1.png',
          '2.png',
          '我们不一样.png')

执行结果:

第二种方法:

from PIL import Image
import math
import operator
from functools import reduce
def image_contrast(img1, img2):
  image1 = Image.open(img1)
  image2 = Image.open(img2)
  h1 = image1.histogram()
  h2 = image2.histogram()
  result = math.sqrt(reduce(operator.add, list(map(lambda a,b: (a-b)**2, h1, h2)))/len(h1) )
  return result
if __name__ == '__main__':
  img1 = "./1.png" # 指定图片路径
  img2 = "./2.png"
  result = image_contrast(img1,img2)
  print(result)

如果两张图片完全相等,则返回结果为浮点类型“0.0”,如果不相同则返回结果值越大。

同样用上面两张图片,执行结果为38,还是比较小的:

这样就可以在自动化测试用例中调用该方法来断言执行结果。

关于Pillow库的详细文档:

http://pillow.readthedocs.org/en/latest/index.html

总结

以上所述是小编给大家介绍的用python实现对比两张图片的不同,希望对大家有所帮助,如果大家有任何疑问请给我留言,小编会及时回复大家的。在此也非常感谢大家对【听图阁-专注于Python设计】网站的支持!

相关文章

Python中每次处理一个字符的5种方法

目的 对字符串的每个字符进行处理,其实每个字符(Char)就是一个长度为1的字符串。 方法 1.使用内建函数list() 复制代码 代码如下: >>> A_string...

用Python将Excel数据导入到SQL Server的例子

使用环境:Win10 x64 Python:3.6.4 SqlServer:2008R2     因为近期需要将excel导入到SQL Serve...

详解Python使用Plotly绘图工具,绘制甘特图

详解Python使用Plotly绘图工具,绘制甘特图

今天来讲一下如何使用Python 的绘图工具Plotly来绘制甘特图的方法 甘特图大家应该了解熟悉,就是通过条形来显示项目的进度、时间安排等相关情况的。 我们今天来学习一下,如何使用pl...

python编程嵌套函数实例代码

python,函数嵌套,到底是个什么东东? 很少有人用,但是,有时确实会用: def multiplier(factor): def multiplyByFactor(numb...

python多线程并发让两个LED同时亮的方法

python多线程并发让两个LED同时亮的方法

在做毕业设计的过程中,想对多个传感器让他们同时并发执行。之前想到 light_red() light_blue() 分别在两个shell脚本中同时运行,但是这样太麻烦了。后来学到了Pyt...