首先抱歉粘贴下面的长段代码。 这是我第一次真的不用担心应用程序的性能,所以我并不真的担心性能。 这段代码几乎在另一张图片中搜索一张图片,在我的计算机上运行需要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"))')