ActiveState Code

Recipe 231476: Discrete Cosine/Sine Transformations


Python implementation of DCT/DST.

Python
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
##################################################################################
##
##	Author:		Premshree Pillai
##	Date:		27/10/03	
##	File Name:	dct-dst.py
##	Description:	-Discrete Cosine/Sine Transformations
##	Website:	http://www.qiksearch.com
##	Category:	Math
##
##################################################################################

from math import *

n = 4.0
a = [[0.0,0.0,0.0,0.0],[0.0,0.0,0.0,0.0],[0.0,0.0,0.0,0.0],[0.0,0.0,0.0,0.0]]
alpha = [0.0,0.0,0.0,0.0]

tempCount = 0
while(tempCount < 4):
    if(tempCount == 0):
        alpha[tempCount] = (1.0 / n)**0.5
    else:
	alpha[tempCount] = (2.0 / n)**0.5
    tempCount = tempCount + 1

i = 0
option = raw_input("Enter choice (DCT=0, DST=1): ")
while(i < 4):
    j = 0
    while(j < 4):
        a[i][j] = alpha[j] * cos(((2.0 * i + 1.0) * j * pi) / (2.0 * n))
        if(option == 1):
		a[i][j] = (2.0 / (n + 1.0)) * sin((i + 1.0) * (j + 1.0) * pi/(n + 1.0))**0.5
	j = j + 1
    i = i + 1

i = 0
while(i < 4):
    j = 0
    while(j < 4):
        u = 0
	print "\nPattern[",i,",",j,"]\n"
	while(u < 4):
            v = 0
            buf = ['']
	    while(v < 4):
		buf.append(a[u][i] * a[v][j])
                v = v + 1
                continue
            print buf[1],"\t",buf[2],"\t",buf[3],"\t",buf[4]
            u= u + 1
        if(i == 3 and j == 3):
            break
        while(raw_input()):
            continue
	j = j + 1
    print "\n"
    i = i + 1

Comments

  1. 1. At 2:06 p.m. on 6 nov 2003, Noah Spurrier said:

    Needs a bit more explaination. This is interesting, but what's it do? It's hard to follow the inputs to the outputs. These input data should be labeled more clearly and you should explain what is going to happen to the input. Like any good recipe it's nice to give hints on when you would want to serve it.

  2. 2. At 5:24 a.m. on 12 nov 2003, Dinu Gherman said:

    Needs some comments. This might be ultra-cool, but even then it would benefit from a couple of comments explaining some things for people to read before running the code, or they might not run it at all.

  3. 3. At 8:06 a.m. on 21 dec 2008, Tim Chen said:

    Thanks for the recipe. There seems a unindented problem in the original script. I uploaded a indented version on http://toolsbytim.googlecode.com/files/dct.py The script can run in PythonWin Editor.

  4. 4. At 6 a.m. on 7 nov 2009, shanoger salman said:

    I tried using this function in C++ but the output is different from that of Matlab DC2 function. Is it possible that i have the equivalent C or C++ code?

Sign in to comment