用python對比兩張圖片的不同
阿新 • • 發佈:2019-01-10
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庫的詳細文件: