www.gusucode.com > images 案例代码 matlab源码程序 > images/ImageCompressionWithTheDiscreteCosineTransformExample.m

    %% Image Compression with the Discrete Cosine Transform
% This example shows how to compress an image using the Discrete Cosine
% Transform (DCT). The example computes the two-dimensional DCT of 8-by-8
% blocks in an input image, discards (sets to zero) all but 10 of the 64
% DCT coefficients in each block, and then reconstructs the image using the
% two-dimensional inverse DCT of each block. The example uses the transform
% matrix computation method.
%
% DCT is used in the JPEG image compression algorithm. The input image is
% divided into 8-by-8 or 16-by-16 blocks, and the two-dimensional DCT is
% computed for each block. The DCT coefficients are then quantized, coded,
% and transmitted. The JPEG receiver (or JPEG file reader) decodes the
% quantized DCT coefficients, computes the inverse two-dimensional DCT of
% each block, and then puts the blocks back together into a single image.
% For typical images, many of the DCT coefficients have values close to
% zero. These coefficients can be discarded without seriously affecting the
% quality of the reconstructed image.
%%
% Read an image into the workspace and convert it to class |double|.
I = imread('cameraman.tif');
I = im2double(I);
%%
% Compute the two-dimensional DCT of 8-by-8 blocks in the image. The
% function |dctmtx| returns the N-by-N DCT transform matrix. 
T = dctmtx(8);
dct = @(block_struct) T * block_struct.data * T';
B = blockproc(I,[8 8],dct);
%%
% Discard all but 10 of the 64 DCT coefficients in each block.
mask = [1   1   1   1   0   0   0   0
        1   1   1   0   0   0   0   0
        1   1   0   0   0   0   0   0
        1   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   0   0   0   0   0   0   0];
B2 = blockproc(B,[8 8],@(block_struct) mask .* block_struct.data);
%%
% Reconstruct the image using the two-dimensional inverse DCT of each
% block.
invdct = @(block_struct) T' * block_struct.data * T;
I2 = blockproc(B2,[8 8],invdct);
%%
% Display the original image and the reconstructed image, side-by-side.
% Although there is some loss of quality in the reconstructed image, it is
% clearly recognizable, even though almost 85% of the DCT coefficients were
% discarded.
imshow(I)
figure
imshow(I2)