% cfncompress.m created by: Dion Monstavicius % adapted by: Chad Netzer % % this function compresses an input image into % a run length encoded bitstream. The scheme is as follows: % all non zero entries are encoded as is. % whenever a zero is encountered, the total number of zeros to encode % is placed in the bitstream as a negative number. % eg: 0 0 0 4 5 0 0 0 0 0 2 0 4 % would be compressed to: % -3 4 5 -5 2 -1 4 % output = the bit stream % entropy = the entropy of the bit stream function [output, entropy] = cfncompress(input) [A B] = size(input); input = reshape(input, 1, A*B); j = 1; zerocounter = 0; zero_out = []; non_zero_out = []; for i = 1:length(input), if input(i) ~= 0, if zerocounter ~= 0, output(j) = -zerocounter; j = j+1; zero_out(length(zero_out) + 1) = zerocounter; zerocounter = 0; end output(j) = input(i); non_zero_out(length(non_zero_out) + 1) = input(i); j = j+1; else zerocounter = zerocounter + 1; end end if zerocounter ~= 0 output(j) = -zerocounter; end p1 = histc(zero_out, 0:max(zero_out)); p2 = histc(non_zero_out, 0:max(non_zero_out)); p_sum = sum(p1) + sum(p2); p1 = p1/p_sum; p2 = p2/p_sum; p = [ p1 p2]; H = 0; for i = 1:length(p); if p(i) ~= 0, H = H - p(i)*log2(p(i)); end end entropy = H;