In this article, we will discuss how to animate an image using python’s OpenCV module.
Let’s suppose we have one image. Using that single image we will animate it in such a way it will appear continuous array of the same image. This is useful in animating the background in certain games. For example, in a flappy bird game to make the bird appear moving forward the background needs to move backward. To understand this let us first consider a linear python list. Consider the following code for a moment.
Python3
a = [ '-' , '-' , '-' , 1 , '-' , '-' , '-' ]
n = len (a)
for i in range ( 2 * n):
print (a[(i % n):] + a[:(i % n)])
|
Output:
['-', '-', '-', 1, '-', '-', '-']
['-', '-', 1, '-', '-', '-', '-']
['-', 1, '-', '-', '-', '-', '-']
[1, '-', '-', '-', '-', '-', '-']
['-', '-', '-', '-', '-', '-', 1]
['-', '-', '-', '-', '-', 1, '-']
['-', '-', '-', '-', 1, '-', '-']
['-', '-', '-', 1, '-', '-', '-']
['-', '-', 1, '-', '-', '-', '-']
['-', 1, '-', '-', '-', '-', '-']
[1, '-', '-', '-', '-', '-', '-']
['-', '-', '-', '-', '-', '-', 1]
['-', '-', '-', '-', '-', 1, '-']
['-', '-', '-', '-', 1, '-', '-']
From the above code, we can see that the position of digit 1 is changing i.e. the index is changing. This is the principle we will use to animate the image horizontally.
We will concatenate the two images using hstack() function from the NumPy module. hstack function takes a tuple consisting of the order of the arrays as arguments and is used to stack the sequence of input arrays horizontally (i.e. column-wise) to make a single array.
Syntax:
numpy.hstack((array1,array2))
Example:
Python3
import cv2
import numpy as np
img = cv2.imread( 'shinchan.jpg' )
height, width, c = img.shape
i = 0
while True :
i + = 1
l = img[:, :(i % width)]
r = img[:, (i % width):]
img1 = np.hstack((r, l))
cv2.imshow( 'animation' , img1)
if cv2.waitKey( 1 ) = = ord ( 'q' ):
cv2.destroyAllWindows()
break
|
Output:

Whether you're preparing for your first job interview or aiming to upskill in this ever-evolving tech landscape,
GeeksforGeeks Courses are your key to success. We provide top-quality content at affordable prices, all geared towards accelerating your growth in a time-bound manner. Join the millions we've already empowered, and we're here to do the same for you. Don't miss out -
check it out now!
Last Updated :
03 Jan, 2023
Like Article
Save Article