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?

P i
  • 29,020
  • 36
  • 159
  • 267
  • I think you need to call something equivalent to plt.ion() in this answer, otherwise the imshow function will block: https://stackoverflow.com/questions/60586078/plotting-changing-graphs-with-matplotlib/60586249#60586249 – Stefan Mar 14 '21 at 08: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. – Dan Mašek Mar 14 '21 at 08:11
  • @Stefan Where do you see matplotlib in this question? – Dan Mašek Mar 14 '21 at 08: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. – Stefan Mar 14 '21 at 08: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. – Dan Mašek Mar 14 '21 at 08:17

1 Answers1

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()
soumith
  • 536
  • 1
  • 3
  • 12
  • Thanks! Linking future visitors to https://stackoverflow.com/questions/66623228/can-i-render-an-opencv-animation-from-a-background-thread-in-python – P i Mar 14 '21 at 10:11