天天看點

圖像壓縮編碼碼matlab實作——算術編碼

clear all

clc

format long;

symbol = ['abcd'];

pr = [0.1 0.4 0.2 0.3];

seqin = ['cadacdb'];

codeword = arencode(symbol, pr, seqin)

seqout = ardecode(symbol, pr, codeword, 7)

function symseq = ardecode(symbol, pr, codeword, symlen)

%給定字元機率的算術編碼

%輸出:symse:字元串

%輸入:symbol:由字元組成的行向量

%      pr:字元出現的機率

%      codeword:碼字

%      symlen:待解碼字元串長度

format long

high_range = [];

for k = 1 : length(pr),

    high_range = [high_range sum(pr(1 : k))];

end

low_range = [0 high_range(1 : length(pr) - 1)];

prmin = min(pr);

symseq = [];

symseq = [];

for i = 1 : symlen,

    index = max(find(low_range <= codeword));

    codeword = codeword - low_range(index);

    %duo to numerical error, sometimes the encoded number

    %will be slightly smaller than the current lower bound.

    %If this happens, a correction is required.

    if abs(codeword - pr(index)) < 0.01 * prmin,

        index = index + 1;

        codeword = 0;

    end

    symseq = [symseq symbol(index)];

    codeword = codeword/pr(index);

    if abs(codeword) < 0.01 * prmin,

        i = symlen + 1;        %break the for loop immediately

    end

end

function arcode = arencode(symbol, pr, seqin)

%算術編碼

%輸出:碼串

%輸入:symbol:字元行向量

%      pr:字元出現機率

%      seqin:待編碼字元串