%Question No:8
%Write a MATLAB function for implementing Wiener filtering for linear image
%restoration using (a)a constant ratio and (b)autocorrelation function.

function wiener(x)
f=imread(x);
f=im2double(f);
[r c]=size(f);
h=fspecial('gaussian',[r c],1.5);
g=imfilter(f,h,'circular');

a=0.1;
b=0.01;
n=a+b*randn(r,c);
g=g+n;

F=fft2(f);
G=fft2(g);
H=psf2otf(h);
N=fft2(n);
H2=conj(H).*H;
Sn=conj(N).*N;
Sf=conj(F).*F;

snsf=Sn./Sf;
huv=H2./(H2+snsf);
tuv=(1./(H+eps)).*huv;
RA=tuv.*G;
ra=real(ifft2(RA));

smsn=sum(sum(Sn));
smsf=sum(sum(Sf));
sr=smsn/smsf;
huv=H2./(H2+sr);
tuv=(1./(H+eps)).*huv;
RC=tuv.*G;
rc=real(ifft2(RC));

figure,imshow(f),title('Original image');
figure,imshow(g),title('Noisy image');
figure,imshow(ra),title('Restored image - Using Autocorrelation');
figure,imshow(rc),title('Restored image - Using Constant Ratio');
end

