我想在屏幕上进行一些模式识别,并将使用 Quartz/PyObjc 库来获取屏幕截图。
我得到的屏幕截图是 CGImage。我想使用 openCV 库搜索其中的模式,但似乎找不到如何将数据转换为 opencv 可读的。
所以我想做的是:
#get screenshot and reference pattern
img = getScreenshot() # returns CGImage instance, custom function, using Quartz
reference = cv2.imread('ref/reference_start.png') #get the reference pattern
#search for the pattern using the opencv library
result = cv2.matchTemplate(screen, reference, cv2.TM_CCOEFF_NORMED)
#this is what I need
minVal,maxVal,minLoc,maxLoc = cv2.minMaxLoc(result)
我不知道如何做到这一点,也无法通过谷歌找到信息。
要添加到 Arqu 的答案中,如果您的最终目标是使用 opencv 或 numpy,您可能会发现使用 np.frombuffer 而不是首先创建 PIL 图像更快,因为 np.frombuffer 与 Image.frombuffer 花费的时间大约相同,但节省了时间从图像转换为 numpy 数组的步骤(在我的机器上大约需要 100 毫秒(其他所有操作大约需要 50 毫秒))。
import Quartz.CoreGraphics as CG
from PIL import Image
import time
import numpy as np
ct = time.time()
region = CG.CGRectInfinite
# Create screenshot as CGImage
image = CG.CGWindowListCreateImage(
region,
CG.kCGWindowListOptionOnScreenOnly,
CG.kCGNullWindowID,
CG.kCGWindowImageDefault)
width = CG.CGImageGetWidth(image)
height = CG.CGImageGetHeight(image)
bytesperrow = CG.CGImageGetBytesPerRow(image)
pixeldata = CG.CGDataProviderCopyData(CG.CGImageGetDataProvider(image))
image = np.frombuffer(pixeldata, dtype=np.uint8)
image = image.reshape((height, bytesperrow//4, 4))
image = image[:,:width,:]
print('elapsed:', time.time() - ct)
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)