【发布时间】:2021-07-15 04:20:05
【问题描述】:
问题看起来很简单,我在屏幕上有两个相似的图像,使用 pyautogui.LocateOnScreen() 可以正常定位第一张图像,使用 moveTo() 可以移动到有问题的图像。问题是我有不止一个图像,我希望它检测到第一个,然后移动到它,然后检测到另一个,最后移动到它。谁能帮我解决这个问题?谢谢。 PS:两张图是一样的
【问题讨论】:
问题看起来很简单,我在屏幕上有两个相似的图像,使用 pyautogui.LocateOnScreen() 可以正常定位第一张图像,使用 moveTo() 可以移动到有问题的图像。问题是我有不止一个图像,我希望它检测到第一个,然后移动到它,然后检测到另一个,最后移动到它。谁能帮我解决这个问题?谢谢。 PS:两张图是一样的
【问题讨论】:
提供一些代码的文本示例很棒。所以,我不必问这个愚蠢的问题。你试过“while”循环吗?
【讨论】:
使用pyautogui.locateAllOnScreen():
import pyautogui
image = 'TemplateImage.png'
for box in pyautogui.locateAllOnScreen(image):
print(pyautogui.center(box))
pyautogui.locateAllOnScreen() 返回一个 4 元组列表,表示模板所在区域周围的框的(左、上、宽、高)。为了找到这个盒子的中心,我们调用了pyautogui.center()
如果模板图像总是位于屏幕的同一部分,我们可以使用region 参数来限制pyautogui.LocateOnScreen() 搜索模板的位置。我们搜索了两次,每次都在不同的区域:
box1 = pyautogui.locateOnScreen('TemplateImage.png', region=(0,0, 300, 400))
center1 = pyautogui.center(box1)
box2 = pyautogui.locateOnScreen('TemplateImage.png', region=(300, 400, 300, 400))
center2 = pyautogui.center(box2)
使用 opencv-python 进行模板匹配。在屏幕截图中检测到您的模板图像后,您可以屏蔽检测到的区域并重新运行模板匹配:
import cv2
import pyscreeze
import pyautogui
import matplotlib.pyplot as plt
#load the image to find
image = 'TemplateImage.png'
templateim = pyscreeze._load_cv2(image,grayscale=False)
(w, h,_) = templateim.shape
# get screenshot
screenim_color = pyautogui.screenshot()
screenim_color = cv2.cvtColor(np.array(screenim_color),cv2.COLOR_RGB2BGR)
Nsearch = 2 # number of times to search
center_locations = [] #list to store locations
for k in range(Nsearch):
result = cv2.matchTemplate(screenim_color, templateim, cv2.TM_CCOEFF_NORMED) # template matching
(_, _, _, maxLoc) = cv2.minMaxLoc(result) # get the location where the correlation coefficient is maximum (This is the top-left tip of the box surrounding the template)
cv2.rectangle(screenim_color, maxLoc, (maxLoc[0] + h, maxLoc[1] + w), (0,0,255), -1) # mask the detected region by drawing a solid rectangle over it
center_loc = (int(maxLoc[0]+h/2),int(maxLoc[1]+w/2)) # get the center location
center_locations.append(center_loc) # append to list
plt.figure()
plt.imshow(screenim_color)
【讨论】: