% compress.m created by: Dion Monstavicius % % 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, 0 is placed into the bitstream % FOLLOWED by the number of zeros to encode that follow that zero. % eg: 0 0 0 4 5 0 0 0 0 0 2 0 4 % would be compressed to: % 0 3 4 5 0 5 2 0 1 4 % output = the bit stream % entropy = the entropy of the bit stream function [output, entropy] = compress(input) [A B] = size(input); input = reshape(input, 1, A*B); j = 1; zerocounter = 0; for i = 1:length(input), if input(i) ~= 0, if zerocounter ~= 0, output(j) = 0; output(j+1) = zerocounter; j = j+2; zerocounter = 0; end output(j) = input(i); j = j+1; else zerocounter = zerocounter + 1; end end if zerocounter ~= 0 output(j) = 0; output(j+1) = zerocounter; end limit = max(output); p = hist(output, limit); p = p/sum(p); H = 0; for i = 1:length(p); if p(i) ~= 0, H = H + p(i)*log2(1/p(i)); end end entropy = H;