首页 > 解决方案 > 我如何使用 pil 在 python 中查看两个图像之间的区别?

问题描述

我正在尝试制作一个从我的 macbook 的相机(或任何相机)看的程序,并让我知道发生了什么事情(灯打开/关闭、任何动作等),该程序每 1 秒截取一次屏幕截图并比较最后一张照片是用刚刚拍的那张。

这是我的while循环中的代码

while True:
    time.sleep(1)

    image = capture_image()

    if last_image == None:
        last_image = image

    # compare the two images

    print('image', image)
    print('last image', last_image)
    print('')

    last_image = image

标签: pythonpython-imaging-library

解决方案


这是一个了解两张图片之间差异的示例。也许它可以解决您的问题。

from PIL import Image
from PIL import ImageChops
img1 = Image.open(yourPath)
img2 = Image.open(yourPath)
# make sure img1,img2 have the same picture width and height.
diff = ImageChops.difference(img1, img2)
diff.show()

在您的情况下,这可能有效。

from PIL import ImageChops
While True:
    time.sleep(1)

.......

    diff = ImageChops.difference(Now_Image,Last_Image)
    If diff.getbbox() is None:
        print("Now_Image and Last_Image are same.")    
    # diff.show()
    # or you can handle the diff picture.

图像将显示这些diff图片之间的差异。两张图片之间的差异会显示给您,并且相同的组件将是黑色的。


推荐阅读