Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Python CV2 slow response time on keys

I have been coding a video player to test if I can play and pause a video in Python. My problem is that whenever I press a key, its irresponsive and needs continuous presses to work, and the effect is random.

If anyone knows what could be causing this, it would be of great help.

import cv2

cap = cv2.VideoCapture('testvideo.mp4')

length = int(cap.get(cv2.CAP_PROP_FRAME_COUNT))

isPlaying = False


def onchange(trackbar_value):
    cap.set(cv2.CAP_PROP_POS_FRAMES, trackbar_value)
    err, vid = cap.read()
    cv2.imshow('player', vid)
    pass


start = 0

cv2.namedWindow('player')
cv2.createTrackbar('test', 'player', start, length, onchange)

onchange(1)

while cap.isOpened():
    if cv2.waitKey(1) & 0xFF == ord('q'):
        break
    elif cv2.waitKey(1) & 0xFF == ord('p'):
        isPlaying = not isPlaying

    ret, player = cap.read()

    if cv2.waitKey(20) == 27:
        break
    if isPlaying:
        cv2.imshow('test', 'frame')

    elif cap.get(cv2.CAP_PROP_POS_FRAMES) >= length:
        break

cap.release()
cv2.destroyAllWindows()
like image 302
kveola92 Avatar asked May 16 '26 12:05

kveola92


1 Answers

I fixed it by changing this part in the while cap.isOpened() loop:

keyPress = cv2.waitKey(20)
ret, player = cap.read()
if keyPress & 0xFF == ord('q'):
    break
elif keyPress & 0xFF == ord('p'):
    isPlaying = not isPlaying

once I removed the

if cv2.waitKey(20) == 27:
    break

line, it worked much better than before too.

All of this sped up the project, and everything works fine now

like image 91
kveola92 Avatar answered May 19 '26 00:05

kveola92



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!