首先抱歉粘貼下面的長段代碼。 這是我第一次真的不用擔心應用程序的性能,所以我並不真的擔心性能。 這段代碼幾乎在另一張圖片中搜索一張圖片,在我的計算機上運行需要30秒,將圖片轉換爲灰度,並且其他修改的時間爲15秒,我需要另外15張剃掉。我讀了一堆頁面,看了一些例子,但在代碼中找不到相同的問題。所以任何幫助將不勝感激。使用PIL優化代碼
從它的外觀(cProfile)在Image模塊中花了25秒,而在我的代碼中只花了5秒。
from PIL import Image
import os, ImageGrab, pdb, time, win32api, win32con
import cProfile
def GetImage(name):
name = name + '.bmp'
try:
print(os.path.join(os.getcwd(),"Images",name))
image = Image.open(os.path.join(os.getcwd(),"Images",name))
except:
print('error opening image;', name)
return image
def Find(name):
image = GetImage(name)
imagebbox = image.getbbox()
screen = ImageGrab.grab()
#screen = Image.open(os.path.join(os.getcwd(),"Images","Untitled.bmp"))
YLimit = screen.getbbox()[3] - imagebbox[3]
XLimit = screen.getbbox()[2] - imagebbox[2]
image = image.convert("L")
Screen = screen.convert("L")
Screen.load()
image.load()
#print(XLimit, YLimit)
Found = False
image = image.getdata()
for y in range(0,YLimit):
for x in range(0,XLimit):
BoxCoordinates = x, y, x+imagebbox[2], y+imagebbox[3]
ScreenGrab = screen.crop(BoxCoordinates)
ScreenGrab = ScreenGrab.getdata()
if image == ScreenGrab:
Found = True
#print("woop")
return x,y
if Found == False:
return "Not Found"
cProfile.run('print(Find("Login"))')