Discrete cosine transforms find their application in image compression. JPEG format, which is a widely accepted standard, uses DCT for compression.

Here is a small demo to show the use of DCT.

The test image, a 512x512 image

Code

The code for understanding DCT is fairly simple.

The first line reads the image into the matrix ‘x’. Then we find the DCT of this image and store it on ‘y’.

The next 5 lines of code is used to take a part of the matrix ‘y’ and save it onto matrix z. Here only 200x200 elements of the matrix ‘y’ are saved on ‘z’.

The plot of ‘y’ and ‘z’ are shown later.

The above operation is similar to cropping of the image.

Now we find the inverse DCT of the matrix ‘z’. This should give us the image back, but it will not. A scaling factor of around 255 is required, either multiply or divide, play around to find the correct one. Divide works for me.

Hence the line: imshow(z1/255).

Result

The resulting image is shown alongside.

Now to understand what we actually did we have to look at the details of the image.

So just type in “whos z1” (without quotes) and you will see that the resulting image is a 200x200. Not only has the image been resized, but the important point is we recovered the complete image with only 200x200 values of the DCT. This is what we mean by energy compaction, where most of the image data is stored in the first few elements of the matrix.

whos z1

imshow(y)

imshow(z)

Hope this post has made you understand and appreciate image processing, and mainly maths.