Skip to content Skip to sidebar Skip to footer

Make A Pause Between Images Display In OpenCV

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 impo

Solution 1:

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

Solution 2:

In the waitkey() call the number is the number of milliseconds to wait for.


Solution 3:

Adding a value to waitkey() will make it pause for the given number of milliseconds. You could use itertools.cycle() to cycle through a list of images.

This script will pause 5 seconds and then display the next image. If escape is pressed it exits.

from itertools import cycle
import cv2


for image_filename in cycle(['image1.jpg', 'image2.jpg']):
    image = cv2.imread(image_filename, 0)
    cv2.imshow('image', image)

    # Pause here 5 seconds.
    k = cv2.waitKey(5000)

    if k == 27:         # If escape was pressed exit
        cv2.destroyAllWindows()
        break

Solution 4:

You can use glob module in python to select all files

import cv2
import glob # get all files in the directory


images = glob.glob("path_to_files/*.jpg") #get all files with given extension

for img in range(len(images)):
    current_image = cv2.imread(images[img], 1) #cv2.imread(images[i], 0) # for image in grayscale
    cv2.imshow('Display Images', current_image)
    key = cv2.waitKey(300) #change to your own waiting time 1000 = 1 second 
    if key == 27: #if ESC is pressed, exit
        cv2.destroyAllWindows()
        break

Post a Comment for "Make A Pause Between Images Display In OpenCV"