用python實現(xiàn)對比兩張圖片的不同
from PIL import Image from PIL import ImageChops def compare_images(path_one, path_two, diff_save_location): """ 比較圖片,如果有不同則生成展示不同的圖片 @參數(shù)一: path_one: 第一張圖片的路徑 @參數(shù)二: path_two: 第二張圖片的路徑 @參數(shù)三: 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')
執(zhí)行結(jié)果:
第二種方法:
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)
如果兩張圖片完全相等,則返回結(jié)果為浮點類型“0.0”,如果不相同則返回結(jié)果值越大。
同樣用上面兩張圖片,執(zhí)行結(jié)果為38,還是比較小的:
這樣就可以在自動化測試用例中調(diào)用該方法來斷言執(zhí)行結(jié)果。
關(guān)于Pillow庫的詳細文檔:
http://pillow.readthedocs.org/en/latest/index.html
總結(jié)
以上所述是小編給大家介紹的用python實現(xiàn)對比兩張圖片的不同,希望對大家有所幫助,如果大家有任何疑問請給我留言,小編會及時回復大家的。在此也非常感謝大家對腳本之家網(wǎng)站的支持!
- python通過opencv實現(xiàn)批量剪切圖片
- python實現(xiàn)圖片批量剪切示例
- python+opencv識別圖片中的圓形
- Python實現(xiàn)圖片尺寸縮放腳本
- python tensorflow學習之識別單張圖片的實現(xiàn)的示例
- Python實現(xiàn)識別手寫數(shù)字 Python圖片讀入與處理
- python使用Image處理圖片常用技巧分析
- python實現(xiàn)讀取并顯示圖片的兩種方法
- python實現(xiàn)識別相似圖片小結(jié)
- Python實現(xiàn)拼接多張圖片的方法
- Python+Opencv識別兩張相似圖片
- Ubuntu下使用Python實現(xiàn)游戲制作中的切分圖片功能
相關(guān)文章
django中使用POST方法獲取POST數(shù)據(jù)
這篇文章主要介紹了django中使用POST方法獲取POST數(shù)據(jù),文中通過示例代碼介紹的非常詳細,對大家的學習或者工作具有一定的參考學習價值,需要的朋友們下面隨著小編來一起學習學習吧2019-08-08Python稀疏矩陣及參數(shù)保存代碼實現(xiàn)
這篇文章主要介紹了Python稀疏矩陣及參數(shù)保存代碼實現(xiàn),文中通過示例代碼介紹的非常詳細,對大家的學習或者工作具有一定的參考學習價值,需要的朋友可以參考下2020-04-04淺談keras中的目標函數(shù)和優(yōu)化函數(shù)MSE用法
這篇文章主要介紹了淺談keras中的目標函數(shù)和優(yōu)化函數(shù)MSE用法,具有很好的參考價值,希望對大家有所幫助。一起跟隨小編過來看看吧2020-06-06Python中threading庫實現(xiàn)線程鎖與釋放鎖
threading用于提供線程相關(guān)的操作,為了保證安全的訪問一個資源對象,我們需要創(chuàng)建鎖。那么Python線程鎖與釋放鎖如何實現(xiàn),感興趣的小伙伴們可以參考一下2021-05-05Python3如何使用tabulate打印數(shù)據(jù)
這篇文章主要介紹了Python3如何使用tabulate打印數(shù)據(jù),文中通過示例代碼介紹的非常詳細,對大家的學習或者工作具有一定的參考學習價值,需要的朋友可以參考下2020-09-09