In: Electrical Engineering
Use SVD method to compress and decompress images in the MATLAB.
Compression function. The input is an image file and k. The output is a text file containing the reduced U, V , and the reduced diagonals of ?.
Decompression function. The input is the output of the compression code. The output is an image (you can use imshow for this purpose).
Copy the following code. Enter an integer when promted for input. You can run this program for varous values of reduced vectors.
function svdImg()
global r;
global M;
r=input('Number of vectors for reconstruction');
%Reading input image
img = imread('coins.png');
figure,imshow(img,[]);
title('Original image');
[M,N] =size(img);
%Calling Compression function
[FilePath] = comprSvd(img);
%Decompression Code
recImg = deComprSvd(FilePath);
end
function [FilePath] = comprSvd(img)
%Compression function takes image as input,and produces a txt file
as
%output
global r;
%Compute SVD
[U,S,V] = svd(double(img));
%Assign reduced vectors
Ur = U(:,1:r);
Sr = S(1:r,1:r);
Vr = V(:,1:r);
%File name
FilePath = 'coef.txt';
%Writing data file
dlmwrite(FilePath,[Ur;Sr;Vr]);
end
function imgRecon = deComprSvd(inptFilePath)
%Decompression function takes txtfile as input and produces
the
%reconstructed image.
global r;
global M;
%Reading txt file
K = dlmread(inptFilePath);
%Assigning reduced vectors
Ur = K(1:M,:);
Sr = K(M+1:M+r,:);
Vr = K(M+r+1:end,:);
%Reconstructing image
imgRecon = Ur*Sr*Vr';
figure,imshow(imgRecon,[]);
title(['Reconstruction with ' num2str(r) ' singular
values']);
end
Typical Output:
>> svdImg
Number of vectors for reconstruction30
>>
Output images:
The following are the reconstructed imagese with 50,100
It can be observed that the quality of the reconstructed image is increasing as the number of vectors is increasing