Simon
Simon

Reputation: 39

Draw a random circle one at a time using OpenCV

I am using Python and OpenCV to draw 10 random small green color circles.

How to make the 1st random circle appear first and be visible for 10 seconds? Then it disappears. Then draw the 2nd random circle(visible for 10 seconds, disappears) and so on until 10.

Below is my code:

import cv2
import numpy as np

img = np.zeros((300, 300, 3), dtype="uint8")
# draw 10 small random circles
for i in range(0, 10):
    # center coordinates
      ccrd = np.random.randint(0, high=300, size=(2,))
  
      # draw random circle
      cv2.circle(img, tuple(ccrd), 5, (0, 255, 0), -1)
# Display the image
cv2.imshow("IMG", img)
cv2.waitKey(0)
cv2.destroyAllWindows()

Thank you very much in advance.

Upvotes: 0

Views: 489

Answers (1)

Jeru Luke
Jeru Luke

Reputation: 21203

You need to use cv.waitKey() appropriately. Place it just after displaying the image and pass the number of milliseconds as parameter.

Code:

import cv2 as cv

# background
img = np.zeros((300, 300, 3), dtype="uint8")

# draw 10 small random circles, one after the other
for i in range(0, 10):
    # make copy of original image
    img2 = img.copy()

    ccrd = np.random.randint(0, high=300, size=(2,))
    cv.circle(img2, tuple(ccrd), 5, (0, 255, 0), -1)

    cv.imshow('res', img2)

    # wait for 10 seconds (10k ms)
    cv.waitKey(10000)

cv.destroyAllWindows()  

Upvotes: 2

Related Questions