Monday, 10 June 2013

Programming Inception - Function within a function

This post is about a small but vital part in one of my projects in the past. This specific part of my project dealt with interpolation of quantized silhouette images, using a simple averaging based recursive interpolation.
Okay, I know its difficult to understand, but don't just stop reading yet. The most interesting part about this is that it can be related to the concept of "programming inception". You might be wondering this is something very difficult or deep. Don't concentrate too hard like cobb here, from the movie inception. This concept is as simple as it can get, its just that at first its difficult to get.

If you are like me and have watched "Inception" several times, then recursion in programming can be thought of having a dream within a dream. The more number of levels of dream you go into, the more specific to details you get. Likewise, a recursive function calls itself with its input and uses the outputs in multiple layers of levels to get deeper and closer to the answer, just like cobb did in the movie to plot an idea in a deep dream level.

I did the implementation using OpenCV so here I will be talking about the code in context with OpenCV function calls. To explain, the simple idea behind this implementation is finding the midpoint of two points and then setting its value. This whole process can be repeated a number of times to achieve greater accuracy, however in this process there is a trade-off between accuracy and efficiency of the final code.
This is one of the most basic interpolation techniques which can be used for real-time recovery of data. To demonstrate its affect, I have implemented a simple example which is able to draw a line between two points by this interpolation method.

The code for the interpolation function is:

void interpolate(int p1x, int p1y, int p2x, int p2y, int steps, int r, int g, int b)
 if(steps >0)
 {<Point3_<uchar> >((p1x+p2x)/2, (p1y+p2y)/2) = Point3_<uchar>(b, g, r);
  interpolate(p1x,p1y,(p1x+p2x)/2, (p1y+p2y)/2, --steps, r, g, b);
  interpolate((p1x+p2x)/2, (p1y+p2y)/2, p2x, p2y, steps, r, g, b);

That's it! input arguments include starting and ending points p1 and p2, number of recursive steps (which defines the details in the final output), and the color component for drawing RGB. disp is a global Mat with three unsigned int channels for RGB.

Randomizing the location of points, the color and the number of recursive steps, I get a pretty cool effect (which looks more like a screensaver then a demo). The video below shows the output:

As this whole process is randomized, every time you will see a different pattern in the output window. Below are some screenshots taken of the same window at different time instants:

The code can be downloaded from: interpolate.cpp

Thats it for today! I will be back soon!