Animating with Python
Published 2021/11/27 by Jordan HayI created an animation in Python. Each frame is generated with a Numpy array of pixel colours and is output to an AVI file with cv2.
The source code has been published on Github, and the animation on Youtube.
''' Renders a sine wave animation with Python. Author: Jordan Hay Date: 26/11/2021 ''' # - Imports import numpy as np import cv2 import math from jmath.approximation import differentiate # - Main if __name__ == "__main__": # X/Y Dimensious to output to X = 1920 Y = 1080 # Framerate frames = 60 # Function to draw # Sine wave with 50 pixel amplitude rounded to integer values # Should be noted that it will draw "upside down" y-axis points downwards func = lambda x: round(50 * math.sin(x*0.05) + 540) # Centre of x axis centre = X//2 # Function that computes how close to the centre of the x-axis something is centreness = lambda x: 1 - abs(x - centre)/centre # Starting data data = np.zeros((Y, X, 3), np.uint8) # CV2 AVI output output = cv2.VideoWriter('project.avi', cv2.VideoWriter_fourcc(*'DIVX'), frames, (X, Y)) # Starting points x, y = (0, 0) while x < X: # Sample point y = func(x) # Insert in drawing data[y:y+3, round(x):round(x)+3] = (255, centreness(x) * 255, centreness(x) * 255) # YX BGR output.write(data) # Get tangent gradient m = differentiate(func, x).value # Move along inversely proportionally to gradient # This should result in drawing speed proportional to line length if m != 0: x += 1/m # Plus some extra movement here x += 1 output.release()