(matlab图像处理)行程编码

I = imbinarize(rgb2gray(imread('Imgs\Lenna.jpg')));
% I = [2 3 2;
%      7 4 2;
%      7 5 7];  % 测试
[m,n] = size(I);
sig = I(:);  % 转化为一维数据
% 行程编码
enco = runlengthenco(sig);  % 编码
dsing = runlengthdeco(enco);  % 解码
ide = col2im(dsing,[m,n],[m,n],'distinct');  % 把向量重新转换成图像块
figure;
subplot(121),imshow(I,[]),title('原图');
subplot(122),imshow(ide,[]),title('解压图像');

其中函数如下

% 编码
function enco = runlengthenco(sig)
    enco = zeros(1);
    k = 1;
    enco(k) = sig(1);
    enco(k+1) = 1;
    i = 2;
    while (i<=length(sig))
        if (sig(i)==enco(k))
            enco(k+1) = enco(k+1)+1;
        else
            k = k+2;
            enco(k) = sig(i);
            enco(k+1) = 1;
        end
        i = i+1;
    end
    enco = enco';
end

% 解码
function dsing = runlengthdeco(enco)
    dsing = (-1);
    for i = 1:2:length(enco)-1
        for j = 1:enco(i+1)
            dsing = [dsing enco(i)];
        end
    end
    dsing(dsing==-1) = [];
    dsing = dsing';
end

运行结果如下
(matlab图像处理)行程编码_第1张图片

注意

行程编码用于二值图像效果不错,如果图像每两个像素的颜色都不同,这非但不能压缩,反而会使数据量增加一倍

你可能感兴趣的:(matlab图像处理)