Skip to content

Instantly share code, notes, and snippets.

@JHay0112
Last active November 27, 2021 00:09
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save JHay0112/e2b7e5e17869000e3d3db75cfceab774 to your computer and use it in GitHub Desktop.
Save JHay0112/e2b7e5e17869000e3d3db75cfceab774 to your computer and use it in GitHub Desktop.
Sine wave render in Python
'''
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()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment