Search code examples
matlabimage-compressionhaar-waveletlossy-compression

Image Compression using Haar Transform


I am a newbie writing a script for lossy image compression using Matlab.

My first step was to have full level processing of an image, which I am doing by using the following script.

clearvars all;
N = 256;

A=imread('test.jpg');
A=double(rgb2gray(A));
A=imresize(A,[N,N],'bicubic');
image(A);axis equal;colormap hsv;%gray(256) ;% display matrix as density plot

B = A;

while N>1

Q = [1 1;1 -1];
I = eye(N/2);
T = 1.414 * kron(I,Q);
II=eye(N)
I1= II(1:2:N,:);
I2=II(2:2:N,:);
P= [I1;I2];
%create transfer matrix N X N
B(1:N,1:N) = P*T*A(1:N,1:N)*T'*P';
%AR(1:N,1:N) = T'*P'*B(1:N,1:N)*P'*T
N = N/2;
end

imagesc(B);
drawnow;

Further, I want to apply quantization and logarithmic thresholding and order the elements according to their increasing absolute values while retaining those that are in the top 5%.

The following script does that:-

cutoff = 80;
% Decide what fraction of coeffs you want to set to % zero, 
% this fraction is the variable ?cutoff?. .....
%(1);imagesc(A);colormap gray(256)
len = 7;
% Wavelet transform A -> B
X = sort(abs(B(:)));
thresh = X( ceil( cutoff*len^2));
maximum=X(len^2);
lmaxt= log2(maximum/thresh);
% Thresholding & Quantization
for i = 1:len
for j = 1:len
    if(abs(B(i,j)) > thresh)
    sign = B(i,j)/abs(B(i,j));
    ln = log2(abs(B(i,j))/thresh);
    q = ceil( 127*ln/lmaxt); Bq(i,j) = sign*q;
else
    Bq(I,j) = 0;
    end
end
end

figure;(2); spy(Bq)

Now, I would like to reverse the process and get the original image with the haar coefficients set to 70%.

Any pointers would be great.


Solution

  • If you apply quantization with interval length larger than 1, then you cannot recover the original image. The best you can do is to revert the process in inversed order and expect some quantization error.

    First you revert the quantization

    % For all pixels (i,j) s.t. Bq(i,j) > 0
    sign = Bq(i,j) / abs(Bq(i,j));
    q = abs(q)
    % To revert q = ceil(127*ln/lmaxt);
    ln = q*lmaxt/127
    B(i,j) = sign * thresh * pow(2, abs(ln))
    

    Then you invert the haar stage (as you had in your code)

    AR(1:N,1:N) = T'*P'*B(1:N,1:N)*P'*T
    

    Usually the dequantization process is made taking the center of the quantization interval (instead of one of the extremes, the max in this case since you used the ceil function), so you can use instead for slightly better results.

    ln = q*lmaxt/127 - 0.5