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 爱好者交流群:810306356

最新文章

  1. Java Web技术之Cookie
  2. 转换一个矩阵(2维数组)为HTML Table
  3. Makefile目标,伪目标,头文件自动依赖
  4. BZOJ4521: [Cqoi2016]手机号码
  5. ehcache入门
  6. java list<int>报错
  7. VMware中安装CentOS7网络配置静态IP地址,常用配置和工具安装
  8. java泛型接口详解
  9. Android零点一度的区别——Matrix
  10. Java learning notes (1):Basic Knowlege points
  11. 掌握SQLServer锁的相关概念
  12. CentOS 7.X 安全手记
  13. Sqlautocode使用过程的一些坑
  14. 十、K3 WISE 开发插件《SQL Profiler跟踪单据操作时产生的SQL语句》
  15. HTML Tags
  16. Js_cookie保存登录名
  17. Android Studio发布Release版本之坑--Unknown host 'd29vzk4ow07wi7.cloudfront.net'
  18. Java从网络批量读取图片并保存至本网站服务器后再插入文章中
  19. Lonely(非洲NANA作品)
  20. MYSQL指定用户访问指定数据库

热门文章

  1. JAVA开发工作流程
  2. BZOJ 1818 内部白点(离散化+树状数组)
  3. BZOJ 1452 Count(二维树状数组)
  4. 【bzoj2654】tree 二分+Kruscal
  5. 前端基础:JavaScript BOM对象
  6. CSS3 transform rotate(旋转)锯齿/元素抖动模糊的解决办法
  7. [SOJ #48]集合对称差卷积
  8. [SCOI2008]天平 差分约束
  9. mmc驱动的读写过程解析
  10. MongoDB基操