压缩比为8:1的灰度图DCT压缩MATLAB代码
时间: 2024-02-26 08:51:36 浏览: 87
对一幅灰度图像的DCT处理(MATLAB )
5星 · 资源好评率100%
以下是MATLAB代码实现8:1的灰度图DCT压缩,其中我们使用了JPEG标准中的量化矩阵,并采用了Huffman编码进行熵编码:
```matlab
% 读入原始图像
I = imread('lena_gray.png');
% 将灰度图像分成大小相等的块
block_size = 8;
[M, N] = size(I);
Mb = floor(M/block_size);
Nb = floor(N/block_size);
blocks = zeros(block_size, block_size, Mb*Nb);
for i = 1:Mb
for j = 1:Nb
idx = (i-1)*Nb+j;
blocks(:,:,idx) = double(I((i-1)*block_size+1:i*block_size, (j-1)*block_size+1:j*block_size));
end
end
% 定义JPEG标准中的量化矩阵
Q = [
16 11 10 16 24 40 51 61;
12 12 14 19 26 58 60 55;
14 13 16 24 40 57 69 56;
14 17 22 29 51 87 80 62;
18 22 37 56 68 109 103 77;
24 35 55 64 81 104 113 92;
49 64 78 87 103 121 120 101;
72 92 95 98 112 100 103 99
];
% 对每个块进行DCT变换
dct_blocks = zeros(block_size, block_size, Mb*Nb);
for i = 1:Mb*Nb
dct_blocks(:,:,i) = dct2(blocks(:,:,i));
end
% 对频域系数矩阵进行量化处理
quant_blocks = zeros(block_size, block_size, Mb*Nb);
for i = 1:Mb*Nb
quant_blocks(:,:,i) = round(dct_blocks(:,:,i)./Q);
end
% 对量化后的矩阵进行熵编码
huff_blocks = cell(1, Mb*Nb);
for i = 1:Mb*Nb
huff_blocks{i} = huffmanenco(reshape(quant_blocks(:,:,i)', 1, []), huffmandict(1:256, Q(:)'));
end
% 将压缩后的数据进行解码和反量化
decode_blocks = zeros(block_size, block_size, Mb*Nb);
for i = 1:Mb*Nb
decode_blocks(:,:,i) = reshape(huffmandeco(huff_blocks{i}, huffmandict(1:256, Q(:)')), block_size, block_size)';
decode_blocks(:,:,i) = decode_blocks(:,:,i).*Q;
end
% 对近似块进行IDCT反变换
idct_blocks = zeros(block_size, block_size, Mb*Nb);
for i = 1:Mb*Nb
idct_blocks(:,:,i) = idct2(decode_blocks(:,:,i));
end
% 将所有的块拼接起来,得到整个压缩后的图像
compressed_I = zeros(M, N);
for i = 1:Mb
for j = 1:Nb
idx = (i-1)*Nb+j;
compressed_I((i-1)*block_size+1:i*block_size, (j-1)*block_size+1:j*block_size) = idct_blocks(:,:,idx);
end
end
% 显示压缩前后的图像
figure, imshow(I), title('Original Image');
figure, imshow(uint8(compressed_I)), title('Compressed Image');
```
需要注意的是,由于MATLAB中的`huffmandict`函数在生成Huffman树时会对输入数据进行排序,因此我们需要将量化矩阵展成一维数组并按照从小到大的顺序排列,以保证压缩和解压缩时使用同一个Huffman字典。
阅读全文