matlap中霍夫曼编码压缩图像的两种完整代码
时间: 2024-01-17 20:04:22 浏览: 45
以下是 MATLAB 中使用霍夫曼编码对图像进行压缩的两种完整代码:
方法1:
```matlab
% 读入图像
img = imread('lena.bmp');
% 计算每个像素值的出现频率
freq = imhist(img);
% 构建霍夫曼树
symbols = 0:255; % 像素值
huffTree = hufftree(symbols, freq);
% 生成霍夫曼编码
huffCode = huffcode(huffTree);
% 对图像进行编码
imgVec = img(:);
imgCode = huffencode(imgVec+1, huffCode); % 像素值加1是因为 MATLAB 中数组下标从1开始
% 对图像进行解码
imgDecoded = huffdecode(imgCode, huffTree);
imgDecoded = reshape(imgDecoded, size(img));
% 计算压缩比
bitPerPixel = length(imgCode) / numel(img);
compressionRatio = 8 / bitPerPixel;
% 显示原图和压缩后的图
figure;
subplot(1,2,1);
imshow(img);
title('Original Image');
subplot(1,2,2);
imshow(uint8(imgDecoded));
title(sprintf('Decoded Image (CR=%.2f)', compressionRatio));
```
方法2:
```matlab
% 读入图像
img = imread('lena.bmp');
% 计算每个像素值的出现频率
freq = imhist(img);
% 构建霍夫曼编码
[~, huffCode] = huffmandict(0:255, freq);
% 对图像进行编码
imgVec = img(:);
imgCode = huffmanenco(imgVec+1, huffCode); % 像素值加1是因为 MATLAB 中数组下标从1开始
% 对图像进行解码
imgDecoded = huffmandeco(imgCode, huffCode);
imgDecoded = reshape(imgDecoded, size(img));
% 计算压缩比
bitPerPixel = length(imgCode) / numel(img);
compressionRatio = 8 / bitPerPixel;
% 显示原图和压缩后的图
figure;
subplot(1,2,1);
imshow(img);
title('Original Image');
subplot(1,2,2);
imshow(uint8(imgDecoded));
title(sprintf('Decoded Image (CR=%.2f)', compressionRatio));
```