python實戰===用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

 

順便提一下

如果有任何問題,你可以在這里找到我 ,軟件測試交流qq群,209092584

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM