cv2.waitkey(0)当随机键按时不等待-OpenCV 3.1.0,python3,ubuntu

cv2.waitKey(0) not waiting when random key pressed - OpenCV 3.1.0, Python3, Ubuntu

本文关键字:-OpenCV 等待 ubuntu python3 waitkey 随机 cv2      更新时间:2023-10-16

所以我有一个程序,其中将不同的按键分配给不同的功能。我正在使用CV2.Waitkey(0)一个一个框架。但是,当按下未分配函数的键时,下一个帧仍会加载。如何防止未分配的键盘将下一帧加载到我的循环中?

谢谢!

while (cap.isOpened()):
frameclick = cv2.waitKey(0)
ret, frame = cap.read()
cv2.imshow('frame',frame)
if frameclick == ord('a'):
    swingTag()
elif frameclick == ord('r'):
    rewindFrames()
elif frameclick == ord('s'):
    stanceTag()
elif frameclick == ord('d'):
    unsureTag()
elif frameclick == ord('q'):
    with open((selectedvideostring + '.txt'), 'w') as textfile:
        for item in framevalues:
            textfile.write("{}n".format(item))
    break

问题与您的逻辑有关。您的程序进入WARE循环并等待键。然后,如果按下键,则读取下一帧,但目前您的程序不在乎按下哪个键。因此,您将有下一个帧,然后才能检查按下哪个按钮,这是迟到的。

,如 @ervin的答案中所述,尝试:

while (cap.isOpened()):
    ret, frame = cap.read()
    # check if read frame was successful
    if ret == False: break;
    # show frame first
    cv2.imshow('frame',frame)
    # then waitKey -- and make it <= 255
    frameclick = cv2.waitKey(0) & 0xFF
    if frameclick == ord('a'):
        swingTag()
    elif frameclick == ord('r'):
        rewindFrames()
    elif frameclick == ord('s'):
        stanceTag()
    elif frameclick == ord('d'):
        unsureTag()
    elif frameclick == ord('q'):
        with open((selectedvideostring + '.txt'), 'w') as textfile:
            for item in framevalues:
                textfile.write("{}n".format(item))
        break