Part of a series of examples from the CV cheat sheet. Click here for other computer vision applications.
Detecting circles in an image is a common task in computer vision. One way to do this is with the Hough (pronounced "Huff") transform. The math behind it is beyond the scope of this example, but we should be able to get you off the ground using it with OpenCV and Python. We're going to assume you have OpenCV installed already and are able to use it in Python.
Take an input image, say, these solar system moons:
Let's detect the circles in this image. The gist is this:
- Open an image
- Detect circles in it
- Draw those circles back on the image (you don't need to do this necessarily, but it's a nice visual)
Here's the code to extract circles in Python:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26
Here's the result:
As you can see, there is still some error! The most elliptical of our Galilean satellites wasn't detected at all, and the radius of a couple others is off. Tweaking the parameters for your use case will help this. If you want to count almost-circles or not count them, how sharp the edge needs to be to count as a detection, and so on.