Pages

Sunday, 15 March 2015

Estimating Pi with OpenCV

Yesterday was Pi day where the date and time specifically corresponded to the value of Pi, i.e. 3/14/15 9:26  <===> 3.1415926 . What made this day extraordinary was how different ideas and videos came out, some explaining its significance while others showing fun ways to estimate its value.

One such video caught my eye in which @thephysicsgirl and @veritasium calculated the value of Pi using Monte Carlo sampling method but with a fun twist. Instead of using random particles they decided to use random darts and a modified dart board. They explain the idea in a very simple and intuitive way in the video.



That was epic!!! and I learned that Monte Carlo can be applied to estimate Pi. What was more awesome was that I could find a number of examples online for this simulation. Being a computer vision engineer, I wanted to give it a try. I formulated the method with randomly sampling and checking against the equation of a circle, to determine if the points landed within the circle or not. The results with 20000 samples or as @thephysicsgirl and @veritasium would call them 'Darts' are shown in figure below. What's really awesome about this is that it makes kind of a cool animation too:


I reached at a final Pi value of 3.131903. As is the case with Monte Carlo methods, in order to reach an accurate result one requires a lot of particles, and by looking at the final image below you can notice that the regions are still not densely sampled (which means that I still need way more particles). 



Finally all the code for this is available at:  https://github.com/devkicks/PiMonteCarlo

Happy Belated Pi Day :D