影像壓縮編碼碼matlab實現——算術編碼

fpga&matlab發表於2020-12-24

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:待編碼字串

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)];
sbidx = zeros(size(seqin));
for i = 1: length(seqin),
    sbidx(i) = find(symbol == seqin(i));
end

low = 0; high = 1;
for i = 1: length(seqin),
    range = high - low;
    high = low + range * high_range(sbidx(i));
    low = low + range * low_range(sbidx(i));
end
arcode = low;
 

相關文章