Skip to content

Instantly share code, notes, and snippets.

@leggitta
Last active February 12, 2017 19:29
Show Gist options
  • Save leggitta/8b558fe6dd875d6f1dfe06f8f11b78bd to your computer and use it in GitHub Desktop.
Save leggitta/8b558fe6dd875d6f1dfe06f8f11b78bd to your computer and use it in GitHub Desktop.
Computes the two dimensional discrete cosine transform of an image with a single non-zero point
"""
Computes the two dimensional discrete cosine transform, first over rows, than over columns
"""
import numpy as np
import matplotlib.pyplot as plt
# create input image
N1, N2 = 100, 100
x = np.zeros((N1, N2))
x[N1 // 2, N2 // 2] = 1
# define one dimensional dct function
def dct1d(x):
N = len(x)
X = np.zeros(N)
n = np.arange(N)
for k in range(N):
X[k] = np.dot(x, np.cos(np.pi * k * (2 * n + 1) / (2 * N)))
return X
# create output
Xr, X = np.zeros((2, N1, N2))
# transform rows
for i in range(N1):
Xr[i] = dct1d(x[i])
# transform columns
for j in range(N2):
X[:, j] = dct1d(Xr[:, j])
# plot the data
fig, ax = plt.subplots(1, 2)
ax[0].imshow(x, interpolation='nearest')
ax[0].set_title("Input Image")
ax[1].imshow(X, interpolation='nearest')
ax[1].set_title("Discrete Cosine Transform")
plt.show()
@leggitta
Copy link
Author

leggitta commented Feb 9, 2017

Generates the following image ...

figure_1-5

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