【Python】对比2个文件夹下的图片差异,并生成对比图(PIL)

本文介绍了使用Python进行图片文件夹内图片差异比较的代码,适用于产品迭代中自动化截图的对比,检查UI自动化结果是否符合预期。
摘要由CSDN通过智能技术生成

Python图片处理-对比2个文件下图片的差异

功能

对比2个文件夹下的文件差异
如下图示例的2个文件夹,想要快速找出有差异的图片:
在这里插入图片描述

在这里插入图片描述

结果示例:
在这里插入图片描述

适用场景说明:

存在2个图片文件夹,满足:

  1. 文件夹下图片个数相同
  2. 文件夹下代表类似含义的图片顺序相同。(比如产生顺序、文件命名相同)

适用场景示例:产品迭代过程中,不同版本自动化跑出来的自动化截图。

代码

'''
功能:检查UI自动化结果,通过对比2个文件夹下的文件是否存在差异
'''
import os
from PIL import Image
import numpy as np
import time

#对比图片,file1是基础,file2是新结果
def compilePICfile(file1,file2,resultpicpath):
    #time_now = time.strftime ('%Y%m%d-%H%M%S', time.localtime ())
    img1=Image.open(file1)
    img2=Image.open(file2)
    array_img1=np.asanyarray(img1)
    array_img2 = np.asanyarray (img2)
    if (np.allclose(array_img1,array_img2)):
        result="PASS"
    else:
        result="Fail"
        new_width=img1.size[0]+img2.size[0]+20
        new_height = max (img1.size[1], img2.size[1])
        new_canvas=Image.new("RGB",(new_width,new_height))
        new_canvas.paste(img1,(0,0))
        new_canvas.paste(img2,(img1.size[0]+20,0))
        new_canvas.save(resultpicpath)
    return result

def myassert(basenurl,resulturl,compilepath):
    result='PASS'
    os.mkdir(compilepath)
    fileList_base=os.listdir (basenurl)
    fileList_result = os.listdir (resulturl)
    file_count = len ([name for name in fileList_base if os.path.isfile (os.path.join (basenurl, name))])
    for i in range(0,file_count):
        currentfile_base=basenurl+"/"+fileList_base[i]
        currentfile_result=resulturl+"/"+fileList_result[i]
        print("正在比对中\t"+currentfile_base+"\t\t"+currentfile_result)
        currentresult=compilePICfile(currentfile_base,currentfile_result,compilepath+"/"+fileList_base[i])
        if currentresult=="Fail":
            result="Fail"
            print("断言结果:有图片对比有差异,已保存差异拼接图片,请检查")
    return result

if __name__ == '__main__':
    baseurl='./result/PIC_00Base[SIT]'
    resulturl="./result/PIC_20240104-192634[SIT]"
    compileResultpath=resulturl+"_CompilePICResult"
    result = myassert (baseurl,resulturl,compileResultpath)
    print("结果是:"+result)

总结

不完善,待优化

  • 8
    点赞
  • 12
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值