De GirinoWiki
public class dct {
/**
* Calcula a DCT (Transformada Discreta de Cosseno) de uma matriz
* quadrada NxN.
* Este código não é otimizado, para possíveis otimizações,
* definições e detalhes, veja
* http://www.girino.org/mediawiki/index.php/Transformada_discreta_de_cosseno
*
* @param img a matriz (imagem) a ser codificada.
* @param size o tamanho da matriz.
* @return a matriz transformada.
**/
public static double[][] dct(double[][] img, int size) {
double[][] ret = new double[size][size];
for (int i = 0; i < size; i++) {
for (int j = 0; j < size; j++) {
ret[i][j] = 0;
for (int x = 0; x < size; x++) {
for (int y = 0; y < size; y++) {
double tmp = img[x][y];
tmp *= Math.cos((2*y + 1) * j * Math.PI/(2*size));
tmp *= Math.cos((2*x + 1) * i * Math.PI/(2*size));
ret[i][j] += tmp;
}
}
ret[i][j] *= 1.0/Math.sqrt(2*size);
ret[i][j] *= i==0?1.0/Math.sqrt(2):1.0;
ret[i][j] *= j==0?1.0/Math.sqrt(2):1.0;
}
}
return ret;
}
/** Matriz de exemplo usada no método main() **/
public static double[][] test = {
{1. , 19. , 37. , 55. , 73. , 91. , 109. , 127.},
{19. , 37. , 55. , 73. , 91. , 109. , 127. , 145.},
{37. , 55. , 73. , 91. , 109. , 127. , 145. , 163.},
{55. , 73. , 91. , 109. , 127. , 145. , 163. , 181.},
{73. , 91. , 109. , 127. , 145. , 163. , 181. , 199.},
{91. , 109. , 127. , 145. , 163. , 181. , 199. , 217.},
{109. , 127. , 145. , 163. , 181. , 199. , 217. , 235.},
{127. , 145. , 163. , 181. , 199. , 217. , 235. , 253.}
};
/** Exemplo. Executa o DCT na matriz de exemplo e imprime o resultado **/
public static void main(String[] args) {
double[][] tmp = dct(test, 8);
for (int i = 0; i < 8; i ++) {
for (int j = 0; j < 8; j++) {
System.out.print(tmp[i][j]);
System.out.print(", ");
}
System.out.print("\n");
}
}
}