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')

執行結果:html

 

 

 

 

 



 

第二種方法:python

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,仍是比較小的:this

 

這樣就能夠在自動化測試用例中調用該方法來斷言執行結果。spa

關於Pillow庫的詳細文檔:3d

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

 

 

python 愛好者交流羣:810306356orm

相關文章
相關標籤/搜索