Animate image using OpenCV in Python

Animated images are sequences of static images played continuously to create dynamic visual content. They're smaller than videos and widely supported across web and mobile platforms. OpenCV provides powerful tools to create animated effects by manipulating image sequences in Python.

What is OpenCV?

OpenCV (Open Source Computer Vision Library) is a comprehensive library for computer vision, machine learning, and image processing. Originally developed by Gary Bradsky at Intel in 1999, it now supports multiple programming languages including Python, C++, and Java across various platforms.

OpenCV provides extensive functionality for image manipulation, video processing, and real-time computer vision applications, making it ideal for creating animated effects.

Installation Requirements

To create animated images with OpenCV, you'll need ?

pip install opencv-python numpy

Creating Image Animation with Horizontal Scrolling

We'll create a scrolling animation effect by splitting and rearranging image columns. The hstack() function from NumPy concatenates arrays horizontally to create the animation frames ?

import cv2
import numpy as np
import time

# Create a sample image with text for better visualization
img = np.zeros((200, 400, 3), dtype=np.uint8)
img[:] = (50, 100, 150)  # Background color

# Add text to make the animation effect visible
cv2.putText(img, 'ANIMATED TEXT DEMO', (50, 100), 
           cv2.FONT_HERSHEY_SIMPLEX, 1, (255, 255, 255), 2)

h, w, c = img.shape
print(f"Image dimensions: {h}x{w}x{c}")

# Create animation frames
frames = []
for i in range(w):
    # Split image at column i
    left_part = img[:, :i]
    right_part = img[:, i:]
    
    # Rearrange: right part first, then left part
    if i == 0:
        animated_frame = img.copy()
    else:
        animated_frame = np.hstack((right_part, left_part))
    
    frames.append(animated_frame)

print(f"Created {len(frames)} animation frames")
Image dimensions: 200x400x3
Created 400 animation frames

Displaying the Animation

Now let's display the animated sequence using OpenCV's window display functions ?

# Display animation (Note: This requires a GUI environment)
for i in range(3):  # Repeat animation 3 times
    for frame in frames[::5]:  # Use every 5th frame for smoother playback
        cv2.imshow('Animated Image', frame)
        
        # Wait 50ms between frames (20 FPS)
        key = cv2.waitKey(50) & 0xFF
        
        # Press 'q' to quit
        if key == ord('q'):
            break
    
    if key == ord('q'):
        break

cv2.destroyAllWindows()

Creating a Rotating Animation Effect

Here's another animation technique using image rotation ?

import cv2
import numpy as np

# Create a simple geometric shape
img = np.zeros((300, 300, 3), dtype=np.uint8)
cv2.rectangle(img, (100, 100), (200, 200), (0, 255, 255), -1)
cv2.circle(img, (150, 150), 30, (255, 0, 0), -1)

# Get image center for rotation
center = (img.shape[1]//2, img.shape[0]//2)

# Create rotation animation
rotation_frames = []
for angle in range(0, 360, 10):
    # Create rotation matrix
    rotation_matrix = cv2.getRotationMatrix2D(center, angle, 1.0)
    
    # Apply rotation
    rotated = cv2.warpAffine(img, rotation_matrix, (img.shape[1], img.shape[0]))
    rotation_frames.append(rotated)

print(f"Created {len(rotation_frames)} rotation frames")

# Simulate displaying first few frames
for i, frame in enumerate(rotation_frames[:5]):
    print(f"Frame {i}: Rotation angle = {i*10} degrees")
Created 36 rotation frames
Frame 0: Rotation angle = 0 degrees
Frame 1: Rotation angle = 10 degrees
Frame 2: Rotation angle = 20 degrees
Frame 3: Rotation angle = 30 degrees
Frame 4: Rotation angle = 40 degrees

Key Animation Parameters

Parameter Function Effect
cv2.waitKey() Frame delay Controls animation speed
np.hstack() Horizontal concatenation Creates scrolling effect
cv2.getRotationMatrix2D() Rotation transformation Creates rotation animation
Frame count Animation length Smoothness and duration

Saving Animation as Video

To save your animation as a video file ?

# Initialize video writer
fourcc = cv2.VideoWriter_fourcc(*'mp4v')
out = cv2.VideoWriter('animation.mp4', fourcc, 20.0, (w, h))

# Write frames to video
for frame in frames[::5]:  # Use every 5th frame
    out.write(frame)

# Release video writer
out.release()
print("Animation saved as 'animation.mp4'")

Conclusion

OpenCV provides powerful tools for creating animated images through frame manipulation techniques like horizontal scrolling and rotation. Use cv2.waitKey() to control animation speed and VideoWriter to save animations as video files for sharing and distribution.

---
Updated on: 2026-03-27T13:22:54+05:30

2K+ Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements