简体   繁体   中英

Why doesn't cv2 show an image within a for loop?

The following code will display an image correctly using cv2 in python:

import cv2

img = 'image file.jpg'

frame = cv2.imread(img)

while True:

    cv2.imshow('frame', frame)

    if cv2.waitKey(20) == ord('q'):

        break

However, say I want to run a for loop which incorporates cv2 showing an image:

import cv2

img = 'image file.jpg'

frame = cv2.imread(img)

test = [1,2]

for t in test:

    print(t)

    cv2.imshow('frame', frame)

    if cv2.waitKey(20) == ord('q'):

        break

I expected this code to show the image twice, but the image isn't shown at all. 't' is printed correctly. What am I missing?

Nevermind I realized I just need to change this:

if cv2.waitKey(20) == ord('q'):

    break

to this:

if cv2.waitKey(0) == ord('q'):

    cv2.destroyAllWindows()

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM