標籤:location font auto htm either -o 調用 org math
from PIL import Imagefrom 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 Imageimport mathimport operatorfrom functools import reducedef 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 resultif __name__ == ‘__main__‘: img1 = "./1.png" # 指定圖片路徑 img2 = "./2.png" result = image_contrast(img1,img2) print(result)
如果兩張圖片完全相等,則返回結果為浮點類型“0.0”,如果不相同則返回結果值越大。
同樣用上面兩張圖片,執行結果為38,還是比較小的:
image
這樣就可以在自動化測試案例中調用該方法來斷言執行結果。
關於Pillow庫的詳細文檔:
http://pillow.readthedocs.org/en/latest/index.html
用python對比兩張圖片的不同