Skip to content

Instantly share code, notes, and snippets.

@oliver
Created April 14, 2014 20:28
Show Gist options
  • Star 6 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save oliver/10680301 to your computer and use it in GitHub Desktop.
Save oliver/10680301 to your computer and use it in GitHub Desktop.
create an animation showing Discrete Cosine Transform and what its frequency levels look like
#!/usr/bin/python
import sys, os
from PIL import Image
import numpy
import scipy.fftpack
sourceImage = sys.argv[1]
image = Image.open(sourceImage)
image = image.resize( (128,128), 1 )
image = image.convert("L")
dctSize = image.size[0]
# get raw pixel values:
pixels = numpy.array(image.getdata(), dtype=numpy.float).reshape((dctSize, dctSize))
# perform 2-dimensional DCT (discrete cosine transform):
dct = scipy.fftpack.dct(scipy.fftpack.dct(pixels.T, norm="ortho").T, norm="ortho")
# create a series of images with increasingly larger parts of the DCT values being used:
os.mkdir("frames/")
for i in range(0, dctSize):
dct2 = dct.copy()
# zero out part of the higher frequencies of the DCT values:
dct2[i:,:] = 0
dct2[:,i:] = 0
# perform 2d inverse DCT to get pixels back:
idct = scipy.fftpack.idct(scipy.fftpack.idct(dct2.T, norm='ortho').T, norm='ortho')
# clip/convert pixel values obtained by IDCT, and create image:
idct = idct.clip(0, 255)
idct = idct.astype("uint8")
img = Image.fromarray(idct)
print img
img.save("frames/img_%04d.png" % i)
os.system("convert -delay 30 -comment 'example of Discrete Cosine Transform (source image: %s)' frames/img_*.png dct.gif" % sourceImage)
@oliver
Copy link
Author

oliver commented Apr 14, 2014

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