Skip to content

Instantly share code, notes, and snippets.

@leggitta
Last active February 8, 2017 23:33
Show Gist options
  • Save leggitta/5658fa6aa136f88fcdf6d08a3a1937bf to your computer and use it in GitHub Desktop.
Save leggitta/5658fa6aa136f88fcdf6d08a3a1937bf to your computer and use it in GitHub Desktop.
Demonstration of the discrete cosine transform, a variation of the fast fourier transform, often used in image and audio compression
import numpy as np
import matplotlib.pyplot as plt
N = 100
x = np.zeros(N)
x[50] = 1
# compute the dct
X = np.zeros(N)
for k in range(N):
X[k] = np.sum([x[n]*np.cos(np.pi/N*(n+0.5)*k) for n in range(N)])
# invert the dct
X_ = np.zeros(N)
for k in range(N):
X_[k] = X[0]/2 + np.sum([X[n]*np.cos(np.pi/N*n*(k+0.5)) for n in range(N)])
X_ *= 2/N
fig, ax = plt.subplots(3)
ax[0].plot(x)
ax[0].set_title('Original Signal')
ax[0].set_xticks([])
ax[1].plot(X)
ax[1].set_title('Discrete Cosine Transform (DCT)')
ax[1].set_xticks([])
ax[2].plot(X_)
ax[2].set_title('Inverted DCT')
plt.show()
@leggitta
Copy link
Author

leggitta commented Feb 8, 2017

Generates the following figure ...

figure_1-2

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