Search code examples
pythonpython-3.ximage-processingpython-imaging-library

Get True or False comparing images with Pillow


I made a code, who takes screenshots, and compares with a target image, when then are equal, it clicks on a specific place on the screen, but, the both images is equal but the program gets false always

The code:

import time
import pyautogui
from PIL import Image
from PIL import ImageChops

def wait(secs):
    time.sleep(secs)

def Screenshot_Taker(path, l, t, r, b):

    wait(2)

    image = pyautogui.screenshot()

    box = (l, t, r, b)

    image = image.crop(box)

    image.save(path, format = "png")


def Image_Compare_Click(Image1, Image2, l, t, r, b, x, y):

    image1 = Image.open(Image1).convert("RGB")
    image2 = Image.open(Image2).convert("RGB")

    while True:

        diff = ImageChops.difference(image1, image2)

        if diff.getbbox():
            print("Images are not the same")
            Screenshot_Taker(Image1, l, t, r, b)
            pyautogui.moveTo(x = 1365, y = 767)
            continue

        else:
            print("Images are the same")
            wait(1)
            pyautogui.click(x = x, y = y)
            wait(1)
            pyautogui.moveTo(x = 1365, y = 767)
            break

When I run:

Screenshot_Taker(path = "Image1.png",
l = 320, t = 550, r = 370, b = 610)

Image_Compare_Click(Image1 = "Image1.png", "Image2.png", 
l = 320, t = 550, r = 370, b = 610, x = 345, y = 580)

The output is:

Images are not the same
Images are not the same
Images are not the same
Images are not the same
Images are not the same

Solution

  • That's because you are comparing the same old two images. In your Image_Compare_Click, you need to do the following:

    def Image_Compare_Click(Image1, Image2, l, t, r, b, x, y):
    
        # image1 = Image.open(Image1).convert("RGB") # <-- commented this
        image2 = Image.open(Image2).convert("RGB")
    
        while True:
            image1 = Image.open(Image1).convert("RGB") #<-- added this
            diff = ImageChops.difference(image1, image2)
            ...