In today’s post, I will show you how to perform a two-dimensional Fast Fourier Transform in Matlab. The 2D Fourier Transform is an indispensable tool in many fields, including image processing, radar, optics and machine vision. In image processing, the 2D Fourier Transform allows one to see the frequency spectrum of the data in both dimensions and lets one visualize filtering operations more easily. In radar, the 2D Fourier Transform is used as a fast way to create a map from a series of coherent radar pulses. Additionally, the far-field pattern of a 2D antenna can be calculated using a 2D Fourier Transform. In Fourier Optics, the 2D Fourier Transform is used to calculate the propagation of electromagnetic waves and through space and optical elements.

The 2D Fourier Transform is simply a Fourier Transform over one dimension of the data, followed by a Fourier Transform over the second dimension of the data. The 2D Inverse Fourier Transform is just the inverse Fourier Transform performed over both dimensions of the data. The formulas for the 2D Digital Fourier Transform and Inverse Transform, courtesy of Rice University, are as follows:

In the following example, I will perform a 2D FFT on two images, switch the magnitude and phase content, and perform 2D IFFTs to see the results. This exercise will hopefully provide some insight into how to perform the 2D FFT in Matlab and help you understand the magnitude and phase in Fourier domain. Here is the code for this example:

%2D FFT Demo

%Import images

imageA = imread('greekchurch','jpg'); imageB = imread('aishwarya','jpg');

%Display images

figure, imshow(imageA) title('Image A - Greek Church') figure, imshow(imageB) title('Image B - Aishwarya Rai')

%Perform 2D FFTs

fftA = fft2(double(imageA)); fftB = fft2(double(imageB));

%Display magnitude and phase of 2D FFTs

figure, imshow(abs(fftshift(fftA)),[24 100000]), colormap gray title('Image A FFT2 Magnitude') figure, imshow(angle(fftshift(fftA)),[-pi pi]), colormap gray title('Image A FFT2 Phase') figure, imshow(abs(fftshift(fftB)),[24 100000]), colormap gray title('Image B FFT2 Magnitude') figure, imshow(angle(fftshift(fftB)),[-pi pi]), colormap gray title('Image B FFT2 Phase')

%Switch magnitude and phase of 2D FFTs

fftC = abs(fftA).*exp(i*angle(fftB)); fftD = abs(fftB).*exp(i*angle(fftA));

%Perform inverse 2D FFTs on switched images

imageC = ifft2(fftC); imageD = ifft2(fftD);

%Calculate limits for plotting

cmin = min(min(abs(imageC))); cmax = max(max(abs(imageC))); dmin = min(min(abs(imageD))); dmax = max(max(abs(imageD)));

%Display switched images

figure, imshow(abs(imageC), [cmin cmax]), colormap gray title('Image C Magnitude') figure, imshow(abs(imageD), [dmin dmax]), colormap gray title('Image D Magnitude')

%Save images

saveas(1,'imageA.png') saveas(2,'imageB.png') saveas(3,'imageAfftmag.png') saveas(4,'imageAfftpha.png') saveas(5,'imageBfftmag.png') saveas(6,'imageBfftpha.png') saveas(7,'imageC.png') saveas(8,'imageD.png')

Notice that imread is used to import the images into Matlab. This function can handle most of the standard image file formats, such as bmp, jpg, tiff and png. In this example, imshow is used to display the images. *Imshow* is one of several functions that plots images, but this function automatically eliminates the axes, displaying the images nicely. This function works well for original images, but when the Fourier transform of an image, or any other significant image processing, is performed, color limits should be adjusted to display a sufficient amount of detail in the data. Imagesc can also be used to display the images. Below are the images that were used in this example, a Greek church on the island of Santorini and Aishwarya Rai.

The 2D FFTs are accomplished using fft2. The image files are imported as uint8, so they should be converted to double arrays before doing the FFTs. The FFT of real, non-even data is complex, so the magnitude and phase of the 2D FFTs should be displayed. The function fftshift is used shift the quadrants of the FFT around to see the lowest frequencies in the center of the plot. *Fftshift* only has to be called once, as it automatically shifts the quadrants around for 2D matrices. Below are the 2D FFTs of the two images.

Look at the FFTs of the two images. Most of the energy in the Fourier domain is present in the center of the image, which corresponds to low frequency data in the image domain. This corresponds to the many gradual changes in the images. However, the FFT of the Greek church, image A, has a diagonal line intersecting the center of the plot. This line is perpendicular to the edge of the wall in the original image. A strong line across an image will produce a perpendicular line in its FFT. Additionally, the Greek church has more sharp, geometric features than the picture of Aishwarya Rai, so there is more energy in the higher frequencies, away from the center of the FFT.

The phase of the FFTs is somewhat hard to interpret visually and generally looks like noise. However, the phase holds a great deal of the information needed to reconstruct the image. To demonstrate the role of the phase of the FFT, I switched the magnitude and phase of the two images in the Fourier domain then performed an inverse 2D FFT to view the results. The two mixed images are shown below.

Image C has the magnitude of the Greek church and the phase of Aishwarya Rai, while Image D has the opposite. You can see that most of the information in the image that we perceive is stored in phase. To display the images properly using *imshow*, the color range of the plot must the minimum and maximum values in the data. Additionally, 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.

So that is it for this week’s post. In my next post, I will create another example that shows how to do image processing with the 2D FFT.

Previous posts on Fourier Transforms

For hottest news you have to go to see internet and on the web

I found this website as a most excellent web page for most recent updates.

However, thee question remains aree these sitews nothing

more than. Nowadays, companies have realized thst the best waay to earn prtofit is ojly through growth ‘

profitable growth. Combine several ideas into one package and offer a discount for hiring

you for multiple services.

This paragraph is genuinely a nice one it helps new net viewers, who are wishing

for blogging.

can any one tell me from where this number [24 100000]

comes, i find this as

imagemax=max(max(abs(F)))

imagemin=min(min(abs(F)))

where F=fft2(image)

and put it like [imagemax imagemin]

but it gives me error and shows a blank white plane in magnitude spectrum. phase spectrum is fine.

why did you write

cmin = min(min(abs(imageC)));

why do we need two min?

{min(min())}

imageC is a matrix, the first min() creates a vector of the lowest value in each column, then the second min() finds the min of that vector, returning the smallest value in the matrix.

Hello! How i can recover (Image C, D Magnitude) same original image?

Pingback: What does frequency domain denote in case of images? | DL-UAT

I perfomed fft2 for an image.while doing inverse for the fft output i got a warning message as: Warning: Displaying real part of complex input. and the image is not displayed.please help me if you know.

Of the panoply of website I’ve pored over this has the most veatricy.

Ive actually been eying that bottle of plum sauce at the store for a bit always afraid it would end up disappointing. Plus I had no idea what to do with it. Great use of pre-made sauce (and letting me know that it's worth the buy)

a classic example of the idiocy of the left; if you don’t agree with me you are a stupid drooling baby; imagine the tantrum this twit will have if Ford actually wins; now that would be a reality show I might like to see

That’s way the bestest answer so far!

Hello everyone, it’s my first visit at this website,

and piece of writing is genuinely fruitful for me, keep up posting these articles or reviews.

This excellent website certainly has all of the info I wanted about

this subject and didn’t know who to ask.

to very usful for fft based any images

we are applying both rgb and gray scale images

for applying rgb images to remove the low components and remaing to show the high components

to very usful for fft based any images

we are applying both rgb and gray scale images

for applying rgb images to remove the low components and remaing to show the high components

Hello Eric, Thanks for the useful post so much : )

I’ve a problem when i execute this line

figure, imshow(fftshift(fftA),[24 100000]), colormap gray

it produces a white image not as the magnitude illustrated above, any help? Thanks in advance.

Hello every body,

I am using atmospheric airglow images. i am trying to do 2D fft for these images in matlab… when i am using the comment

F=fft2(double(adj));

it is giving the following response…

“Function definitions are not permitted in this context.”

let me know how to do fft for airglow images..

Hello every body,

I am using atmospheric airglow images. i am trying to do 2D fft for these images in matalb… when i am using the comment

F=fft2(double(adj));

it is giving the following response…

“Function definitions are not permitted in this context.”

let me know how to do fft for airglow images..

Hello every body,

I am using atmospheric airglow images. i am trying to do 2D fft for these images… when i am using the comment

F=fft2(double(adj));

it is giving the following response…

“Function definitions are not permitted in this context.”

let me know how to do fft for airglow images..

I relish, cause I discovered exactly what I used to be having a look

for. You’ve ended my four day lengthy hunt!

God Bless you man. Have a great day. Bye

I am actually glad to read this blog posts which includes tons of useful facts, thanks for providing such information.

All,

I am late to this particular party, but I too was having lots of errors when attempting to run this code in matlab. The problem was that is was importing the images in RGB, such that it was a 3D matrix instead of 2D.

To fix, I added two lines of code, just after the imread lines:

imageA = imageA(:,:,1);

imageB = imageB(:,:,1);

run the rest as is, and it works perfectly.

-Tevis

Error using .*

Matrix dimensions must agree.

Error in fourier_t (line 26)

fftC = abs(fftA).*exp(j.*angle(fftB));

how to remove this error?

i used pout.tif and rice.png images from matlab image toolbox and it didnt worked but with rice.png and cameraman.tif combo it wokrked. is there any way to make it work with pout.tif and rice.png combo ??

Both images must have same size i.e. number of rows and columns must b same. Use matlab’s imresize function.

imageA = imread(‘rice.png’);

imageB = imread(‘pout.tif’);

imageC = imresize(imageB, [256 256]);

hello, i need to know if there’s a way to do the 2D fft but without using the command fft2 in matlab…please help me

It’s awesome to pay a visit this site and reading the views

of all mates on the topic of this piece of writing, while I am

also zealous of getting familiarity.

Assalamualaikum. Thanks! JazakAllah.

It is perfect time to make some plans for the future and it is time to be happy.

I have read this post and if I could I desire to suggest you some interesting things or advice.

Maybe you can write next articles referring to this article.

I want to read more things about it!

Can u please help me to provide Matlab Code for Fractional Fourier Transform of an image.

Garima, have you got Matlab Code for Fractional Fourier Transform of an image ?

Not Yet

Yes! Finally something about beauty treatment lancaster.

Yes! Finally something about beauty treatment lancaster.

I have an image of a spectrum taken by my iphone4. I have used imageJ software to plot a graph of Greyscale vs. pixel distance. now I want to convert my scale of pixel distance into” wavelength in nm.” If 1 pixel=.33nm. Then How can I convert my graph from “Greyscale vs. Pixels” to “Greyscale vs. Wavelength” in nm.?

That’s the best answer by far! Thanks for cotunibtnirg.

Excellent post. I have taken the liberty to reprint it on my blog, since as I noted, you did a better job than I would have done. It's been fully attributed to you, but if any objections, please let me know, and I will remove it.

about wondering if the consumerism associated with the sport balances out with the benefits of raising the value of nature and a healthy lifestyle. I think it does.Athletes like you and Scott not only draw attention to the value of our world in its natural condition, but you also encourage everyone to realize that we're capable of so much more than what we may believe about ourselves. I know I'm grateful.Whoa. That was way serious…umm…quick, something funny…hey, remember that scene in Zombieland where the dude has to make a second lap to unlock his car? Yeah…that was rad.

Heh, kenellÃ¤ opiskelijalla on neljÃ¤ kuukautta lomaa?Ei minulla ainakaan, ei ole koskaan ollut? TÃ¶issÃ¤ on pakko kÃ¤ydÃ¤ ympÃ¤ri vuoden eikÃ¤ ole mitÃ¤Ã¤n viiden viikon lomaa vielÃ¤ siunaantunut.

figure, imshow(abs(fftshift(fftA)),[24 100000]), colormap gray

why [24 100000] is given ? can anyone tell me please?

i want to 2D transform Fourier & inverse Fourier from a image and use this code:

hfft2d = vision.FFT;

hcsc = vision.ColorSpaceConverter(‘Conversion’, ‘RGB to intensity’);

hgs = vision.GeometricScaler(‘SizeMethod’, ‘Number of output rows and columns’, ‘Size’, [512 512]);

x = imread(‘fouri1.png’);

x1 = step(hgs,x);

ycs = step(hcsc, x1);

y = step(hfft2d, ycs);

y1 = ifftshift(double(y));

imshow(log(max(abs(y1), 1e-6)),[]);

colormap(jet(64));

but for inverse i have problems.please guide me……

Hi Sir,

I would like to deblur a blur image and i need to find the parameters of motion blur (eg. blur length and blur direction). I’m wondering how i can use the FFT to find the blur direction from blurred image.

Thanks

Appreciate for your helps ~!

Hi Eric

I have a SEM image, and i’m trying to perform a high-pass filter on it, first I adquire the image and convert it to double.

Then I perform the FFT, and it goes ok. Lets say I get F(u,v) that is my representation in the frequency domain of my image.

The filter I’m tryng to perform is a second-order Butterworth. So I define the filter H(u,v), with bigger atenuation ocurring at lower frequencies (closer to the center), it happens to be ok.

Then I apply fftshift to the filter H(u,v), because I didn’t apply it to the FFT for its correct visualization, i’m pretty sure there shouldn’t be a problem with this.

Then I multiply H(u,v) with F(u,v) element to element, and I get what is supposed to be the FFT of my filtered image, lets call it G(u,v)=H(u,v)*F(u,v); and it seem visually ok.

But the last step is where the trouble appears. That is, when I apply the inverse transform: uint8(ifft2(real(G))); that the “filtered image” that I get is right and wrong at the same time. I mean, it is right because the filter works detecting edges, but it is not right because the filtered image is a yuxtaposition of the correct result, with a spatially-inverted equal version of this correct result.

Do you know what I mean? I can send you the code and images explaining this to you if you agree to help me. You’ve got my email so I would really apreciate it.

Best Regards, Daniel.

sir,I am unable to do the fourier transform of an image with out using matlab functions.i am resulting in an error stating

“complex arthimetic is not supported”.

kindly help me with this problem.

hello every body.

my question is :

iam work in image processing filed , i went to show fft2 and i want to change some value for fft2,

see…

a=imreade(‘image.png’);

xx=fft2(a);

xx(1,3)=x(1,3)+1000;

xx(1,5)=x(1,5)-1000;

.

..

…

iy = ifft(xx);

x2 = uint8(iy);

imwrite(inv1,’p3.png’);

c=imread(‘p3.jpg’);

cc=fft2(c);

——————————

my problem now is : cc==xx ??????????

so i cant found the change in fft2 for image.

what would you like to display..is it ‘image.png’ or ‘p3.png’..??

There seems to be a problem with the magnitude data. Has anyone been able to solve the problem? All I have is a white screen when the input image is of type double…

Jay,

Try using imagesc instead of imshow to display the image. You are probably have trouble with the color range.

-Eric

Hey Eric,

I utilize fft2 for EM wave propagation in free space. Initially I know my EMwave every where but I want to find it from another approach which is very straight forward in electromagnetics and it is like

1. A = fft2 ( my field in a plne ex. E(x,y,0))

2. B = A * phaseshift in Fourier domain ( exp(i*sqrt(k^2-(kx^2+ky^2))*dz)

C . find E field in plane (x,y,dz) by ifft2 (B)

then I expect this result to be equal to my direct computation of E @ (Xz,y,dz) which is surprisingly not!

have you encountered similar problem?

is it possible if I sent my code for you to have a glance?

Thank you

Thanks for your question, Yasi. This question seems like it might take a bit longer to solve, so can you please post this question along with your code in one of our forums? If possible, a little theory behind your code would be helpful, too (e.g. Wikipedia article). I promise that I’ll follow up on it and try to help you.

-Eric

Dear Eric,

I appreciate it! I can make a power point to address the problem and theory behind it and send it t you along with the full code. but may I know where exactly should I sent it?

Bests,

Yasi

Yasi, can you email me at everner@matlabgeeks.com? If possible, I would prefer to keep our troubleshooting public, so that other people can help and learn from your example. Would it be possible to use online sources or to post your PPT presentation as images on the Internet somewhere?

Thanks,

Eric

Sir if the problem of EM wave Propogation is solved can you please help me with the Same.

Because I am facing similar problem as Yasi though my problem is not exactly same but its 90% related.

In my assignment, I am supposed to filter an image and then plot the fourrier transform of the filter in 3D. I dont understand how i can plot the fourrier transform of the filter instead of the image in 3D. Please help.

i used an averaging filter of mask size of 13 by 13 to clear most of the noise. How do I plot the fourier transform of the filter in 3D?

Uzair,

Thanks for your question. Try this:

M = fft2(mask); %mask is the 2D array holding your mask

surf(M); %Surface plot of your mask in 3D

-Eric

do rply asap

can nybody help me with a program for 2D DFT with phase and magnitude… need its output as well….

plz do rply

Priti,

The code to do that is in this post. It’s not organized into a function, but you should be able to find the phase and magnitude of the 2D FFT of an array by using the code in this post. You can just use fft2, abs, and angle. Please read through the post and try to solve the problem. If you are still having problems, please post again.

-Eric

hi Eric,

can u plz post a full program for the magnitude n phase WAVES of FFT not for photos.. plz if possible post it soon.. thank you very much.

Priti,

Try this:

X = fft2(x);

magX = abs(X);

phaseX = angle(X);

-Eric

Hi Eric,

i have a program here…

N=5

x=[1 1 1 0 0];

subplot(2,1,1);

stem([0:N-1],abs(fft(x))); %magnitude%

title(‘magnitude response’);

subplot(2,1,2);

stem([0:N-1];

angle(fft(x))); %phase%

title(‘phase response’);

can u convert it to 2-D…

plz do rply asap …

wil b very grateful to u if send it by 2moro afternoon… hav to submit it for my exams…

thankyou for everything…

– priti.

Can someone explain me why when I am using

I= imread(‘.\pomoc\OriginalImages\Lena.bmp’);

B = fft2(I);

C=ifft2(B);

figure, imshow(I),figure, imshow(C);

C is totaly blank?

This is because fourier transformation is just for grayscal image not for rgb.So u need to use your grayscale lena image.

Thanks

CAn you help me on this question?

Hello every one..

I am confused on a one question of my assignment which is on fourier transformation.Can anyone help me plz?The question is

1) Use lena image (f(i,j)). Calculate F(u-N/2,v-N/2). Plot|F(u-N/2,v-N/2)|. Reverse the magnitude of FT properly so that the resultant image is not too dark.

I am waiting for this answer. Can any one here o help me with a complete code? Thanks

Ali,

Sorry for not responding earlier. It looks like you just need to do the 2D FFT using fft2. I’m not sure what u-N/2 and v-N/2 is supposed to accomplish. Perhaps that just does the same thing as the fftshift function? I don’t know what you mean by “reverse the magnitude of FT.” You can change the way that the image is displayed by modifying the coloraxis using caxis. Hope this helps.

-Eric

Well maimdaaca nuts, how about that.

Hi, John, when you say you are a determinist, what exactly do you mean?Are you saying that all observable occurrences in the universe, including the physical actions taken by humans, can in principle be fully accounted for and predicted in mechanistic, mathematical fashion?Or are you a determinist in the broader sense, meaning simply that everything that happens is fully accounted for by *something* (iow, that nothing happens by chance/no reason at all), but where that something can include peoples’ intentions, and does not necessarily reduce to mathematically predictable mechanism?

Is there anyone who can help me in fourier transformation in image processing using Matlab?I can write my question if I get a response.

Thanks

Ali

Damn, I wish I could think of sohinmetg smart like that!

interesting ……human modeling is estrordianrily weak…. if you want physics envy you can have it…..since cultural and social standards in the western world are near chaos….i suspect your sternbergs theory will remain..untestable and hollow…..2 dimensional……hardly worthy of an explanation of he human condition…got it?

Hi Eric,

can you pls upload a matlab code to cancel noise in a grayscale image in image processing based on ADAPTIVE PARTICLE SWARM OPTIMIZATION ALGORITHM

Shrirenga,

I’m not familiar with that algorithm, but I’ll consider writing a post about it in the future.

-Eric

I am writing a GUI tool for eliminating periodic noise , and i want to know is there any method that, if I select a bright patch (by some gui means)at one side of center bright patch (origin)in fourier domain then the opposite conjugate symmetrical point about the origin could be selected automatically. looking forward for your reply

Atul,

I recommend using the ginput function, as Vipul shows in this post: http://matlabgeeks.com/tips-tutorials/getting-user-input/

You can then transform the coordinates to whatever you need.

-Eric

Hi Eric,

My question is how do i implement the quaternion fourier transform in color image.

The symplectic decomposition for the above quaternion

image is given by:

mu= sqrt(-1);

q(n,m)= f1(n,m)+f2(n,m)*mu;

f1(n,m)=g(n,m)*mu;

f2(n,m)=b(n,m)+r(n,m)*mu;

quaternion fourier transform of q(n,m);

Hi Eric

I like your post, I performed 2D FFT of an image which was in gray scale. How does edges are handled in Matlab 2dFFt code, and what is the window function utilized.

It’s kind of buried in the above code, but I wanted to point out- Color images are represented by a 3D matrix (to hold RGB values) instead of a 2D one. That’s why the FFT magnitude won’t display.

If you’re using a color image, run it through rgb2gray() before running the transform.

Hey Guys,

I would appreciate if you share me a MatLab code on how to do a 2D FFT of digital elevation model.

thanks!!

What is i here?

Thanks for the nice demo on DFT. I am not getting magnitude plots. Please help me.

Thanks a lot

That is complete, correct and accurate.

hey thanx for your article. It is really much helpful to me. I have a problem ,when i tried to find the magnitude of colour image its totally white nothing concentrated at centre.

please help me as it is part of my project.

thank you.

Hey, thanks for your article, I have a question, I want to separate the bird from lines but I cant I have tried different ways can you give me some comments

http://tinypic.com/r/15d5mkm/5

Hi Sareh,

I hope you are doing well. What do mean by “separate the bird from lines”? Do you want to create two separate images, one with only a bird and another with only lines? What have you tried so far?

Eric

Hey, that post leaves me feeling fohlsio. Kudos to you!

Mnie siÄ™ wydaje,ze facet,ktÃ³ry kocha siÄ™ z wieloma kobietami poszukuje czegoÅ› wiÄ™cej niÅ¼ ciaÅ‚a,ale o tym nie wie.No i teÅ¼ jestem ciekawa waÅ¼eÅ„ Adama:)

It’s good to see that there are intelligent people out there that are kind enough to put this kind of information out there for the oblivious minds to see.I’ve been taking zoloft on and off forever (maybe a year and a half now) and I’ll tell ya, my world has been crazy. I’m like a zombie on and off. Even when I’m not taking the medication for fear that it is doing this to me, it still affects my grip on reality. It really sucks, I miss feeling “normal”.

Hello, i believe that i saw you visited my blog so i came to â€œreturn the chooseâ€.I’m attempting to in finding issues to enhance my site!I assume its ok to make use of some of your ideas!!

This was a great documentary. it has helped to confirm my view thatï»¿ despite the good intentions of all founders of religion, including mohamed, the organised religion of today are devices purely used to control and divide people who otherwise have alot in common; knowledge

Dear God, Lisa, the very thought of seeing Levi sans apparel makes me throw up a little in the back of my mouth.I can't remember where I read this, but it seems apropos:"At one time it required talent, wisdom, beauty, grace, poise, understanding or honor, or some combination of the above, to become well known. Apparently it now requires nothing more than an utter lack of shame."

Hi Eric,

This is a nice article which I found while searching answers for some doubts regarding 2D-FFT. Before going to my doubt, one thing: I couldn’t find the next article on image processing, which you mentioned in this post. I would like to read that as well, as my doubts are regarding image processing using 2D-FFT.

OK, now coming to my problem:

I have an image of a wave (there are some grids as well) propagating: http://www.flickr.com/photos/66468892@N07/6052890522/

I want to find the wavelength of this wave. I used a sample rate of 138.5 pixels per centimetre and did the 2D-FFT (and fftshift) and got this image [I removed the DC component as well]: http://www.flickr.com/photos/66468892@N07/6062522739/

Now, how can I relate the peaks to the colour waves and also to the grids – which peak corresponds to which?

This is my code:

close all;

clear all;

clc

img = imread(‘f75p0.png’); %importing image

figure(1); imshow(img);

cimg = img(1:485,1:220,1:3); %cropping image

figure(2); imshow(cimg);

imgred = cimg(:,:,1); %just the red channel

imggrey = rgb2gray(cimg);

figure(3); imshow(imgred);

dred = double(imgred); %converting to double

dgrey = double (imggrey);

figure(4);mesh(dred);

Fs_x = 346/2.5; % sample rate in pixels per centimeter

Fs_y = 346/2.5;

dx = 1/Fs_x; % centimeters per pixel

dy = 1/Fs_y;

[ M, N, ~ ] = size(cimg); % pixels

x = dx*(0:N-1)’; % centimeters

y = dy*(0:M-1)’;

dFx = Fs_x/N; % cycles per centimeter

dFy = Fs_y/M;

Fx = (-Fs_x/2:dFx:Fs_x/2-dFx)’; % cycles per centimeter

Fy = (-Fs_y/2:dFy:Fs_y/2-dFy)’;

imgfftred = fft2(dred); %performing 2D-FFT

imgfftred(1,1) = 0; %removing DC component

imgfftred = fftshift(imgfftred); %shifting zero component to centre

figure(5)

surf(Fx,Fy,abs(imgfftred)); %plotting image w.r.t hori. & vert. frequencies

view(0,0); %to view the peaks

shading interp; %colouring the peaks

Hey Paul,

Sorry for the delay. It seems like you have already done most of the work to calculate wavelength. Since you have already related the points in your FFT to sampling frequency, you just need to take the inverse of the distance from your peak to the center of the FFT. For instance, you have a peak at

fx = 1.258

fy = -0.1427

fd = sqrt(x^2 + y^2) = 1.2661

wavelength = 1/fd = 0.79 cm

If you measure the distance between troughs in pixels in the picture, you’ll get a value somewhere around there. I measured it once and got 0.895 cm. There are other peaks in the FFT as well. If you measure the distances to those peaks, you will get other values for wavelength in the direction of those peaks from the center. The problem is that the resolution on this FFT is not that great. The bins in the FFT are somewhat coarse, so you will have a lot of error in your measurement. However, the waves in this picture are also irregular, so I’m not sure how meaningful one value of “wavelength” is for the entire image. It looks like the wavelength is different in different parts of the image, which is probably why you have a cluster of peaks close to each other in the FFT.

Hope this helps,

Eric

Thanks a lot Eric. That helped a lot indeed.

One doubt though: Would it be right to think that the grid patterns are having no effect on the 2D-FFT? In other words, can we consider that all the peaks in the FFT image are due to the colour bands and not due to the grids?

Once again, thank you for the reply.

Regards,

Paul T John

Hey Paul,

Yea, I’m sure the grids would show up in the FFT too. They could be the cause of the energy in the FFT from X = +/- 4 to 6. It’s hard to tell because there is so much going on in this picture. If you could filter out the grids, you could see how they contribute to the FFT. Perhaps just try a simple threshold filter to start, and see if you can save only the grids. Do the FFT on those, and compare it to the original FFT.

-Eric

Hi Paul,

I have some questions due to your code. i have pictures that i’d like to find the wavelength too. my questions are: what is w.r.t vert means in your code? what is cycles per centimeter and how did you define the code for it? because i have a similar picture as yours. How do you measure the wavelength and which point of peak that can represent the wavelength?

thanks a lot,

titin

Why is the phase from -pi to pi?

Why is the phase from -pi to pi?

Jose,

I chose [-pi pi] as the phase limits so that the center of the color spectrum of the graph would be at zero phase. The phase limits could also have been from 0 to 2*pi. Either one is fine. Does that answer your question?

Eric

how would i encrypt ONE image… by taking the fft and shuffling the rows/columns by using an algo and taking inverse?

Allison,

One way to do that is the following:

A = fft2(a); %Take FFT

p = randperm(size(A,1));

B = A(p,:); %Shuffle rows

b = ifft2(B); %Take inverse FFT

Eric

nice article, but while i executing this i cant get the magnitude(abs) image as shown above for both the images, I am getting only a complete White window for a coding line —–> figure, imshow(abs(fftshift(fftA)),[24 100000]), colormap gray

Please help me out , also tell me the meaning of the value [24 100000]

Thank u sir

Senthil,

The parameters [24 100000] are the limits of the colormap. Values below 24 are displayed as black, and values above 100000 are displayed as white, while values in between are displayed as grayscale values. Look at the Mathworks page for imshow under the heading “imshow(I,[low high])”: http://www.mathworks.com/help/toolbox/images/ref/imshow.html

You should play with the values of 24 and 100000. I arrived at those values through a couple minutes of trial and error. Perhaps the results are different on our respective computers and versions of Matlab.

Hope this helps,

Eric

Dear Eric,

Thank you for providing such good information to let unprofessional people, like me, can calculate some useful data. However, I have a similar problem about the limits. I have tried very large number and also tried using min(I(:)) max(I(:)). It is still all white in image. It seems the there’s difficulty to identify the value I have. Is there any format I should set up or something else I should consider? I check for my value and they are about several to several hundreds of thousand.

Shih-Che

Shih-Che,

Sorry for taking so long to respond. I recommend using imagesc. If that doesn’t work, then I recommend checking your array to make sure it contains the correct data.

-Eric

Hello. Will you please tell me how much time the FFT function took (I’m assuming a desktop PC)? In particular I’m interested in the speed at 4096×4096 pixels.

Shawn,

I’m using a Macbook Pro running virtual Windows 7 on Parallels, so my results may differ from someone using a desktop PC. However, the FFT2 functions in the code took 0.047 s each to run. When I set the FFTs to (4096,4096), they took approximately 5.4 s each to run.

Eric

Thanks very much.

If you use GPU acceleration for the FFT’s a 4096×4096 array will take less than a seccond. FFTs are amazing on GPUs!