Friday, September 6, 2013

Activity 13 : Image Compression

(Welcome, Interwebs traveler. A note before you go: please click any image to view in enlarged/theater mode. Now explore on!)

This week, we code an image compression scheme based on Principal Component Analysis (PCA). Essentially, PCA takes sets of highly similar data, determines the pattern/similarities in the data, and expresses the similarities in a set of linearly uncorrelated values called the principal components [1,2]. From our AP186 and AP187 lectures, we know that we will then be able to reconstruct any of the data in the original data set using a linear combination of the principal components multiplied with the appropriate coefficients [3: AP186/AP187 lectures].

It should be noted (since in the past activities, I have been using MATLAB), I will be using Scilab here. This is due to the difficulty I have had in determining the appropriate function that corresponded to Scilab's pca() function. I mean, I was able to determine what PCA function was installed with my copy of MATLAB, however I was unsure of the output of the function. I felt it was wiser to (finally) install Scilab instead of running around blind with MATLAB.

So how will this compression scheme work? We first select a sample image. The picture shown in Figure 1 is a true-color image converted to a .png format in Activity 4. It has dimensions of 256 pixels x 256 pixels, and has a file size of 192 KB. Our goal is to use PCA in our compression scheme and reduce this file size.

Figure 1. Sample true-color image stored in PNG format.
Dimension in pixels is 256x256, and file size is 192 KB.

Compression Scheme (grayscale)

For our grayscale compression scheme, the sample image is converted to grayscale by taking the average of the intensity values found in the Red, Green and Blue channels. Figure 2 shows the result after conversion to grayscale in this manner.

Figure 2. Sample image converted to grayscale, still stored in PNG format.
Dimension in pixels is 256x256, and file size is 38.7 KB.

We then write a code which chops the image into blocks of 10 pixels x 10 pixels. Each block is concatenated into a column matrix, and the whole collection of blocks is combined into a single matrix X. X has dimension MxN, where M is the number of blocks from chopped from the sample image and N = 100 are the number of pixels per 10x10 block.

Since the dimensions of my sample image are not divisible by 10, we consider only the first 250 rows and 250 columns, effectively cropping the image to be of size 250x250 pixels. We then have M = 25x25 = 625 blocks with N = 100 elements per block. Thus, X is of dimension 625x100.

Applying PCA on matrix X using the Scilab function pca(x), we obtain the normalized principal components facpr, the set of coefficients comprinc, and the eigenvalues (found in the 1st column) and ratios of the corresponding eigenvalue over the sum of eigenvalues (found in the 2nd column) in lambda [4]. Figure 3 shows the principal components we obtained after PCA.

Figure 3. Principal components of the grayscale image.

To determine the principal components which contribute significantly to our image, we check the 2nd column of lambda and find all values greater than 0.001 or 0.1%. The results tell us that the first 18 principal components have values greater than 0.1%. This means the principal components beyond the 18th will have minimal contribution.

The grayscale image will be reconstructed by taking the product of facpr and comprinc, and we can set the number of principal components to be used in the facpr and comprinc. Figures 4 to 9 show the reconstructed image after the compression scheme, with 4, 8, 12, 16, 20 and 24 principal components. (I take the 20th and the 24th instead of the 18th to maintain the increment of 4.) The images are saved in PNG format using Scilab's imwrite.

Figure 4. Sample image after compression, reconstructed using 4 components.

Figure 5. Sample image after compression, reconstructed using 8 components.

Figure 6. Sample image after compression, reconstructed using 12 components.

Figure 7. Sample image after compression, reconstructed using 16 components.

Figure 8. Sample image after compression, reconstructed using 20 components.

Figure 9. Sample image after compression, reconstructed using 24 components.

Visually, we can see that using more principal components (as shown by 4-20 principal components) greatly enhances the reconstructed image. However, the change from the image by 20 and 24 principal components is minimal.

Checking the file size of each, we have the following:

  • 4 components: 31.3 KB;
  • 8 components: 34.2 KB;
  • 12 components: 35.5 KB;
  • 16 components: 35.9 KB;
  • 20 components: 37.0 KB; and,
  • 24 components: 37.5 KB.

So by the file size, we can see that the use of more principal components improves the quality of the reconstructed image at the expense of an increase in the file size.


Compression Scheme (colored)

For fun, we compress the sample image per channel and recombine them during reconstruction (after compression). Figures 10 to 15 show the reconstructed color image after the compression scheme, with 4, 8, 12, 16, 20 and 24 principal components. The images are saved in PNG format using Scilab's imwrite.

Figure 10. Sample image after compression, reconstructed in color using 4 components.

Figure 11. Sample image after compression, reconstructed in color using 8 components.

Figure 12. Sample image after compression, reconstructed in color using 12 components.

Figure 13. Sample image after compression, reconstructed in color using 16 components.

Figure 14. Sample image after compression, reconstructed in color using 20 components.

Figure 15. Sample image after compression, reconstructed in color using 24 components.

As with the grayscale images, the quality improves with increasing number of principal components. Again checking the file sizes:

  • 4 components: 60.1 KB
  • 8 components: 62.8 KB
  • 12 components: 64.0 KB
  • 16 components: 64.6 KB
  • 20 components: 64.7 KB
  • 24 components: 64.9 KB
The conclusion remains the same: in our compression scheme, the quality of the image improves (or the saved image is less lossy) at the expense of bigger file size.

Grading

Based on the criteria for grading, I believe I can give myself a 12/10 for completing the activity and for experimenting with compression in color (despite the color being a little off for the reconstructed images).

Friday, August 30, 2013

Activity 12 : Playing Notes by Image Processing

(Welcome, Interwebs traveler. A note before you go: please click any image to view in enlarged/theater mode. Now explore on!)

Today we'll be doing something that I find weird... we'll program our computer to play some sheet music via Scilab/MATLAB. It's weird because I used to play piano (a looooong time ago), and for me I'd rather just relearn how to play than prep my computer to play because:
  •  if I play the piano, it's just a matter of relearning how to read sheet music and hitting the right keys; whereas,
  •  if the computer plays, I have to crop the sheet music, apply morphological operations, detect each note, etc...
In any case, if I accomplish this activity, maybe I can put on my resume: plays the piano via MATLAB. Haha.

The sheet music that I chose is the piano piece "Pop Goes the Weasel", from our source [1]. (I tried to look for a piece with only one kind of note so I could start from there, but unfortunately even "Twinkle Twinkle" has more than one kind of note.)

Let's go over sheet-reading quickly. (Thank you, source [2], for the refresher course. Haha.) We only focus on the top lines, which means we'll only be reading the notes that are played with the right hand. There are three notes present for the right hand: the quarter note, the half note, and the dotted half note. We also have one kind of rest, the quarter rest. Our goal is to use image processing to isolate each note/rest, identify each note/rest, and translate the note/rest to a particular sound.

From our sheet music, I crop the desired lines and combine them to make one long line of notes:

Figure 1. One long line of notes for the right hand in "Pop Goes the Weasel."

To remove the lines, I applied an opening operation with a structuring element of a diagonal line of length 3 and degree 45. I isolated the quarter notes (sample in Figure 2(a)) from the cleaned image using correlation:

Figure 2(a). Sample quarter notes.
Image taken from [2].

Figure 2(b). Isolated quarter notes.

...and I isolated the half notes (sample in Figure 3(a)):

Figure 3(a). Sample quarter notes.
Image taken from [2].

Figure 3(b). Isolated half notes.

...as well as the dotted half notes:

Figure 4. Isolated dotted half notes.

...and finally the quarter rests:

Figure 5. Isolated quarter rests.

Initially, I got really frustrated with the half notes and the dotted half notes, because the quarter notes kept getting identified with the half and dotted half notes. In the interest of simplicity, I manually blocked out all the components which were not half or dotted half notes and took the correlation of that with the half/dotted half notes. :S

After isolating each type of note/rest, I took the centroid of each note to represent them as a single point (idea from blog [3]; I initially had no intention of using the centroid, but my idea of scanning through the whole image was too complicated!). Recalling Activity 5, the centroid [4] is simply the sum of all pixel coordinates on one axis divided by the number of pixels. I then took the convolution of a certain marker with the centroids, so that I have now clearly defined each type of note. To recombine the isolated notes, I simply added the images produced by convolution with the markers.

Figure 6 shows the markers, denoted in grayscale to better separate each marker:

Figure 6. Notes and rests converted to user-defined markers.

Since I now know the what each marker stands for, I can set the amount of time a certain note will play or a certain rest will umm, rest. I first used this source [5] to set the time, but later on I'll change the duration based on my preference.

What's left is to detect the row position of each marker on the image. With a corresponding note/rest per row value, MATLAB begins to sing!

And here is MATLAB's rendition of "Pop Goes the Weasel":
https://dl.dropboxusercontent.com/u/14710699/pop.wav


Grading

I got really frustrated with this activity, particularly while I was trying to differentiate the quarter notes, the half notes and the dotted notes. I am not satisfied with my performance here, so I give myself an 8/10.

Tuesday, August 20, 2013

Activity 11 : Application of Binary Operations 1

(Welcome, Interwebs traveler. A note before you go: please click any image to view in enlarged/theater mode. Now explore on!)

Our activity here focuses on extracting a certain region of interest (ROI). It will allow us to utilize the skills we've acquired from the previous activities, particularly those of morphological operations. We're tasked to look at 'cells' in images, extract them as our ROI and calculate the average size of the ROI. Armed with this knowledge, we can then detect which cells have grown disproportionately, or rather, have become cancerous.

Figure 1 shows a set of what we'll consider as our normal, healthy cells. We analyze the image in sections of 256x256 pixels. Each section is converted to binary based on its histogram, and the ROI is polished using our morphological operations.

Figure 1. Scattered punched paper that will simulate normal, healthy cells.

After much hard work (on around 14 overlapping sections!), we extract the cells from the background as in Figure 2. We use a color map to easily find where clumps of cells still remain, and we separate them from the single cells before we finally calculate the mean cell size. The mean cell size is 534.0417 pixels with a standard deviation of 15.3297 pixels.

Figure 2. Color map of cells in Figure 1, extracted from the background.
Areas with the same color have the same value on the map.

We inspect a collection of cells with a few cancerous cells, shown by Figure 3. Of course, visually, the overgrown cancerous cells are easy to find considering the small size of Figure 3 and the small number of cells in the image. But for our activity, we'll process the image as if we cannot visually find the cancerous cells.

Figure 3. Scattered punched paper that will simulate normal, healthy cells
interspersed with cancerous cells. Which are cancerous?

We again extract the cells from the background and discard the clumps of normal, healthy cells. Thankfully, the cancerous cells are not attached to these clumps so we can quickly discard them from our analysis.

Figure 4. Color map of cells in Figure 3, extracted from the background.
Areas with the same color have the same value on the map.

The mean cell size and standard deviation from our healthy cells can be used as a threshold to extract the cancerous cells. Figure 5 portrays the cancerous cells (as considered by our threshold) in yellow while healthy cells are in maroon. Although the cancerous cells were segmented from the background, we somehow manage to get healthy cells too!

Figure 5. Color map of cancerous cells extracted using the mean cell size of healthy cells as threshold.
Maroon cells are considered healthy while yellow cells are cancerous.
It can be seen that a few healthy cells are extracted as well.

But a second look at Figure 1 and Figure 3 tells us that the cells are not of the same size in the images. We scale the mean cell size and standard deviation values from Figure 1 to match the mean cell size of healthy cells in Figure 3, and ta-da! The cancerous cells are finally segmented from the rest.

Figure 6. Color map of cancerous cells extracted using the mean cell size of healthy cells as threshold.
Maroon cells are considered healthy while yellow cells are cancerous.
Finally! We have isolated our cancerous cells.

Now we have to give someone the bad news... or do we?

Using our image processing powers, we will try to cure our patient of their cancer by eroding the cancerous cells until they shrink to a healthy size. The verdict?

No more cancer!

Figure 7. No more cancer! Orange cells used to be cancerous
but we've shrunk them down to normal size like our healthy maroon cells.

Grading

Because I was able to cure cancer besides detecting the patient's cancerous cells, I give myself 11/10 and a Nobel Prize. Yay!

This activity was rather frustrating for me, mainly because I couldn't decide whether I was satisfied with the segmentation in each section. I was literally coming back to previous sections to try to isolate more cells to improve the mean cell size value, as well as increasing the overlapping sections. I had to stop and forcefully convince myself that my work was good enough, or else I would still be trying to segment my ROI. :O

Acknowledgements

I would like to acknowledge Floyd Willis Patricio for reminding me through a Facebook chat that an erosion followed by a dilation with the same structuring element is mainly an opening operation. Haha. I was too engrossed with trying to experiment with a good combination of morphological operations that I had forgotten what an opening operation technically entailed, thus having a code filled with imerode-imdilate's (instead of the sensible imopen's).

Monday, August 12, 2013

Dear Ma'am Jing : A Letter

Dear Ma'am Jing,

You've mentioned in class before that you would like your students to be open and honest with concerns that conflict with their academics. In light of my inability to accomplish all 10 activities and my occasional absences, I would like to take this opportunity to apologize and to explain my actions.

You see, Ma'am, in the 1st semester of AY 2009-2010 I found myself unexpectedly pregnant. Although the doctor told me I would be able to continue to attend classes in the 2nd semester (since my expected delivery date was in April, during the summer break), my parents decided to bring me to the province, causing me to be delayed with my major subjects. Upon my return, I was lucky enough to be able to make up for lost time by joining off-season course offerings and petitioning for other subjects, such that I ended up extending for only one semester instead of two.

This semester, the 1st semester of AY 2013-2014, is that one semester. While some people would think I am on a good pace (I mean, just one sem instead of two!), my parents are of a different opinion. Since the start of my 5th year, they've been anxious and worried about my future, considering that I'm spending a lot more time in school instead of already finishing and getting a job and also considering that they and my siblings took 4-year courses. This has put a lot of pressure on me to accomplish my thesis for this semester.

Of course, I understand that it's normal for physics majors to have countless sleepless nights due to academics and research; however, with my daughter, things are a little more difficult for me. While weekends are a reprieve for some of my peers, it's not a time for rest for me. Weekends are time for me to bond with my daughter, and recently, to help her with her schoolwork (she started going to school just this AY). Although my parents are there to help me and act like parents to her as well, I believe it's important for me to be present and active in her development.

Because of all these things, and the testimonies of labmates and orgmates that the load of AP186 and AP187 led to the one-sem delay in their theses work, I made the irresponsible decision to skip AP186 and AP187 to focus on my thesis to the point of truancy. I was bound by the incorrect notion that prioritizing my thesis and research work over my academics would bring me closer to my goal of graduating by this semester.

I would like to sincerely apologize for being disrespectful through my truancy. I will do my very best not to let it happen again, with the exceptions being emergencies related to my daughter (I'm sorry Ma'am, I'm a single mother so if something happens I'm the only parent available to attend to her).

I do (and did, before your email, Ma'am) intend to finish all my blog posts for the incomplete activities, mainly because I enjoy AP186. The activities in AP186 are fun and interesting to do, and I really appreciate the lessons I take away from each activity.

Again, I'm sorry, Ma'am Jing. Thank you for this opportunity to explain myself.



Sincerely,

Justine

Tuesday, July 23, 2013

Activity 10 : Morphological Operations

(Welcome, Interwebs traveler. A note before you go: please click any image to view in enlarged/theater mode. Now explore on!)

For this activity, we focus on the morphology or the shape and structure of objects in images. According to our AP186 Activity 10 handout [1] we will work with binary shapes and perform morphological operations on them, essentially changing their form and shape [2]. The morphological operations will allow us to further process or extract information from the image [1]. In particular, we will investigate the dilation and erosion morphological operations.

Morphological Operations

As mentioned above, morphological operations manipulate the shape or structure of objects in images in the interest of processing or extracting information. There are two principal morphological operations: dilation, and erosion [2]. Both operations involve overlaying a structuring element B over the image A, which in this case is binary, and then sliding B over A [2].

(Note that in source [2], the background is white or value 1 while the object is black or value 0. In this activity, our background is black while the object is white. We use the activity's color scheme for the discussion below.)

For dilation, when the origin of B is on a black (or background) pixel, there is no change made to A [2]. However, when it lands on a white (or object) pixel, we convert all pixels within the structuring element from black to white, such that new pixels will be added to the object [2].

For erosion, when the origin of B is on a black (or background) pixel, there is no change made to A [2]. But if it lands on a white (or object) pixel with B laying over at least one black pixel, the origin of B is converted from white to black, such that pixels will be removed from the object [2].

Prediction

Knowing the above concepts about dilation and erosion, I make a hand-drawn prediction of the effect of dilation and erosion on the shapes in Figure 1.

Figure 1. Shapes to be used for morphological processing.
From left to right: 5x5-pixel (px) square; triangle with 4px base and 3px height;
10x10px hollow box with thickness 2px; and, cross with height and width 5px.

Figure 2 and 3 show the predictions for dilation.

Figure 2. Hand-drawn prediction for dilation.
The orange color shows the original shape while the blue color shows the added pixels.

Figure 3. Hand-drawn prediction for dilation.
The orange color shows the original shape while the blue color shows the added pixels.

Figure 4 is the hand-drawn prediction for erosion of the shapes.

Figure 4. Hand-drawn prediction for erosion.
The orange color shows the original shape while the outline shows the removed pixels.

Numerical Image Processing

Figures 5 and 6 show the resultant images from morphological processing using MATLAB. We can see that my predictions are the same as the resultant images, which is a good sign. :D Yay!

Figure 5. Result of dilation using the structuring element in the 1st column,
for the figures: (left to right) square, triangle, hollow box, and cross.
Figure 6. Result of erosion using the structuring element in the 1st column,
for the figures: (left to right) square, triangle, hollow box, and cross.

Grading

Based on the criteria given, I give myself 8/10 for a few missing pieces in the activity and a lackluster discussion. :(

Tuesday, July 9, 2013

Activity 8 : Enhancement in the Frequency Domain

(Welcome, Interwebs traveler. A note before you go: please click any image to view in enlarged/theater mode. Now explore on!)

In our previous activities, images were manipulated through their cumulative distribution function. For this week's activity, we manipulate images in the frequency domain to remove certain components present in the image. The components we aim to remove are repetitive in the spatial domain. Examples of these are lines produced from stitching images and the canvas weave of a painting, and we will attempt to remove them from our images in a section below.

But first, we review a few Fourier transforms (FT) of repeated shapes.

Fourier Transform of Repeated Shapes

Two Dots


We recall that two white dots on a black background represent two Dirac deltas in two-dimensional (2D) space. We also recall that two Dirac deltas symmetric along one axis is the FT of a cosine wave [1]. Assuming the deltas are present in the frequency domain and taking the 2D fast FT (FFT) of the deltas to convert them back to the spatial domain, we obtain the plot in Figure 1(b).

Figure 1. (a) Two dots representing two Dirac deltas in the 2D image plane.
(b) Corresponding 2D FFT of the deltas.

Two Circles


Figure 2(a) is a row of two circles of different radii, increasing from the left to right columns. Figure 2(b) shows the 2D FFT of the circles. We can see that as the radii of the circles becomes larger, the FT shrinks.

Figure 2. (a) Two white circles placed on a black background,
with increasing radius r (left to right: 0.1, 0.2, 0.3, 0.4 and 0.5 a.u.).
(b) Corresponding 2D FFT of the circles in (a).

Two Squares


Figure 3(a) is a row of two squares of different side lengths, increasing from the left to right columns. Figure 3(b) shows the 2D FFT of the squares. As with the circles, the FT shrinks as the side length becomes larger. However, the FT is boxy in shape. Recalling our reference from Activity 7, particularly this file [2], we find the theoretical FT plot of a square. This is shown in Figure 4.

Figure 3. (a) Two white squares placed on a black background,
with increasing side length s (left to right: 10, 20, 30, 40 and 50 px).
(b) Corresponding 2D FFT of the squares in (a).

Figure 4. Theoretical FT of a square aperture (shown in the lower left corner).
The top view of the FT is shown in the upper left corner,
and the right side shows the 3D plot of the FT.

Two Apertures with Gaussian Gradient


Figure 5(a) is a row of two apertures with Gaussian gradient of different standard deviations, increasing from the left to right columns. Figure 2(b) shows the 2D FFT of the Gaussian apertures. The FTs also shrink as the aperture increases; however, the Gaussian FT is devoid of diffraction effects unlike the FT of the circles.

Figure 5. (a) Two apertures with Gaussian gradient placed on a black background,
with increasing standard deviation sigma (left to right: 0.1, 0.2, 0.3, 0.4 and 0.5).
(b) Corresponding 2D FFT of the apertures in (a).

Recalling our Activity 7, we know that we can use shapes in the frequency domain as transfer functions which simulate the passage or blockage of light at that plane, if we take the convolution of the object and the transfer function.

Convolution


We also recall our convolution from Activity 7 and perform another demonstration of it here. We take 10 white dots randomly placed on a 200x200 pixel black image, and convolve it with a 5x5 random pattern. Figure 6 shows the 200x200 image, the 5x5 random pattern, and the resultant convolved image.

Figure 6. (a) An image of 10 white dots randomly placed on a 200x200-pixel black background.
(b) Random patterns of size 5x5 pixels. (c) Corresponding convolved image
of (a) and (b) along the same columns.

We also investigate uniformly-spaced dots along the x- and y-axes, changing the distance d between each point. Taking the FFT of the uniformly-spaced dots (shown in Figure 7(a)), we find that the FT is a uniformly spaced grid. When d = 200, the FT begins to resemble a sine wave, which is expected because only 2 dots are left at this separation distance.

Figure 7. (a) Uniformly spaced dots along the x- and y-axes,
in increasing distance d (left to right: 2, 5, 10, 20, 50, 100 and 200 pixels).
(b) 2D FFT of the uniformly-spaced dots in (a).

Pattern Removal

Line Removal


As instructed, we attempt to remove the lines produced by stitching multiple images from the lunar orbiter. We use the image of the lunar surface in Figure 8(a), which apparently has white lines crossing the image at intervals. Figure 8(b) shows the FT of Figure 8(a). The white lines can be filtered by blocking the vertical line in the center of Figure 8(b), and we obtain the filtered image Figure 8(c).

Figure 8. (a) Image of the lunar surface with white lines at regular intervals;
(b) 2D FFT of the image in (a); and, (c) Filtered lunar orbiter image.

Weave Removal


The next task is to remove the canvas weave pattern on the image of the painting in Figure 9(a). I attempted to filter the other peaks and retain the central peak in the frequency domain, in the hopes that this will result in a filtered image. Unfortunately, this was not the case, as shown in Figure 9(b). In fact, a lot of the painting information is lost and the canvas weave is emphasized, which is the opposite of our desired effect. Boo :(

Figure 9. (a) Painting with a canvas weave pattern; and, (b) resulting image
after attempts at filtering. The attempts were unfortunately unsuccessful.

Grading

Based on the criteria, I believe I deserve a 9/10 because although I was unable to successfully filter the canvas weave from the painting, I was able to accomplish other parts of the activity.

This activity was a little bit stressful for me, because for some reason even if I was blocking peaks in the frequency domain for the painting, I did not seem to be blocking/filtering the correct peaks. :(

Thursday, July 4, 2013

Activity 7 : Fourier Transform Model of Image Formation

(Welcome, Interwebs traveler. A note before you go: please click any image to view in enlarged/theater mode. Now explore on!)

Lens as a Fourier Transformer

For this activity, we learn about the Fourier transform in relation to image formation. What is the Fourier transform (FT)? In the words of our Activity 7 handout [1], the FT is a linear transform which converts a signal with X dimension into one with 1/X dimension; particularly, if the signal is in dimensions of space, the FT will convert it to one of inverse space or spatial frequency [1]. In its continuous two-dimensional (2D) form, the FT of some function f is expressed as [2]:

Figure 1. Continuous two-dimensional expression of the Fourier transform (FT) of a function f.
Image taken from source [2].

where the function f has dimensions in x and y. While in theoretical or mathematical calculations use of this form is suitable, it will take quite some time in numerical calculations. An example would be if the FT is used in image processing (where it is often used). To reduce processing time, the Fast Fourier Transform (FFT) algorithm was developed [3], which provides quick calculation of the FT in its discrete form [2]:

Figure 2. Discrete two-dimensional expression of the FT of a function f.
Image taken from source [2].

We demonstrate the effectiveness of the FFT by employing the pre-programmed algorithm in MATLAB. This is called by using the code fft2(). We use a white circle on a black background (created in MATLAB) to simulate a circular aperture. Figure 3 shows the expected FT plot [4] and the calculated FT plot. We can see that the calculated/numerical FT plot is similar to the expected FT plot, signifying that the algorithm works. Yay!

Figure 3. Circular aperture and its Fourier transform plot,
plotted theoretically (a) and (b) (taken from source [4]),
and numerically (c) and (d).

The numerical FT in Figure 3 above was calculated and saved after applying fftshift(), which essentially shifts the low-frequency components in the frequency space to the center of the image. Figure 4 compares the plot of the FT before and after shifting (shown in Fig 4(a) and Fig 4(b), respectively).

Figure 4. 2D FFT of the circle: (a) before shifting, and (b) after shifting.

We also check what happens when we apply the FFT algorithm on the calculated FT plot, and the result is shown in Fig 5(c). The result is the original centered circle, indicating that the FFT transforms the image to its spatial frequency domain and another FFT takes it back to the spatial domain.

Figure 5. The circle as viewed in the different domains:
(a) in spatial domain; (b) in frequency domain, after first application of 2D FFT;
and, (c) in spatial domain, after second application of 2D FFT.

But what if the object in the image is not symmetrical? We apply the 2D FFT algorithm once and twice on certain Latin letters, the letter 'A' and the letters in my name 'JUSTINE'. Of course, after one application of the FFT algorithm, the letters are transformed to the frequency domain and we see the signal frequency of each letter. After the second FFT, we see that the letters are recovered but are inverted.

Figure 6. Latin letters as viewed in the different domains. 1st row: in the spatial domain;
2nd row: in the frequency domain, after first application of 2D FFT;
3rd row: in the spatial domain, after second application of 2D FFT.

Wait a minute, this looks familiar... why yes, of course! This is the same effect that using a convex lens would produce! For light passing through the circular lens, it would be focused to a point (with some diffraction effects) and then enlarge again to the circular figure. For asymmetrical objects placed more than the lens's focal length, the image will be inverted [5], which we see for the Latin letters. Thus, we have demonstrated that the FFT simulates using a concave lens.

Convolution

The convolution is an operation which gives the overlap of two functions f and g, expressed by

Figure 7. Continuous expression of the convolution of f and g.
This is also denoted by f *g, where the star or asterisk (*) indicates convolution [6].
Image taken from the AP186 handout [1].

where x' and y' are the original 2D coordinates of f and g, and x and y are the 2D coordinates of the convolution h [1]. This is denoted by a star or asterisk (*) as in (f *g) [6]. Our handout helpfully adds that when applied to functions under linear transforms such as our FT above, the convolution of f and g in one domain becomes the multiplication of their transform F and G in the other domain [1]. This means that to simulate the overlap of f on g (or vice versa), we only need to multiply their corresponding linear transforms.

We can use this knowledge to simulate the passage of light through a circular aperture by taking the FFT of an object, namely the letters VIP, and convolving it with circles of different radii. Note that we consider the circles to be transfer functions already in the frequency domain. Figure 8 shows the result of changing the circle radius before convolution. Note that the resulting image is rotated 180 degrees (using Adobe Illustrator) for presentation purposes on this blog post.

Figure 8. Result of convolution between a circular aperture (1st row)
of radius 0.1, 0.2, 0.3, 0.4 and 0.5 a.u. (left to right columns),
and the letters VIP. The results are shown in the 2nd row.

We can see that the convolution simulates light passing through an aperture, where a small radius creates an image distorted by diffraction and a large radius allows most (if not all) of the object light to pass.

But does this work for other optical phenomena? For fun, I wanted to see what happens if we use two rectangles placed close together as the transfer function. We expect this to simulate Young's double-slit experiment [7]. Figure 9 illustrates the effect of the slit widths, indicating that as the slit widths increase the diffraction envelope shrinks and thus the diffraction effects should be less visible [8].

Figure 9. Illustration of the effect of the slit widths, for a 2-slit aperture.
As the slit widths increase, the diffraction envelope shrinks.
Image taken from source [8].

From the resulting convolved images shown in Figure 10, we can see that the double-slit experiment is simulated again by the convolution method, since for an increase in slit widths there are less diffraction effects perceived in the convolved images.

Figure 10. Result of convolution between two rectangles (1st row)
of width 1, 2, 3, 4 and 5 pixels (left to right columns),
and the letters VIP. The results are shown in the 2nd row.

Correlation

An operator similar to convolution is correlation, which is given by

Figure 11. Continuous expression of the correlation of f and g.
Image taken from the AP186 handout [1].

where x' and y' are the original 2D coordinates of f and g, and x and y are the 2D coordinates of the correlation p [1]. This is denoted by

Figure 12. Correlation p expressed in terms of f and g (middle term),
and in terms of the convolution of f and g (last term).
Image taken from AP186 handout [1].

and we can see that the correlation is simply the correlation of f (with conjugate coordinates) and g [1]. Now, what the correlation does is it gives an indication of the relationship between f and g [9]. If f and g are highly and positively correlated, meaning that when one increases the other increases as well, p will have a value +1 or almost +1. If they are highly but negatively correlated, meaning that when one increases the other decreases, p will have a value -1 or almost -1. If they are not correlated, p will have a value 0 or around 0.

Due to this nature of the correlation operator, we can use it to locate frequencies or perform 'template matching'. We demonstrate this on the text "The rain in Spain stays mainly in the plain", capitalized and evenly sized, in Figure 13(a). Taking the correlation of the letters 'A', 'N', and 'S' of the same size as the "rain in Spain" text, we get the result in Figure 13(b) where a bright peak is shown at the position the letters are found.

Figure 13. Correlation of text in (a), made using capitalized and evenly sized letters,
and select letters of the same size as shown in (b).
A bright spot or peak is present at the position the letters are found in the text.

What if the text has letters of different sizes and position? Figure 14(a) shows the new image after resizing and rotation of some of the letters. We take its correlation with the letters 'A', 'N', and 'S' from Figure 13(b). The result is shown by Figure 14(b). We can see that the peaks occur only where the letters have the same size and orientation. However, for the correlation with 'A', some peaks can be found possibly because the FT of the rotated 'SP' in Spain resemble the FT of the upright 'A'. For 'S', no bright peaks stand out because there is little to no correlation between the text and 'S'.

Figure 14. Correlation of new text in (a), made using resized and rotated letters,
and the same letters as in Figure 13(b).

We also test the text in Figure 14(a) for resized and rotated letters, such that they have the same size and orientation as the word 'Spain'. As expected, there are bright peaks in the corresponding letters in the word 'Spain'. Yay!

Figure 15. Correlation of new text in (a), made using resized and rotated letters,
and new resized and rotated letters made to be the same as the word 'Spain' in (a).

We can also use the correlation for edge detection [1], which is essentially template matching with a line template. Using a 3x3-pixel line template (1st column in Figure 16) and taking the correlation with the 'VIP', 'Rain in Spain' and the 'Rain' rotated counterpart, we obtain the edge outlines of the texts.

Figure 14. Images resulting from edge detection, with the edge template on the 1st column
and three sample texts in the 2nd to 4th columns.

We can see that the orientation of the templates dictate the edge outline that is emphasized. For example, the first template shows a white horizontal line. The resulting image shows the parts of the text edge outline that is horizontal in orientation. All the templates are lines (horizontal, vertical, slanting) except for the third template which is essentially a single white pixel surrounded by black background. Correlation of the template with the texts produce the corresponding edge outline which is equally emphasized on all sides.

Grading

Based on the criteria required, I believe I deserve a grade of 12/10 since I performed a few extra activities such as the resized and rotated letters for template matching.