Animar imagen usando OpenCV en Python

En este artículo, discutiremos cómo animar una imagen usando el módulo OpenCV de Python.

Supongamos que tenemos una imagen. Usando esa imagen única, la animaremos de tal manera que aparecerá una array continua de la misma imagen. Esto es útil para animar el fondo en ciertos juegos. Por ejemplo, en un juego de pájaros voladores, para que el pájaro parezca moverse hacia adelante, el fondo debe moverse hacia atrás. Para entender esto, primero consideremos una lista de pitones lineales. Considere el siguiente código por un momento. 

Python3

a = ['-', '-', '-', 1, '-', '-', '-']
n = len(a)  # length of the array
 
for i in range(2*n):
    # i is the index of the list a
    # i%n will have a value in range(0,n)
    # using slicing we can make the digit 1
    # appear to move across the list
    # this is similar to a cyclic list
    print(a[(i % n):]+a[:(i % n)])

Salida :

['-', '-', '-', 1, '-', '-', '-']
['-', '-', 1, '-', '-', '-', '-']
['-', 1, '-', '-', '-', '-', '-']
[1, '-', '-', '-', '-', '-', '-']
['-', '-', '-', '-', '-', '-', 1]
['-', '-', '-', '-', '-', 1, '-']
['-', '-', '-', '-', 1, '-', '-']
['-', '-', '-', 1, '-', '-', '-']
['-', '-', 1, '-', '-', '-', '-']
['-', 1, '-', '-', '-', '-', '-']
[1, '-', '-', '-', '-', '-', '-']
['-', '-', '-', '-', '-', '-', 1]
['-', '-', '-', '-', '-', 1, '-']
['-', '-', '-', '-', 1, '-', '-']

Del código anterior, podemos ver que la posición del dígito 1 está cambiando, es decir, el índice está cambiando. Este es el principio que usaremos para animar la imagen horizontalmente. 

Concatenaremos las dos imágenes usando la función hstack() del módulo NumPy. La función hstack toma una tupla que consiste en el orden de los arreglos como argumentos y se usa para apilar la secuencia de arreglos de entrada horizontalmente (es decir, en columnas) para hacer un solo arreglo.

Sintaxis :

numpy.hstack((array1,array2))

Ejemplo :

Python3

import cv2
import numpy as np
 
img = cv2.imread('shinchan.jpg')
 
height, width, c = img.shape
 
i = 0
 
while True:
    i += 1
     
    # divided the image into left and right part
    # like list concatenation we concatenated
    # right and left together
    l = img[:, :(i % width)]
    r = img[:, (i % width):]
 
    img1 = np.hstack((r, l))
     
    # this function will concatenate
    # the two matrices
    cv2.imshow('animation', img1)
 
    if cv2.waitKey(1) == ord('q'):
       
        # press q to terminate the loop
        cv2.destroyAllWindows()
        break

Salida :

Publicación traducida automáticamente

Artículo escrito por rajarshiban13 y traducido por Barcelona Geeks. The original can be accessed here. Licence: CCBY-SA

Deja una respuesta

Tu dirección de correo electrónico no será publicada. Los campos obligatorios están marcados con *