Inverse Fourier Transform function gives wrong result - matlab

I am implementing a code for image enhancement and to apply Fourier and inverse Fourier transform I am using the code below but in result it gives black image.
F = fft2(image); F = fftshift(F); % Center FFT
F = abs(F); % Get the magnitude
F = log(F+1); % Use log, for perceptual scaling, and +1 since log(0) is undefined
F = mat2gray(F); % Use mat2gray to scale the image between 0 and 1
Y = ifft2(F);
subplot(1,1,1);
imshow(Y,[]); % Display the result

You try to image the inverse FFT of a matrix which is pure real (and positive), abs(F). The inverse FT of that is a complex one, and since you lose the phase of the original FT, you will get strange result (almost black image, with eventually the first pixel white...).
Second error, you shift the fft to make some computations, but you don't inverse the shift before
For what you want, you have to keep the phase of the FFT:
F = fft2(image); F = fftshift(F); % Center FFT
Fp = angle(F); % Get the phase
F = abs(F); % Get the magnitude
F = log(F+1); % Use log, for perceptual scaling, and +1 since log(0) is undefined
F = mat2gray(F); % Use mat2gray to scale the image between 0 and 1
Y = real(ifft2(ifftshift(F.*exp(1i*Fp))));
subplot(1,1,1);
imshow(Y,[]); % Display the result
Note: you need to take the real part of the inverse FFT since Matlab creates automatically a complex array as output of a FT (direct or inverse), even if it is a real output. You can check this if you see the value of max(abs(imag(Y(:)))), 6e-11 on my computer.

Related

How can I restore my image back from the Fourier Spectrum

I've taken the following image:
PandaNoise.bmp and tried to remove the periodic noise by focusing on its Fourier spectrum. Commented lines are the ones I'm not sure about. I can't get it back to the image plane. What am I doing wrong here?
panda = imread('PandaNoise.bmp');
fpanda = fft2(panda); % 2d fast fourier transform
fpanda = fftshift(fpanda); % center FFT
fpanda = abs(fpanda); % get magnitude
fpanda = log(1 + fpanda); % use log to expand range of dark pixels into bright region
fpanda = mat2gray(fpanda); % scale image from 0 to 1
figure; imshow(fpanda,[]); % show the picture
zpanda = fpanda;
zpanda(fpanda<0.5)=0;
zpanda(fpanda>0.5)=1;
%img = ifft2(zpanda);
%img = ifftshift(img);
%img = exp(1-img);
%img = abs(img);
Here is an example of how to work with the complex Fourier transform. We can take the log modulus for display, but don't change the original Fourier transform matrix, since the phase information that we throw away with abs is very important.
% Load data
panda = imread('https://i.stack.imgur.com/9SlW5.png');
panda = im2double(panda);
% Forward transform
fpanda = fft2(panda);
% Prepare FT for display -- don't change fpanda!
fd = fftshift(fpanda);
fd = log(1 + abs(fd));
figure; imshow(fd,[]); % show the picture
% From here we learn that we should keep the central 1/5th along both axes
% Low-pass filter
sz = size(fpanda);
center = floor(sz/2)+1;
half_width = ceil(sz/10)-1;
filter = zeros(sz);
filter(center(1)+(-half_width(1):half_width(1)),...
center(2)+(-half_width(2):half_width(2))) = 1;
filter = ifftshift(filter); % The origin should be on the top-left, like that of fpanda.
fpanda = fpanda .* filter;
% Inverse transform
newpanda = ifft2(fpanda);
figure; imshow(newpanda);
After computing the ifft2, newpanda is supposed to be purely real-valued if we designed the filter correctly (i.e. perfectly symmetric around the origin). Any imaginary component still present should be purely numerical innacuracy. MATLAB will detect that the input to ifft2 is conjugate symmetric, and return a purely real result. Octave will not, and you would have to do newpanda=real(newpanda) to avoid warnings from imshow.

How to do circular convolution between 2 functions with cconv?

I was asked to do circular convolution between two functions by sampling them, using the functions cconv. A known result of this sort of convolution is: CCONV( sin(x), sin(x) ) == -pi*cos(x)
To test the above I did:
w = linspace(0,2*pi,1000);
l = linspace(0,2*pi,1999);
stem(l,cconv(sin(w),sin(w))
but the result I got was:
which is absolutely not -pi*cos(x).
Can anybody please explain what is wrong with my code and how to fix it?
In the documentation of cconv it says that:
c = cconv(a,b,n) circularly convolves vectors a and b. n is the length of the resulting vector. If you omit n, it defaults to length(a)+length(b)-1. When n = length(a)+length(b)-1, the circular convolution is equivalent to the linear convolution computed with conv.
I believe that the reason for your problem is that you do not specify the 3rd input to cconv, which then selects the default value, which is not the right one for you. I have made an animation showing what happens when different values of n are chosen.
If you compare my result for n=200 to your plot you will see that the amplitude of your data is 10 times larger whereas the length of your linspace is 10 times bigger. This means that some normalization is needed, likely a multiplication by the linspace step.
Indeed, after proper scaling and choice of n we get the right result:
res = 100; % resolution
w = linspace(0,2*pi,res);
dx = diff(w(1:2)); % grid step
stem( linspace(0,2*pi,res), dx * cconv(sin(w),sin(w),res) );
This is the code I used for the animation:
hF = figure();
subplot(1,2,1); hS(1) = stem(1,cconv(1,1,1)); title('Autoscaling');
subplot(1,2,2); hS(2) = stem(1,cconv(1,1,1)); xlim([0,7]); ylim(50*[-1,1]); title('Constant limits');
w = linspace(0,2*pi,100);
for ind1 = 1:200
set(hS,'XData',linspace(0,2*pi,ind1));
set(hS,'YData',cconv(sin(w),sin(w),ind1));
suptitle("n = " + ind1);
drawnow
% export_fig(char("D:\BLABLA\F" + ind1 + ".png"),'-nocrop');
end

Linear regression -- Stuck in model comparison in Matlab after estimation?

I want to determine how well the estimated model fits to the future new data. To do this, prediction error plot is often used. Basically, I want to compare the measured output and the model output. I am using the Least Mean Square algorithm as the equalization technique. Can somebody please help what is the proper way to plot the comparison between the model and the measured data? If the estimates are close to true, then the curves should be very close to each other. Below is the code. u is the input to the equalizer, x is the noisy received signal, y is the output of the equalizer, w is the equalizer weights. Should the graph be plotted using x and y*w? But x is noisy. I am confused since the measured output x is noisy and the model output y*w is noise-free.
%% Channel and noise level
h = [0.9 0.3 -0.1]; % Channel
SNRr = 10; % Noise Level
%% Input/Output data
N = 1000; % Number of samples
Bits = 2; % Number of bits for modulation (2-bit for Binary modulation)
data = randi([0 1],1,N); % Random signal
d = real(pskmod(data,Bits)); % BPSK Modulated signal (desired/output)
r = filter(h,1,d); % Signal after passing through channel
x = awgn(r, SNRr); % Noisy Signal after channel (given/input)
%% LMS parameters
epoch = 10; % Number of epochs (training repetation)
eta = 1e-3; % Learning rate / step size
order=10; % Order of the equalizer
U = zeros(1,order); % Input frame
W = zeros(1,order); % Initial Weigths
%% Algorithm
for k = 1 : epoch
for n = 1 : N
U(1,2:end) = U(1,1:end-1); % Sliding window
U(1,1) = x(n); % Present Input
y = (W)*U'; % Calculating output of LMS
e = d(n) - y; % Instantaneous error
W = W + eta * e * U ; % Weight update rule of LMS
J(k,n) = e * e'; % Instantaneous square error
end
end
Lets start step by step:
First of all when using some fitting method it is a good practice to use RMS error . To get this we have to find error between input and output. As I understood x is an input for our model and y is an output. Furthermore you already calculated error between them. But you used it in loop without saving. Lets modify your code:
%% Algorithm
for k = 1 : epoch
for n = 1 : N
U(1,2:end) = U(1,1:end-1); % Sliding window
U(1,1) = x(n); % Present Input
y(n) = (W)*U'; % Calculating output of LMS
e(n) = x(n) - y(n); % Instantaneous error
W = W + eta * e(n) * U ; % Weight update rule of LMS
J(k,n) = e(n) * (e(n))'; % Instantaneous square error
end
end
Now e consists of errors at the last epoch. So we can use something like this:
rms(e)
Also I'd like to compare results using mean error and standard deviation:
mean(e)
std(e)
And some visualization:
histogram(e)
Second moment: we can't use compare function just for vectors! You can use it for dynamic system models. For it you have to made some workaround about using this method as dynamic model. But we can use some functions as goodnessOfFit for example. If you want something like error at each step that consider all previous points of data then make some math workaround - calculate it at each point using [1:currentNumber].
About using LMS method. There are built-in function calculating LMS. Lets try to use it for your data sets:
alg = lms(0.001);
eqobj = lineareq(10,alg);
y1 = equalize(eqobj,x);
And lets see at the result:
plot(x)
hold on
plot(y1)
There are a lot of examples of such implementation of this function: look here for example.
I hope this was helpful for you!
Comparison of the model output vs observed data is known as residual.
The difference between the observed value of the dependent variable
(y) and the predicted value (ŷ) is called the residual (e). Each data
point has one residual.
Residual = Observed value - Predicted value
e = y - ŷ
Both the sum and the mean of the residuals are equal to zero. That is,
Σ e = 0 and e = 0.
A residual plot is a graph that shows the residuals on the vertical
axis and the independent variable on the horizontal axis. If the
points in a residual plot are randomly dispersed around the horizontal
axis, a linear regression model is appropriate for the data;
otherwise, a non-linear model is more appropriate.
Here is an example of residual plots from a model of mine. On the vertical axis is the difference between the output of the model and the measured value. On the horizontal axis is one of the independent variables used in the model.
We can see that most of the residuals are within 0.2 units which happens to be my tolerance for this model. I can therefore make a conclusion as to the worth of the model.
See here for a similar question.
Regarding you question about the lack of noise in your models output. We are creating a linear model. There's the clue.

Account for overrotation of imaginary argument in MATLAB

Let's say we have some Fourier transform with an imaginary and real part.
Calculating the magnitude for some frequency is simple as shown in the code below.
However if the frequency, in this case p=1, is for example 1000 then we have an issue. We need to account for the fact that the imaginary part has to be in between -pi and pi.
For example. Let's say that my imaginary part is Im => w-100 and my real part is just Re => 1.
The angle/phase would be: arctan(Im/Re) = arctan(w-100). Simply substituting a value for w will not work. We need to subtract the extraneous full rotations and pass that to the arctan function.
How would I do that?
p = 1; % Value given in argument
x1 = exp(-4*(t-2))*cos(9*t)*heaviside(t); % define function
F = fourier(x1,t,w); % fourier transformation
sub1 = double(subs(F,w,p)); % SUBSTITUTE value for omega
mod1 = abs(sub1) % print out modulus
ang1 = angle(sub1) % print out phase angle
NOTE: The fourier transform returns a symbolic function. Hence I'm casting it to a double in sub1.
Check this Matlab function, which works under some cases very well :)... I've used it several cases for resolving Fourier Spectrums with a nice "unwrapped" phase :D:D:
ang2=unwrap(ang1);
If this do not work, try to pre-multiply after and before to fit in the pi fractions....
EDIT
Are you needing this?:
% Fourier Transform
syms t v;
w=(0:1:100*pi)';
lw=length(w);
x = exp(-4*(t-2))*cos(9*t)*heaviside(t); % Function
F = fourier(x,t,v); % Fourier Transform
F0= double(subs(F,v,w)); % Symbolic Substitution
f = abs(F0); % Magnitude
th = angle(F0); % Phase (unwrap not required)
%th=unwrap(angle(F0)); % Unwrapped Phase
% Plot
ha=plotyy(w,f,w,th);
title('Fourier Transform');
xlabel('Frequency - \omega');
ylabel(ha(1),'Magnitude - |f|');
ylabel(ha(2),'Phase - \theta');
If so, no unwrapping of the phase is required, which smoothy varies from pi/2 at w=-inf to -pi/2 at w=inf....

Matlab inverse FFT from phase/magnitude only

So I have this image 'I'. I take F = fft2(I) to get the 2D fourier transform. To reconstruct it, I could go ifft2(F).
The problem is, I need to reconstruct this image from only the a) magnitude, and b) phase components of F. How can I separate these two components of the fourier transform, and then reconstruct the image from each?
I tried the abs() and angle() functions to get magnitude and phase, but the phase one won't reconstruct properly.
Help?
You need one matrix with the same magnitude as F and 0 phase, and another with the same phase as F and uniform magnitude. As you noted abs gives you the magnitude. To get the uniform magnitude same phase matrix, you need to use angle to get the phase, and then separate the phase back into real and imaginary parts.
> F_Mag = abs(F); %# has same magnitude as F, 0 phase
> F_Phase = cos(angle(F)) + j*(sin(angle(F)); %# has magnitude 1, same phase as F
> I_Mag = ifft2(F_Mag);
> I_Phase = ifft2(F_Phase);
it's too late to put another answer to this post, but...anyway
# zhilevan, you can use the codes I have written using mtrw's answer:
image = rgb2gray(imread('pillsetc.png'));
subplot(131),imshow(image),title('original image');
set(gcf, 'Position', get(0, 'ScreenSize')); % maximize the figure window
%:::::::::::::::::::::
F = fft2(double(image));
F_Mag = abs(F); % has the same magnitude as image, 0 phase
F_Phase = exp(1i*angle(F)); % has magnitude 1, same phase as image
% OR: F_Phase = cos(angle(F)) + 1i*(sin(angle(F)));
%:::::::::::::::::::::
% reconstruction
I_Mag = log(abs(ifft2(F_Mag*exp(i*0)))+1);
I_Phase = ifft2(F_Phase);
%:::::::::::::::::::::
% Calculate limits for plotting
% To display the images properly using imshow, the color range
% of the plot must the minimum and maximum values in the data.
I_Mag_min = min(min(abs(I_Mag)));
I_Mag_max = max(max(abs(I_Mag)));
I_Phase_min = min(min(abs(I_Phase)));
I_Phase_max = max(max(abs(I_Phase)));
%:::::::::::::::::::::
% Display reconstructed images
% because the magnitude and phase were switched, the image will be complex.
% This means that the magnitude of the image must be taken in order to
% produce a viewable 2-D image.
subplot(132),imshow(abs(I_Mag),[I_Mag_min I_Mag_max]), colormap gray
title('reconstructed image only by Magnitude');
subplot(133),imshow(abs(I_Phase),[I_Phase_min I_Phase_max]), colormap gray
title('reconstructed image only by Phase');