我怎样才能使这个 while True 循环运行得更快并正常工作?它检测屏幕上是否存在 3 个不需要的项目,当消失时,触发警报

问题描述 投票:0回答:1

我用了一段时间的 True 循环来搜索三个不同图像的存在。如果检测到这三个中的任何一个,则按下“空格”以搜索另一个应用程序。如果发现一个应用程序没有这三个图像中的任何一个,循环就会被打破,并触发警报通知用户有工作要做。

我遇到的问题是,我认为 pyautogui 检测到图像在按下 enter 后立即消失,并且下一个应用程序正在我的浏览器中加载,当它加载时,什么也没有,它是一个空白页面。加载下一个应用程序只需要几分之一秒。当下一个加载时,通常会出现 3 个图像中的 1 个,但循环已经过早中断。

这是循环:

while True:
    pyautogui.press("space")
    img = pyautogui.locateOnScreen("ffd1.PNG", confidence=0.7)
    img = pyautogui.locateOnScreen("ffd2.PNG", confidence=0.7)
    img = pyautogui.locateOnScreen("ffd3.PNG", confidence=0.7)
    if img == None:
        ctypes.windll.user32.MessageBoxW(0, "There's work to be done!!", "There's work to be done!!", 0x1000)
        break

有更好的方法吗?我希望它快速按下“空格键”,同时搜索缺少的图像。我尝试在其中添加一个 time.sleep(.5) ,但它根本没有帮助。循环仍然在加载屏幕之间中断。 :|

有人指出我只搜索一张图片。我在这里修好了...它仍然很慢。

while True:
    img = pyautogui.locateOnScreen("ffd1.PNG", confidence=0.7)
    if img == None and img2 == None and img3 == None:
        ctypes.windll.user32.MessageBoxW(0, "There's work to be done!!", "There's work to be done!!", 0x1000)
        break
    img2 = pyautogui.locateOnScreen("ffd2.PNG", confidence=0.7)
    if img == None and img2 == None and img3 == None:
        ctypes.windll.user32.MessageBoxW(0, "There's work to be done!!", "There's work to be done!!", 0x1000)
        break
    img3 = pyautogui.locateOnScreen("ffd3.PNG", confidence=0.7)
    if img == None and img2 == None and img3 == None:
        ctypes.windll.user32.MessageBoxW(0, "There's work to be done!!", "There's work to be done!!", 0x1000)
        break
    pyautogui.press("space")
    

尝试使用 opencv 重写,但它总是无缘无故地崩溃

img = cv2.imread('ffd1.PNG')
image_detected = False

while True:
    screenshot = pyautogui.screenshot()
    screenshot = np.array(screenshot)
    screenshot = cv2.cvtColor(screenshot, cv2.COLOR_RGB2BGR)
    
    res = cv2.matchTemplate(screenshot, img, cv2.TM_CCOEFF_NORMED)
    threshold = 0.8
    loc = np.where(res >= threshold)
    
    if np.any(loc) and not image_detected:
        print("Image detected on the screen! Pressed space key.")
        image_detected = True
        pyautogui.press('space')
        time.sleep(1)
        
    elif not np.any(loc) and image_detected:
        print("Image is no longer detected on the screen. Exiting...")
        break
python python-3.x pyautogui
1个回答
0
投票

pyautogui 在屏幕捕获方面是出了名的慢,而 openCV 和 mss 是/是探索的替代方案。也就是说,您仍然经常循环多次以设置 img 的所有值以进行测试。您的 opencv 代码最接近我的预期。

对于 pyautogui,试试这个:

while any(map(lambda f: pyautogui.locateOnScreen(f, confidence=0.7), ["ffd1.PNG", "ffd2.PNG", "ffd3.PNG"])):
    print("Image detected on the screen! Pressed space key.")
    pyautogui.press('space')
    time.sleep(1)

ctypes.windll.user32.MessageBoxW(0, "There's work to be done!!", "There's work to be done!!", 0x1000)

我预计不会有很大的改进,特别是如果您有更大的显示器。

© www.soinside.com 2019 - 2024. All rights reserved.