用python對比兩張圖片的不同

來源:互聯網
上載者:User

標籤: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對比兩張圖片的不同

相關文章

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.