In getting back the matrix after applying Discrete cosine transform in Java

180 views Asked by At

I want to apply DCT on an image, but before doing that on such a big matrix, I wanted to apply the DCT and IDCT on a 2X2 matrix. Following is the code I have written to perform the DCT and IDCT on a 2X2 matrix.But am not getting back the original matrix after the IDCT. Where have I gone wrong??

package dct;

/**
 *
 * @author jain
 */
public class try4 {

    public static void main(String[] args)
    {
        int n = 2;

        double[][] ob = new double[n][n];
        double[][] dct = new double[n][n];
        double[][] rb = new double[n][n];
        double[] c = new double[2];


        // initialize co-efficients
        c[0] = 1/Math.sqrt(2);
        c[1] = 1;

        ob[0][0] = 54.0;
        ob[0][1] = 35.0;
        ob[1][0] = 28.0;
        ob[1][1] = 45.0;

        for(int u = 0; u < 2;u++)
        {
            for(int v =0; v < 2;v++)
            {
                double sum = 0;
                for(int j = 0;j < 2; j++)
                {
                    for(int i = 0;i < 2;i++)
                    {
                        //sum += Math.cos(((2*i+1)/(2.0*n))*u*Math.PI)*Math.cos(((2*j+1)/(2.0*n))*v*Math.PI)*ob[i][j];
                        sum += Math.cos(( (2*i + 1) * (u*Math.PI) ) / (2*n) ) * Math.cos(( (2*j + 1) * (v*Math.PI) ) / (2*n) ) * ob[i][j];
                    }
                }

                sum = sum * (2/n) * c[u]*c[v];
                dct[u][v] = sum;

            }
        }

        System.out.println("The DCT matrix is ");

        for(int i= 0; i < 2;i++)
        {   
            for(int j = 0;j < 2; j++)
                {
                    System.out.print(dct[i][j] + "\t");
                }
            System.out.println();
        }

        for(int u = 0; u < 2;u++)
        {
            for(int v =0; v < 2;v++)
            {
                double sum = 0;
                for(int j = 0;j < 2; j++)
                {
                    for(int i = 0;i < 2;i++)
                    {
                        //sum +=c[u]*c[v]*dct[u][v] * Math.cos( ((2*i+1)/(2.0*n))) *Math.cos(((2*j+1)/(2.0*n))*v*Math.PI);
                        sum += c[u]*c[v]*dct[u][v] * Math.cos( ( (2*i + 1) * (u*Math.PI) ) / (2*n) ) * Math.cos(( (2*j + 1) * (v*Math.PI) ) / (2*n) );
                    }
                }
                sum = sum * (2/n);
                rb[u][v] = sum;
            }
        }
        System.out.println("The retrieved matrix is ");

        for(int i= 0; i < 2;i++)
        {   
            for(int j = 0;j < 2; j++)
                {
                    System.out.print(rb[i][j] + "\t");
                }
            System.out.println();
        }
     }// main ends
}// class ends
0

There are 0 answers