Python Forum
Image comparison, a more pythonic method
Thread Rating:
  • 0 Vote(s) - 0 Average
  • 1
  • 2
  • 3
  • 4
  • 5
Image comparison, a more pythonic method
#1
I'm comparing two screenshots to determine if a kiosk is frozen.
So both images will have the exactly the same size and structure which makes it an apples to apples comparison.
I'm just wondering if there is a faster method of comparison, or if there's an interesting pythonic method of achieving this goal.
import pyautogui
from PIL import Image
from time import sleep

pyautogui.screenshot('current_screen.png')
img_a_pixels = Image.open('current_screen.png').getdata()
#sleep(60) #Used in practice
pyautogui.screenshot('current_screen.png')
img_b_pixels = Image.open('current_screen.png').getdata()

difference = 0
for pixel_a, pixel_b in zip(img_a_pixels, img_b_pixels):
    if pixel_a != pixel_b:
        difference += 1
print(difference)
This returns an int telling how many pixels are different, an allowance of a few hundred has to be allotted for the clock, mouse, and blinking cursor.
Reply
#2
You can use numpy to do such comparison, e.g.

import numpy as np 
img_a_array = np.array(img_a_pixels)
img_b_array = np.array(img_b_pixels)
difference = (img_a_array == img_b_array).sum()
Also, you can use the threshold to specify colors similarity, e.g.

threshold = 2
difference_with_threshold = (np.abs(img_a_array - img_b_array) <= threshold).sum()
Reply
#3
(Jun-07-2018, 01:55 AM)scidam Wrote: You can use numpy to do such comparison, e.g.

import numpy as np 
img_a_array = np.array(img_a_pixels)
img_b_array = np.array(img_b_pixels)
difference = (img_a_array == img_b_array).sum()
Also, you can use the threshold to specify colors similarity, e.g.

threshold = 2
difference_with_threshold = (np.abs(img_a_array - img_b_array) <= threshold).sum()

Cool, I will do some speed comparisons with the numpy code that you provided. Thank you.
I use the threshold and comparison counter method for determining how much of an image is black or white.
Reply


Forum Jump:

User Panel Messages

Announcements
Announcement #1 8/1/2020
Announcement #2 8/2/2020
Announcement #3 8/6/2020