How to show videos frame by frame (with key presses) with python cv2?

I am trying to open a video file and play it frame by frame using key presses. So it would open and show a single frame indefinitely until a particular key is pressed and then it would switch to the next frame.

I'm using python3 and cv2. This is the first time I am using cv2 so any corrections/recommendations are welcome.

The code below works in the sense that it shows the video one frame at a time but not only when I press k but with any key press and it ignores the q to exit.

import cv2
import os

def play_video(folder):
# load video capture from file
video = cv2.VideoCapture(os.path.join(folder, “Field.mp4”))
# window name and size
cv2.namedWindow(“video”, cv2.WINDOW_AUTOSIZE)
while video.isOpened():
# Read video capture
ret, frame =
# Display each frame
cv2.imshow(“video”, frame)
# show one frame at a time
cv2.waitKey(00) == ord(‘k’)
# Quit when ‘q’ is pressed
if cv2.waitKey(1) == ord(‘q’):
# Release capture object
# Exit and distroy all windows


I would like to press a specific key to move forward (one to move back too, but that might be for another question) and be able to press q to quit.

Any suggestions? Thank you in advance!

#python #video

3 Likes25.35 GEEK