In this, I will explain to you about performing a simple animation with Opencv.

 

As usual you have to open a new IDLE file and start the program by importing necessary libraries.

import cv2

import numpy as np

import time

Then we create a blank frame where we do our animation. Let’s name it Frame_out. The size is 500 X 640 pixels with 3 channels.

Frame_out = np.zeros((500, 640, 3),np.uint8)

Then we define a variable “a”. Its a long integer type. We use it with a while loop for animation.

a = 1

In the animation I wanted to show you a color change and increment of the size of a rectangle.

Due to the color change we limit the value of a to 254. (a<255). Although, I use the same “a” for increment of the size of rectangle, you can define a separate variable for the size.

Let’s start the loop.

while a<255:

We draw a triangle in red color on the blank frame we created above. However, as the loop continues, the color fades and ultimately become black. (0,0,255-a) Here 255-a means that, when “a” increases the value of red color is reduced from 255 to 1.

cv2.rectangle(Frame_out,(a,a),(a*2,a*2),(0,0,255-a),0)

We wait for some time.

time.sleep(0.05)

The drawn rectangle is shown with cv2.imshow function.

cv2.imshow(‘Animation’, Frame_out)

While new rectangle is created, we want to delete the previous rectangle. For the, there is no a clear method. So, you can use any technique. What I do here is, draw a black rectangle on the previous one. Then it is viewed as removing the previous rectangle. (Try to find your own method).

cv2.rectangle(Frame_out,(a,a),(a*2,a*2),(0,0,0),0)

We do increases the value of “a” by 2. (Or you use any value that you prefer)

a +=2

Here I have added an if condition. Normally our while loop will break, if the value of “a” is 255. To prevent that we reset the “a” to 1, if it’s value is greater than 254.

if(a > 254):

a = 1

The loop will continue for ever, due to we reset the “a” in a certain value.

To break the loop manually we can use cv2.waitKey() function. “If k==27” means that if Esc key is pressed.

k = cv2.waitKey(10)

if k == 27:

break

Finally we destroy all windows we create. Thats a cleat exit.

cv2.destroyAllWindows()

 

Save the file. Press F5 to run animation.

 

Download the python code here.

A Simple Animation with Opencv

Leave a Reply

Your email address will not be published. Required fields are marked *