cv2.waitKey (25) & 0xFF == ord ('q'): и cv2.imwrite () не работают

Я слежу за этим проектом по созданию ИИ, который будет играть в игру Google Chrome Dino. Я застрял в какой-то момент, когда снимаю экранную ленту для генерации обучающих данных. Я новичок в резюме

Предполагается, что проект прервет поток видео и сохранит файл CSV в cv2.waitKey (25) & 0xFF == ord ('q'): condition. Я считаю, что это происходит при нажатии клавиши «q». Но когда я нажимаю «q», ничего не происходит. Оператор печати в этом условии if не печатается, когда я нажимаю q.

Кроме того, хотя консоль печатает оператор печати в условиях нажатия клавиши «вверх», «вниз» или «t», но

cv2.imwrite('./images/frame_(0).jpg'.format(x), img) 

Кажется, не работает, так как изображения в папке изображений не сохраняются.

Вот код

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)

person Bob.B    schedule 03.06.2018    source источник


Ответы (1)


cv2.waitKey() работает только в том случае, если вы нажимаете клавишу, когда окно OpenCV (например, созданное с помощью cv2.imshow()) находится в фокусе. Мне кажется, что вы вообще не используете возможности графического интерфейса OpenCV.

Если в вашей программе есть графический интерфейс OpenCV, сфокусируйте его и нажмите клавишу.

Если нет и если вы не хотите его реализовывать, почему бы не использовать keyboard.isPressed()?

person fecavy    schedule 03.06.2018