2017-08-08 134 views
0

我已經使用pyscreenshot在python中創建了一個程序,它週期性地截取了一個屏幕的特定區域,它將包含幾個預定義的圖像之一。我正在尋找從文件加載每個這些圖像到列表中,並將它們與屏幕截圖進行比較,以查看當前顯示哪些圖像。最初文件由screenshotting影像創建,因爲他們在屏幕上:如何比較pscreenshot中截取的屏幕截圖和保存的屏幕截圖?

while True: 

filenm = str(i) + ".png" 
im=ImageGrab.grab(bbox=(680,640,735,690)) #accross, down 
im.save(filenm) 
time.sleep(1) 
i = i + 1 

然後,當我試圖對它們進行比較總是報告錯誤:

image2 = Image.open("04.png") 

im=ImageGrab.grab(bbox=(680,640,735,690)) #accross, down 

if im == image2: 
    print "TRUE" 
else: 
    print "FALSE" 

但是比較兩個保存到文件中的圖像工作原理:

image = Image.open("03.png") 
image2 = Image.open("04.png") 

if image == image2: 
    print "TRUE" 
else: 
    print "FALSE" 

所以我的問題是如何做的影像會有所不同,一旦從文件加載,我怎麼能比較「活」的截圖從文件加載圖像?

回答

0

它看起來像當我使用ImageGrab.grab(),一個PIL.Image.Image對象被創建,其中Image.open()創建一個PIL.pngImagePlugin.PngImageFile對象。您不希望在實際對象上調用==,因爲在比較這兩種對象類型時,沒有爲PIL圖像實現特殊語義,因此它只是檢查它們是否是內存中的相同對象。代碼我會用正確的(使用numpy的)的比較兩個圖像看起來像

import numpy as np 
from PIL import Image 

def image_compare(image_1, image_2): 
    arr1 = np.array(image_1) 
    arr2 = np.array(image_2) 
    if arr1.shape != arr2.shape: 
     return False 
    maxdiff = np.max(np.abs(arr1 - arr2)) 
    return maxdiff == 0 

def image_compare_file(filename_1, filename_2): 
    im1 = Image.load(filename_1) 
    im2 = Image.load(filename_2) 
    return image_compare(im1, im2) 

下面我就PIL圖像的優勢,自動鑄造用np.array()到NumPy的ndarrays。然後檢查尺寸是否匹配,並計算絕對誤差的最大值。如果此最大值爲零,則圖像是相同的。現在,你可以只調用

if image_compare_file('file1.png','file2.png'): 
    pass # images in file are identical 
else: 
    pass # images differ 

if image_compare(image1,image2): 
    pass # images are identical 
else: 
    pass # images differ 
+0

這看起來接近我所需要的,但請記住,我不想加載兩個文件進行比較,因爲這需要每秒保存一個屏幕截圖並一遍又一遍地加載相同的比較文件。我需要使用PIL.Image.Image和PIL.pngImagePlugin.PngImageFile。 –

0

您可能會感興趣的使用感知差異工具可以讓你快速識別截圖差異。 imgdiff是一個爲Python封裝工具的庫。一個簡單的版本,大概可以用PIL的ImageChop實現,如在this answer

import Image 
import ImageChops 

im1 = Image.open("splash.png") 
im2 = Image.open("splash2.png") 

diff = ImageChops.difference(im2, im1) 

更多關於感性的版本比較,看看Bret Slatkin's talk about using it for safe continuous deployment

+0

聽起來不錯,但我怎麼知道這個答案呢?差異似乎包含另一個圖像。 –

+1

@GarethFrance它是一個圖像,但更有用的是將其視爲包含像素差異的二維數組。如果需要對Image對象進行一些計算,可以將Image對象轉換爲numpy ndarray。例如,如果'diff'中所有元素的總和爲0,那麼您知道這兩個圖像是完美匹配的像素。 – ahota