Pause the showing of a series of images in opencv

I have the following code

the_list=os.listdir(directory)
img_list= [i for i in the_list if i.endswith('.png')]
img_list.sort()

for img_name in img_list:
    img=cv2.imread(img_name)
    cv2.imshow("movie",img)
    #cv2.waitKey(0)
    cv2.waitKey(10)

With this, if I use 0 in waiKey I have to press a key everytime but if I use 10 then I have something “like” a movie where each image is shown after another

My question is, how can I modify the script so that I can press a key to pause or continue the showing of the pics?

Answer

I haven’t tested this code but it should work, by pressing p you should be able to pause and unpause:

the_list=os.listdir(directory)
img_list= [i for i in the_list if i.endswith('.png')]
img_list.sort()
time_to_wait=10
for img_name in img_list:
    img=cv2.imread(img_name)
    cv2.imshow("movie",img)
    k = cv2.waitKey(time_to_wait)
    if k == ord('p'):
        if time_to_wait == 10:
             time_to_wait=0
        else:
             time_to_wait=10