基于matlab的JPEG彩色图像编码解码源码

%% 清空环境
close all;
clc;
clear;

%% 图像压缩
filePath='2.bmp';%被压缩的图像的途径


quantizationFactor=0.5;%该变量为量化因子,最小为0.01,最大为255,建议在0.5和3之间,越小质量越好文件越大
I=imread(filePath);%读bmp彩色图像
FileCode=encode(I,quantizationFactor);%压缩图像
%保存文件
savePath='save.myjpeg';%文件保存路径
fileID = fopen(savePath, 'w');
for i=1:8:length(FileCode)-8
    fwrite(fileID,bin2dec(FileCode(i:i+7)),'uint8');
end
i=i+8;
if i<=length(FileCode) %剩余位数不足一个字节,补零
    lastBitsCount=length(FileCode)-i+1;
    lastByte=['0' '0' '0' '0' '0' '0' '0' '0' ];
    lastByte(1:lastBitsCount)=FileCode(i:length(FileCode));
    fwrite(fileID,bin2dec(lastByte),'uint8');
end
fclose(fileID);

%计算压缩比
listing=dir(filePath);
originalSize=listing.bytes;
listing=dir(savePath);
currentSize=listing.bytes;
disp(['压缩比率为' num2str(originalSize/currentSize)]);

%% 读取文件并解压缩图像
fileID2 = fopen(savePath, 'r');
Bytes=fread(fileID2,inf,'uint8');
fclose(fileID2);
Codes=dec2bin(Bytes,8);%传化为字符串,方便解码时取一位操作
FileCode2=reshape(Codes',1,length(Codes)*8);%获得字符代表码流,将每组字节码,合并成一个字符串
I2=decode(FileCode2);%解压缩

%% 测试对比
[m n ~]=size(I2);
disp(['比特率为' num2str(currentSize*8/(m*n))]);%输出比特率
disp(['信噪比为' num2str(PSNR(I,I2))]);%输出信噪比
%原图像与压缩图像对比imwrite
figure('Name','原图像','NumberTitle','off'),imshow(I);
figure('Name','压缩图像','NumberTitle','off'),imshow(I2);

评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

fpga和matlab

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值