I would like to show several images, making a pause in between. I have tried with waitKey, waiting the user to press ESC, but it doesn't seem to be working.
import numpy as np
import cv2
img = cv2.imread('image1.jpg',0)
cv2.imshow('image',img)
# here it should be the pause
k = cv2.waitKey(0)
if k == 27: # wait for ESC key to exit
cv2.destroyAllWindows()
img = cv2.imread('image2.jpg',0)
cv2.imshow('image',img)
Any suggestion?
Thanks in advance
If there is a frame to read, you can then use imshow() to display the current frame in a window, otherwise exit the loop. Notice that you also use the waitKey() function to pause for 20ms between video frames. Calling the waitKey() function lets you monitor the keyboard for user input.
You can implement a pause/resume feature by determining what key was pressed from the return value of cv2. waitKey() . To pause the video, you can pass no parameter (or 0) to cv2. waitKey() which will wait indefinitely until there is a key press then it will resume the video.
Python OpenCV – waitKey() Function waitkey() function of Python OpenCV allows users to display a window for given milliseconds or until any key is pressed. It takes time in milliseconds as a parameter and waits for the given time to destroy the window, if 0 is passed in the argument it waits till any key is pressed.
Python Opencv destroyAllWindows() function allows users to destroy or close all windows at any time after exiting the script. If you have multiple windows open at the same time and you want to close then you would use this function. It doesn't take any parameters and doesn't return anything.
In the code you've posted, image1.jpg
is displayed and waits for the user to press any key since you've used waitKey(0)
. The 0
indicates the program will wait until a user hits a key. You can add the number of milliseconds you want to wait before the second image is displayed in place of the 0
. Once you've pressed a key, image2.jpg
is read but not displayed since you do not have a waitKey
after the second imshow
and the program will exit.
You can try the following code. This code assumes that your "several images" are located in a folder and it displays an image, pauses for 3 seconds and displays the next.
import cv2
import os
folder_path = ''#folder path to your images
for path in os.listdir(folder_path):#loop to read one image at a time
imgpath = os.path.join(folder_path, path)
frame = cv2.imread(imgpath, 1)
cv2.imshow('Window', frame)
key = cv2.waitKey(3000)#pauses for 3 seconds before fetching next image
if key == 27:#if ESC is pressed, exit loop
cv2.destroyAllWindows()
break
In the waitkey()
call the number is the number of milliseconds to wait for.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With