0

The following code is not rendering:

import cv2
import numpy as np
from time import sleep

hz = 30
bitmap = np.zeros((512,512,3),np.uint8)

for i in range(512):
    sleep(1/hz)
    bitmap[i,i,:] = 128
    cv2.imshow("Color Image", bitmap)

cv2.waitKey(0)
cv2.destroyAllWindows()

What am I missing?

5
  • I think you need to call something equivalent to plt.ion() in this answer, otherwise the imshow function will block: stackoverflow.com/questions/60586078/… Commented Mar 14, 2021 at 8:09
  • 1
    Indentation on the line with waitKey, it needs to run each iteration, or you won't see anything (as explained in the documentation). The parameter of waitKey also needs to be non-zero. | Also, the sleep expects the rest of the loop body to happen in 0 time, which won't be the case, so your loop will run slower than you want. Commented Mar 14, 2021 at 8:11
  • @Stefan Where do you see matplotlib in this question? Commented Mar 14, 2021 at 8:12
  • @DanMašek I don't, hence the word equivalent, and why I didn't attempt to answer it (as I don't know the correct function). I'm fairly certain that imshow blocks execution. Commented Mar 14, 2021 at 8:14
  • 1
    @Stefan No, cv2.imshow doesn't block. But it needs a call to waitKey to run the message loop, so that the window gets rendered. Commented Mar 14, 2021 at 8:17

1 Answer 1

1

The waitKey should be inside the loop. The input to the waitKey is the number of milliseconds the frame should be rendered. When its 0, the frame is rendered indefinitely. Try this.

import cv2
import numpy as np
from time import sleep

hz = 30
bitmap = np.zeros((512,512,3),np.uint8)

for i in range(512):
    sleep(1/hz)
    bitmap[i,i,:] = 128
    cv2.imshow("Color Image", bitmap)
    cv2.waitKey(3)
cv2.destroyAllWindows()
Sign up to request clarification or add additional context in comments.

1 Comment

Thanks! Linking future visitors to stackoverflow.com/questions/66623228/…

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.