cv2.waitKey(25) & 0xFF == ord('q'): 和 cv2.imwrite() 不起作用

Bob*_*b.B 4 python opencv python-3.x

我正在关注这个项目,制作一个可以玩 Google Chrome Dino 游戏的 AI。我在捕获屏幕源以生成训练数据时陷入了困境。我是简历新手

该项目应该中断视频源并将 CSV 文件保存在 cv2.waitKey(25) & 0xFF == ord('q'): 条件中。我相信是当按下“q”键时。但是当我按“q”时什么也没有发生。当我按 q 时,此 if 条件中的打印语句不会打印。

另外,虽然控制台在按下“向上”、“向下”或“t”键的情况下打印打印语句,但

cv2.imwrite('./images/frame_(0).jpg'.format(x), img) 
Run Code Online (Sandbox Code Playgroud)

似乎不起作用,因为图像文件夹中没有保存图像。

这是代码

import cv2 
from mss import mss 
import numpy as np 
import keyboard

#Captures dinasour run for given coordinates

def start():
    """
    Capture video feed frame by frame, crops out coods and the dino then process
    """

    sct = mss()

    coordinates = {
        'top': 168,
        'left': 230,
        'width': 624,
        'height': 141
    }

    with open('actions.csv','w') as csv:
        x = 0
        while True:
            img = np.array(sct.grab(coordinates))

            #crop out the dino from the image array
            img = img[::,75:624]

            #edge detection to reduce ammount of image processing work
            img = cv2.Canny(img, threshold1=100, threshold2=200)

            if keyboard.is_pressed('up arrow'):
                cv2.imwrite('./images/frame_(0).jpg'.format(x), img)
                csv.write('1\n')
                print('jump write')
                x += 1

            if keyboard.is_pressed('down arrow'):
                cv2.imwrite('./images/frame_(0).jpg'.format(x), img)
                csv.write('2\n')
                print('duck')
                x += 1


            if keyboard.is_pressed('t'):
                cv2.imwrite('./images/frame_(0).jpg'.format(x), img)
                csv.write('0\n')
                print('nothing')
                x += 1

            # break the video feed
            if cv2.waitKey(25) & 0xFF == ord('q'):
                csv.close()
                cv2.destroyAllWindows()
                print('Exited')
                break

def play():
    sct = mss()

    coordinates = {
        'top': 168,
        'left': 230,
        'width': 624,
        'height': 141
    }

    img = np.array(sct.grab(coordinates))

    # crop out the dinosaur from the image array
    img = img[::,75:615]

    # edge detection to reduce amount of image processing work
    img = cv2.Canny(img, threshold1=100, threshold2=200)
Run Code Online (Sandbox Code Playgroud)

fec*_*avy 5

cv2.waitKey()仅当您在 OpenCV 窗口(例如使用 创建cv2.imshow())获得焦点时按下该键才起作用。在我看来,你根本不使用 OpenCV 的 GUI 功能。

如果您的程序中有 OpenCV GUI,请将其聚焦,然后按 键。

如果没有,并且您不想实现它,为什么不使用 呢keyboard.isPressed()