JPEG图像压缩的代码
时间: 2023-07-02 21:16:25 浏览: 96
以下是基于Matlab实现的JPEG图像压缩代码:
```matlab
% 读取图像
img = imread('image.jpg');
% 将图像划分为8x8的小块
img = im2double(img);
[h, w, c] = size(img);
n_h = floor(h/8) * 8;
n_w = floor(w/8) * 8;
img = img(1:n_h, 1:n_w, :);
blocks = reshape(img, 8, 8, n_h/8, n_w/8);
% DCT变换
dct_blocks = zeros(size(blocks));
for i = 1:n_h/8
for j = 1:n_w/8
dct_blocks(:, :, i, j) = dct2(blocks(:, :, i, j));
end
end
% 量化矩阵
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];
% 量化
quant_blocks = zeros(size(blocks));
for i = 1:n_h/8
for j = 1:n_w/8
quant_blocks(:, :, i, j) = round(dct_blocks(:, :, i, j) ./ (Q*quality));
end
end
% 熵编码
bits = cell(n_h/8, n_w/8);
for i = 1:n_h/8
for j = 1:n_w/8
zz = zigzag(quant_blocks(:, :, i, j));
bits{i, j} = huffman(zz);
end
end
% 显示压缩结果
compressed_size = 0;
for i = 1:n_h/8
for j = 1:n_w/8
compressed_size = compressed_size + length(bits{i, j});
end
end
fprintf('压缩率: %.2f\n', compressed_size / (n_h*n_w*3*8));
% 解压缩
decoded_blocks = zeros(size(blocks));
for i = 1:n_h/8
for j = 1:n_w/8
zz = huffman_decode(bits{i, j});
quant_blocks(:, :, i, j) = zigzag_inverse(zz);
decoded_blocks(:, :, i, j) = quant_blocks(:, :, i, j) .* (Q*quality);
end
end
% IDCT变换
decoded_img = zeros(n_h, n_w, c);
for i = 1:n_h/8
for j = 1:n_w/8
decoded_img((i-1)*8+1:i*8, (j-1)*8+1:j*8, :) = idct2(decoded_blocks(:, :, i, j));
end
end
% 显示原图和解压缩后的图像
figure;
subplot(1, 2, 1);
imshow(img);
title('原图');
subplot(1, 2, 2);
imshow(decoded_img);
title('解压缩后的图像');
```
其中,`quality`是压缩质量,取值范围为0~1,即0表示最差质量,1表示最好质量。`zigzag`和`zigzag_inverse`函数分别是蛇形扫描和逆蛇形扫描,用于将8x8的块展开成一维向量和将一维向量还原成8x8的块。`huffman`和`huffman_decode`函数分别是Huffman编码和解码函数,用于将量化后的系数进行熵编码和解码。
阅读全文