Python使图像识别代码循环,直到发生什么事情并中断i

2024-06-15 00:52:44 发布

您现在位置:Python中文网/ 问答频道 /正文

我有这个密码:

import cv2
import numpy as np
import pyautogui
import time

#image recognition
def imagesearch(image, precision=0.8):
    im = pyautogui.screenshot()
    img_rgb = np.array(im)
    img_gray = cv2.cvtColor(img_rgb, cv2.COLOR_BGR2GRAY)
    template = cv2.imread(image, 0)
    template.shape[::-1]

    res = cv2.matchTemplate(img_gray, template, cv2.TM_CCOEFF_NORMED)
    min_val, max_val, min_loc, max_loc = cv2.minMaxLoc(res)
    if max_val < precision:
        return [-1,-1]
    return max_loc

#continuous image searching on screen
def imagesearch_loop(image, timesample, precision=0.8):
    pos = imagesearch(image, precision)
    while pos[0] == -1:
        print(image+" not found, waiting")
        time.sleep(timesample)
        pos = imagesearch(image, precision)
    return pos

pos = imagesearch_loop("Bonus_Box.png", 0.5)
while not (imagesearch_loop("Bonus_Box.png", 0.5)):
    print("Hello")
    #do things..., after everything finishes and no image found return to while
print("image found ", "x:", pos[0], "y:", pos[1])

我试着让它在一个条件下循环。虽然不是imagesearch_loop("Bonus_Box.png", 0.5)我想做一些事情,但当一切都结束后,我的图像不再出现在屏幕上,我想返回while not (imagesearch_loop("Bonus_Box.png", 0.5)):重新开始搜索。你知道吗

谢谢你抽出时间


Tags: posimageimportboxloopimgreturnpng
1条回答
网友
1楼 · 发布于 2024-06-15 00:52:44

使用其他循环进行编码,最简单的方法是使用通常的Ctrl-C中断循环:

import cv2
import numpy as np
import pyautogui
import time

#image recognition
def imagesearch(image, precision=0.8):
    im = pyautogui.screenshot()
    img_rgb = np.array(im)
    img_gray = cv2.cvtColor(img_rgb, cv2.COLOR_BGR2GRAY)
    template = cv2.imread(image, 0)
    template.shape[::-1]

    res = cv2.matchTemplate(img_gray, template, cv2.TM_CCOEFF_NORMED)
    min_val, max_val, min_loc, max_loc = cv2.minMaxLoc(res)
    if max_val < precision:
        return [-1,-1]
    return max_loc

#continuous image searching on screen
def imagesearch_loop(image, timesample, precision=0.8):
    pos = imagesearch(image, precision)
    while pos[0] == -1:
        print(image+" not found, waiting")
        time.sleep(timesample)
        pos = imagesearch(image, precision)
    return pos


try:
    while True:
        pos = imagesearch_loop("Bonus_Box.png", 0.5)
        while not (imagesearch_loop("Bonus_Box.png", 0.5)):
          print("Hello")
          #do things..., after everything finishes and no image found return to while
        print("image found ", "x:", pos[0], "y:", pos[1])
except KeyboardInterrupt:
    pass

相关问题 更多 >