Skip to content

Instantly share code, notes, and snippets.

@WitherOrNot
Created June 26, 2020 03:57
Show Gist options
  • Save WitherOrNot/97f9a0d5a19d9d7fb0a9d3d14989bba4 to your computer and use it in GitHub Desktop.
Save WitherOrNot/97f9a0d5a19d9d7fb0a9d3d14989bba4 to your computer and use it in GitHub Desktop.
Convert image to desmos graph
import numpy as np
import cv2
import matplotlib.pyplot as plt
import code
import time
import sys
from fractions import Fraction
SKIP = 8 if len(sys.argv) <= 3 else int(sys.argv[3])
def chunk(lst, size):
return [lst[i:i + size] for i in range(0, len(lst), size)]
def seq_to_latex(seq, name, subscript):
res = f"{name}_{{{subscript}}}=\\left["
res += ",".join(map(str, seq))
res += "\\right]"
return res
def floor_thresh(x, threshold=1e-4):
if abs(round(x) - x) < threshold:
return round(x)
else:
return x
def eval_fseries(t, amps, freqs, shifts):
return sum([a*np.cos(f*t + s) for a,f,s in zip(amps,freqs,shifts)])
def fourier_series(vals, time_intv=1):
fft = np.fft.rfft(vals) / len(vals)
amps = []
freqs = []
shifts = []
for i in range(len(fft)):
amp = np.abs(fft[i])
amps.append(amp)
freq = 2*np.pi*i / time_intv
freqs.append(freq)
shift = np.arctan2(fft[i].imag, fft[i].real)
shifts.append(shift)
offset = vals[0] - eval_fseries(0, amps, freqs, shifts)
amps[0] += offset
amps = list(2*np.array(amps))
amps[0] -= vals[0]
return amps, freqs, shifts
if __name__ == "__main__":
im = cv2.imread(sys.argv[1])
imgray = cv2.cvtColor(im,cv2.COLOR_BGR2GRAY)
ret,thresh = cv2.threshold(imgray,127,255,0)
contours, hierarchy = cv2.findContours(thresh,cv2.RETR_TREE,cv2.CHAIN_APPROX_SIMPLE)
print("Got contour")
cnth = [[x for x in list(np.vstack(cnt).squeeze())] for cnt in list(contours)]
print("Got point list")
for x in range(len(cnth)):
if type(cnth[x][0]) != type(np.array([])):
cnth[x] = [np.array(cnth[x])]
del contours
h,w = im.shape[:2]
cntx = [[a[0] for a in b] for b in cnth]
cnty = [[h - a[1] for a in b] for b in cnth]
del cnth
print("Got each coordinate")
sys.stdout = open(sys.argv[2], "w")
print("C\\left(x,A,F,S\\right)=\\sum_{n=1}^{\\operatorname{length}\\left(A\\right)}\\left(A\\left[n\\right]\\cos\\left(F\\left[n\\right]x+S\\left[n\\right]\\right)\\right)\\left\\{0\\le x\\le1\\right\\}")
for i in range(0,len(cntx)):
ampx, freqx, shiftx = fourier_series(cntx[i][::SKIP])
ampy, freqy, shifty = fourier_series(cnty[i][::SKIP])
print(seq_to_latex(ampx, "A", f"{i}x"))
print(seq_to_latex(freqx, "F", f"{i}x"))
print(seq_to_latex(shiftx, "S", f"{i}x"))
print(seq_to_latex(ampy, "A", f"{i}y"))
print(seq_to_latex(freqy, "F", f"{i}y"))
print(seq_to_latex(shifty, "S", f"{i}y"))
print(f"\\left(C\\left(t,A_{{{i}x}},F_{{{i}x}},S_{{{i}x}}\\right),C\\left(t,A_{{{i}y}},F_{{{i}y}},S_{{{i}y}}\\right)\\right)")
@WitherOrNot
Copy link
Author

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment