Detecting Circles in Images using OpenCV and Hough Circles

Figure 2: Detecting the top of a soda can using circle detection with OpenCV.

A few days ago, I got an email from a PyImageSearch reader asking about circle detection. See below for the gist:

Hey Adrian,

Love your blog. I saw your post on detecting rectangles/squares in images, but I was wondering, how do you detect circles in images using OpenCV?

Thanks.

Great question.

As you’ve probably already found out, detecting circles in images using OpenCV is substantially harder than detecting other shapes with sharp edges.

But don’t worry!

In this blog post I’ll show you how to utilize the cv2.HoughCircles function to detect circles in images using OpenCV.

Read on to find out how.

Looking for the source code to this post?
Jump right to the downloads section.

OpenCV and Python versions:
This example will run on Python 2.7/Python 3.4+ and OpenCV 2.4.X/OpenCV 3.0+.

The cv2.HoughCircles Function

In order to detect circles in images, you’ll need to make use of the cv2.HoughCircles function. It’s definitely not the easiest function to use, but with a little explanation, I think you’ll get the hang of it.

Take a look at the function signature below:

cv2.HoughCircles(image, method, dp, minDist)

  • image: 8-bit, single channel image. If working with a color image, convert to grayscale first.
  • method: Defines the method to detect circles in images. Currently, the only implemented method is cv2.HOUGH_GRADIENT, which corresponds to the Yuen et al. paper.
  • dp: This parameter is the inverse ratio of the accumulator resolution to the image resolution (see Yuen et al. for more details). Essentially, the larger the dp gets, the smaller the accumulator array gets.
  • minDist: Minimum distance between the center (x, y) coordinates of detected circles. If the minDist is too small, multiple circles in the same neighborhood as the original may be (falsely) detected. If the minDist is too large, then some circles may not be detected at all.
  • param1: Gradient value used to handle edge detection in the Yuen et al. method.
  • param2: Accumulator threshold value for the cv2.HOUGH_GRADIENT method. The smaller the threshold is, the more circles will be detected (including false circles). The larger the threshold is, the more circles will potentially be returned.
  • minRadius: Minimum size of the radius (in pixels).
  • maxRadius: Maximum size of the radius (in pixels).

If this method seems complicated, don’t worry. It’s actually not too bad.

But I will say this — be ready to play around with the parameter values from image to image. The minDist parameter is especially important to get right. Without an optimal minDist value, you may end up missing out on some circles, or you may detecting many false circles.

Detecting Circles in Images using OpenCV and Hough Circles

Ready to apply the cv2.HoughCircles function to detect circles in images?

Great. Let’s jump into some code:

Lines 2-4 import the necessary packages we’ll need. We’ll utilize NumPy for numerical processing, argparse for parsing command line arguments, and cv2 for our OpenCV bindings.

Then, on Lines 7-9 we parse our command line arguments. We’ll need only a single switch, --image, which is the path to the image we want to detect circles in.

Let’s go ahead and load the image:

We load our image off disk on Line 12 and create a copy of it on Line 13 so we can draw our detected circles without destroying the original image.

As we’ll see, the cv2.HoughCircles function requires an 8-bit, single channel image, so we’ll go ahead and convert from the RGB color space to grayscale on Line 14.

Okay, time to detect the circles:

Detecting the circles is handled by the cv2.HoughCircles function on Line 17. We pass in the image we want to detect circles as the first argument, the circle detection method as the second argument (currently, the cv2.cv.HOUGH_GRADIENT method is the only circle detection method supported by OpenCV and will likely be the only method for some time), an accumulator value of 1.5 as the third argument, and finally a minDist of 100 pixels.

A check is made on Line 20 to ensure at least one circle was found in the image.

Line 22 then handles converting our circles from floating point (x, y) coordinates to integers, allowing us to draw them on our output image.

From there, we start looping over the center (x, y) coordinates and the radius of the circle on Line 25.

We draw the actual detected circle on Line 28 using the cv2.circle function, followed by drawing a rectangle at the center of the circle on Line 29.

Finally, Lines 32 and 33 display our output image.

So there you have it — detecting circles in images using OpenCV.

But let’s go ahead and take a look at some results.

Fire up a shell, and execute the following command:

We’ll start with something simple, detecting a red circle on a black background:

Figure 1: Detecting a simple circle in an image using OpenCV.

Figure 1: Detecting a simple circle in an image using OpenCV.

Not bad! Our Python script has detected the red circle, outlined it in green, and then placed an orange square at the center of it.

Let’s move on to something else:

Figure 2: Detecting the top of a soda can using circle detection with OpenCV.

Figure 2: Detecting the top of a soda can using circle detection with OpenCV.

Again, our Python script is able to detect the circular region of the can.

Now, let’s try the 8 circle problem.

In this problem we have one large circle, followed by seven circles placed inside the large one.

Since this is a much smaller image than the previous ones (and we are detecting multiple circles), I’m going to adjust the minDist to be 75 pixels rather than 100.

Figure 3: Notice how cv2.HoughCircles failed to detect the inner-most circle.

Figure 3: Notice how cv2.HoughCircles failed to detect the inner-most circle.

Hm. Now it looks like we have ran into a problem.

The cv2.HoughCircles function was able to detect only seven of the circles instead of all eight, leaving out the one in the center.

Why did this happen?

It’s due to the minDist parameter. The center (x, y) coordinates for the large outer circle are identical to the center inner circle, thus the center inner circle is discarded.

Unfortunately, there is not a way around this problem unless we make minDist unreasonably small, and thus generating many “false” circle detections.

Summary

In this blog post I showed you how to use the cv2.HoughCircles function in OpenCV to detect circles in images.

Unlike detecting squares or rectangles in images, detecting circles is substantially harder since we cannot reply on approximating the number of points in a contour.

To help us detect circles in images, OpenCV has supplied the cv2.HoughCircles function.

While the cv2.HoughCircles method may seem complicated at first, I would argue that the most important parameter to play with is the minDist, or the minimum distance between the center (x, y) coordinates of detected circles.

If you set minDist too small, you may end up with many falsely detected circles. On the other hand, if minDist is too large, then you may end up missing some circles. Setting this parameter definitely takes some fine tuning.

Have a Question?

Do you have a question about OpenCV and Python? Just send me a message. And I’ll do my best to answer it on this blog.

Downloads:

If you would like to download the code and images used in this post, please enter your email address in the form below. Not only will you get a .zip of the code, I’ll also send you a FREE 17-page Resource Guide on Computer Vision, OpenCV, and Deep Learning. Inside you'll find my hand-picked tutorials, books, courses, and libraries to help you master CV and DL! Sound good? If so, enter your email address and I’ll send you the code immediately!

, , ,

169 Responses to Detecting Circles in Images using OpenCV and Hough Circles

  1. Nick R January 12, 2015 at 4:51 pm #

    Hi! Great tutorial, I just had a quick question – if I am doing this on Windows and not Linux how would I go about doing the same thing? Or would I have to run this through a windows command prompt?

    • Adrian Rosebrock January 12, 2015 at 5:25 pm #

      Hi Nick, you would have to run the script from the Windows command prompt.

      • ATUL September 1, 2017 at 2:44 am #

        Hey.. Adrian.
        Can you provide me a code for this picture. I want to find out the Coordinates of holes in the given picture. Please Help me
        .
        Thanx in advance.

        • Adrian Rosebrock September 1, 2017 at 9:41 am #

          While I’m happy to help, I cannot write code for you. I hope you understand.

      • cf September 5, 2017 at 2:01 am #

        Do you also use c++ programming language to describe algorithm

        • Adrian Rosebrock September 5, 2017 at 9:12 am #

          I only provide Python code here on PyImageSearch.

  2. Dustin Decker January 26, 2015 at 3:57 pm #

    FINALLY! I’m guessing my search foo was lacking, but this is the first place I’ve found a concise walk through of the cv2.HOUGH_GRADIENT method, particularly the MinDist impact… for the past 24 hours I’ve been trying random values to deduce how all this was working.

    THANK YOU!

    • Adrian Rosebrock January 26, 2015 at 4:47 pm #

      Hi Dustin. Awesome! I’m glad to hear that the tutorial was helpful for you!

  3. Ifeoma January 28, 2015 at 10:51 pm #

    Thanks so much for the detailed explanation. I used it to detect circles in my Android application when pictures are taken with the camera. It worked fine and saved me a lot of time. Thanks.

    • Adrian Rosebrock January 29, 2015 at 6:49 am #

      Fantastic, I’m happy the article helped!

  4. Denis February 3, 2015 at 1:10 pm #

    What a great time to learn python image recognition. Thanks.

  5. Sofia February 21, 2015 at 8:34 pm #

    Hey Adrian!

    Thanks for the run-through.

    Is there an intuitive way to understand the meaning of param1, param2, and dp?

    Moreover, I am confused because: my images have many circle-like objects, but if I increase the range of radii by increasing maxRadius, I sometimes get fewer circles. Is this something you have seen and could explain?

    Thanks a lot!

    • Adrian Rosebrock February 22, 2015 at 7:15 am #

      Hi Sofia, if you have many circle like objects and you increase the maxRadius, then you will certainly find fewer circles. The maxRadius parameter controls the maximum radius of a circle. So if a circle has a radius greater than maxRadius, then it will not be detected. I would also take a look at these slides for a more in-depth review of circle detection.

  6. Jayanthi.P March 6, 2015 at 6:04 am #

    I run this code but i got an error in line no 22.It displayed error like IndentationError:expected an indented block.How to run this code without an error.Can you help me sir?.Thank you.

    • Adrian Rosebrock March 6, 2015 at 6:28 am #

      Based on that error it looks like your Python code is not indented correctly — perhaps you mixed both spaces and tabs?

  7. Jayanthi.P March 7, 2015 at 3:34 am #

    Sir what do you mean python code is not indented correctly?.In line no 22 you use astype(“int”) that int show in error.If i change int like float,i got the same error.What i suppose to do?.

    • Adrian Rosebrock March 7, 2015 at 6:50 am #

      The “int” or “float” is not the issue. The problem is you may have mixed tabs and spaces in your indentation of the code. More information on this type of error can be found in this StackOverflow post. If you can spare the time, brushing up on a bit of Python will definitely help you avoid these types of errors.

  8. Rama Chandran.P March 9, 2015 at 4:29 am #

    Sir i am doing my project on human computer interaction.In that i plan to do roak paper sscissor game and arithmetic operation.So i have an hand image which capture from webcam.From that captured image i have to fix center point and contour point.So that only i can detect fingers.Sir can you tell me how to fix these points and how to detect finger from the hand image?.Thank you!

    • Adrian Rosebrock March 9, 2015 at 8:27 am #

      Hi Rama, you’ll have to look into the topic of “contour defects” to aide in detecting fingers connected to the hand.

  9. Vinh March 17, 2015 at 11:03 am #

    Hello

    It is a great tutorial.

    I have a question: in my image, the circle is not perfect, but just “like a circle”

    (something like: https://mysticalbootcamp.files.wordpress.com/2011/12/3.jpg)

    Now I want to measure the radius of this kind of “circle”. How can I start?

    Thank you very much

    • Adrian Rosebrock March 17, 2015 at 11:33 am #

      There are different ways to approach a problem like this. You could try more advanced techniques of ellipse detection, those would probably help. Personally, I would just find the contours of each circle, compute the center of the circle, and from there, it’s simple to determine the radius.

  10. Mon April 8, 2015 at 11:40 am #

    It’s great! I just had a question – how can I find coordinates of the circle? ex: x= ,y=

    • Adrian Rosebrock April 8, 2015 at 11:42 am #

      Line 25 gives you the x, y coordinates of the center of the circle along with the radius.

  11. Heyne April 9, 2015 at 12:03 pm #

    Can I detect circles in video by picamera and how? Thanks so much

    • Adrian Rosebrock April 9, 2015 at 12:57 pm #

      You certainly can, but you’ll have to tune the parameters of the cv2.HoughCircles function, which is not always the easiest task. I would suggest starting by reading this post on accessing the Raspberry Pi camera.

      • Heyne April 13, 2015 at 9:38 am #

        Thanks, I’ve tried but have not yet done. what should I do next?

        • Adrian Rosebrock April 13, 2015 at 11:32 am #

          The scikit-image package as a more powerful transform that would probably be worth looking into.

      • Steve Carter December 10, 2016 at 9:39 pm #

        Hi Adrian,
        On this point here – using the raspberry pi camera.
        What if I wanted to take a photo using the raspberry pi camera and then use cv2.HoughCircles to determine whether or not a circle was present in the picture taken?
        Is that an easier task than simply detecting circles from a raw stream?
        Thanks
        Steve

        • Adrian Rosebrock December 12, 2016 at 10:44 am #

          A video stream is just a collection of frames. Each frame can be considered an individual image. A video stream can be slightly more complicated due to motion blur as objects move, but the same general process applies. Technically applying circle detection to a single image (provided there is no blur) is easier, but if you can guarantee that in a video stream, it’s just as easy.

    • Dave April 27, 2015 at 11:58 am #

      Hey!! did you solve it?

      I need to do exactly the same, and i don’t know how to do that. If you both please can help me, i’ll be very grateful.

      I’m using a picamera with a raspberry pi B+.

      Thanks a bunch!

  12. Elmo June 28, 2015 at 1:21 pm #

    Hello adrian, is it possible to detect an oval object as a circle too? i mean the object is not a perfect circle. i’ve implemented your tutorial but it cannot detect the non-perfect-circle object. or maybe which params that i need to change? thanks a lot before

    • Adrian Rosebrock June 28, 2015 at 2:37 pm #

      You can indeed detect an ellipse/oval region instead of a circle in an image, but it’s a bit more challenging (especially for the algorithm itself). Take a look at the circular and elliptical Hough transforms of scikit-image for more information.

  13. Pranav September 10, 2015 at 1:28 pm #

    Hi Adrian,

    You are doing a fantastic job. Your blog has now become my preferred destination to search for any python + opencv feature. I was wondering if you plan to write an article on multiprocessing of images for increasing speed anytime soon.
    So I want to batch process some images from a given folder and save the output in another folder. I tried using Pool from multiprocessing library but am running into errors. Any pointers?

    • Adrian Rosebrock September 11, 2015 at 6:31 am #

      Hey Pranav — thanks for putting this back on my radar. I was planning on doing a series of posts on Hadoop and image processing in the future, but I should start with just the basics of multiprocessing. As for other libraries, you might want to give pp a try.

  14. Bosmart September 13, 2015 at 3:52 pm #

    Hi, Cool stuff! I’m trying to make it detect my iris but no luck, even if I open my eyes really wide… Any suggestions?

    • Adrian Rosebrock September 14, 2015 at 6:15 am #

      If you’re trying to detect your iris, then I’m not sure circle detection is your best bet. I would try simple thresholding methods (since there will be substantial contrast between your iris and the whites of your eyes) first.

  15. Ibrahim October 3, 2015 at 5:27 am #

    Hi Adrian,

    Thanks for the tutorials. I’m having trouble with detecting circles using OpenCV 3 with Python3. I can load and image and video stream from the camera however when I try to use cv2.cv.CV_HOUGH_GRADIENT I get an error

    ‘module’ object has no attribute ‘cv’.

    Changing this to cv2.CV_HOUGH_GRADIENT I get a different error

    ‘module’ object has no attribute ‘CV_HOUGH_GRADIENT’.

    I am working within the virtual environment (if that’s the correct terminology).

    Any help would be appreciated.

    Cheers,
    Ibrahim

    • Adrian Rosebrock October 3, 2015 at 6:15 am #

      Again, just to firm: you’re using OpenCV 3? If so, then it should be: cv2.HOUGH_GRADIENT

      • John Tilghman May 23, 2017 at 6:05 pm #

        I am using the Python/OpenCV that I created using your:

        https://www.pyimagesearch.com/2015/12/14/installing-opencv-on-your-raspberry-pi-zero/

        When I run your code here, I get:

        (cv) pi@raspberrypi:~ $ python detect_circles.py –image Hough_image1.jpg

        circles = cv2.HoughCircles(gray, cv2.CV_HOUGH_GRADIENT, 1.2, 100)
        AttributeError: ‘module’ object has no attribute ‘CV_HOUGH_GRADIENT’

        Not sure how to fix this one yet.

        • Adrian Rosebrock May 25, 2017 at 4:25 am #

          Hi John — it sounds like you are using OpenCV 3 while this blog post assumes you’re using OpenCV 2.4. In OpenCV 3 the cv2.CV_HOUGH_GRADIENT flag changed to cv2.HOUGH_GRADIENT

      • Mohamed O. August 29, 2017 at 1:59 am #

        Thanks. I faced the same issue & changing it to cv2.HOUGH_GRADIENT worked for me.

  16. Talat Shaikh October 20, 2015 at 12:13 am #

    Hi Adrian,

    How do I output the number of circles detected on the terminal screen?\
    Thanks.

    • Adrian Rosebrock October 20, 2015 at 6:13 am #

      The circles variable is just a list, so just use the len function:

      print(len(circles))

  17. akif November 25, 2015 at 11:10 am #

    Hi there,
    How can we find the radius of circle?

    • Adrian Rosebrock November 25, 2015 at 1:52 pm #

      Hey Akif — you’ll want to look into the cv2.minEnclosingCircle function. This will give you the radius of the circle.

      • akif November 27, 2015 at 4:12 pm #

        Hi ,I have got another question.
        I am trying to do iris recognition system.For the last step,I need to encode the normalized image into binary and then,match the encoded images.
        For encoding,I used cv2.imencode,is this right thing to do?
        For matching,I could not find what to do.
        Thank you…

  18. Ty December 7, 2015 at 3:18 am #

    Hi,

    Thanks for the tutorials Adrian

    I can detect circles when I use the sample images you provided but when I try to read other images like this image http://www.clker.com/cliparts/U/D/6/q/l/q/12-color-circles-hi.png , the hough circles return None as the value meaning no circles were detected. The parameters I used were 1.2 as dp and 75 as minDist. Am I doing something wrong?

    Thanks in advance


    Hi again,

    I think I found a solution. It had something to do with the image size. After resizing the image to 300×300, I was able to detect some circles.

    I have another image with dimension 640×480. I tried resizing it to 300×300 but I believe the circles in the original image would become ellipses once they’re compressed. Is there any other way I can do this? Also does the input image have to be a perfect square dimension image? I saw that the sample images you provided all have perfect square dimensions.

    Thanks in advance

    • Adrian Rosebrock December 7, 2015 at 6:56 am #

      The images do not have to be a perfect square, they can be rectangular, that’s not an issue at all. Often times it’s beneficial to resize your images and make them smaller before you process them.

  19. Mike January 8, 2016 at 9:49 pm #

    Hi Adrian, I’m prefacing this with: I am very new to python or opencv

    is there some way to name or number the circles I detect? Not just print the total number found, but place a unique identifier on each one.

    For instance, if I have an image with 5 circles, can I place a “1” on the first one, a “2” on the second, etc.
    Thanks

    • Adrian Rosebrock January 9, 2016 at 6:19 am #

      Since circles is just a list, I would assign a unique identifier to each one pasted on the index of the circle in the list. For example

      for (i, (x, y, r)) in enumerate(circles):

      Will assign the unique index i to each circle in the circles list.

  20. Selim January 9, 2016 at 9:18 am #

    Hi,

    I ran the code, but there is a problem. When the circles are moving, for example: a ball, code cannot detect it. Is there a way to solve this problem?

    I recently started learning raspberry, so an easy explanation is much appreciated.

    Thanks

    • Adrian Rosebrock January 9, 2016 at 5:34 pm #

      Hough circles is not a good method for real-time video processing. The motion blur makes it very challenging to reliably detect the circles. If possible, you might want to try color based methods or using HOG + Linear SVM.

  21. moti January 14, 2016 at 4:38 am #

    can you explain more about parameter 1 and 2?

    • moti January 14, 2016 at 4:46 am #

      i will add some agenda,
      1. i am following a ball with this method and point it with laser and servos, to make the “hit” more accurate i need good detection (parameters 1 &2).

      2. i try to run it in realtime, the loop time is ~180 ms with resolution of 640X480.
      to reduce the loop time i am cropping the image according to last recognition,
      thats make the loop time ~40 ms.
      BUT when running the SAME picture – the biggest picture find the circle just fine and with the cropped image it sometimes find bigger radius detection (with the same parameters).
      do you have an idea why the processing is different???
      thanks again

      • Adrian Rosebrock January 14, 2016 at 6:12 am #

        It sounds like you want to increase your FPS processing rate. If so, take a look at this post, as well as the posts it links to. Inside I detail how to speedup camera I/O substantially — this will help with your first problem.

        As for your second question, you’re running Hough circles on a smaller, cropped ROI? This actually does make sense due to the accumulator gradient. See the paper referenced in the blog post for more information.

    • Adrian Rosebrock January 14, 2016 at 6:09 am #

      For a deeper explanation of the parameters, review the Yuen et al. paper. This paper discusses the gradient value along with the accumulator.

      • moti January 14, 2016 at 8:40 am #

        thanks.

  22. Meryl January 26, 2016 at 10:56 pm #

    Thank you for this helpful tutorial!
    I am using this code you have provided to detect petri dishes for a project my lab is working on. I am having a few problems where the code is detecting a circle but it is off center from what I expect and doesnt match the contours of the petri dish. It also detects some circles that dont exist even though my min distance is 1000, which I think is quite high.
    I am new to image analysis and opencv and generally dont have much clue as to what I am doing, so I would really appreciate some help!

    • Adrian Rosebrock January 27, 2016 at 3:08 pm #

      It’s hard to say what the exact issue could be without seeing your images, but in general, it can be hard to determine the parameters to Hough circles. You might want to investigate simple contour methods instead using the cv2.findContours function and contour properties to identify circle-like regions. You can also try the scikit-image implementation for finding circles.

  23. YaddyVirus March 27, 2016 at 11:09 am #

    Hi Adrain! I tried running your code but it gives me an error saying-

    output = image.copy()
    AttributeError: ‘NoneType’ object has no attribute ‘copy’

    I have removed your input argument function and provided a direct image to the cv2.imwrite function. Could that be the problem? Because it looks like it is an input error.

    • Adrian Rosebrock March 28, 2016 at 1:34 pm #

      If you hardcoded your image path to cv2.imread and your image is None, then you’ll want to double check the path you supplied to cv2.imread and ensure that it’s correct. Based on the error message, I can almost guarantee that the path to the image is not valid.

  24. lali March 31, 2016 at 7:10 pm #

    Hi,after detecting circles with houghcircle ,i need to verify if all circles (wanted to be detected) is detected
    as a first solution is to add reference image which contained all circles must be detected
    and try to color the circle detected in the reference image
    i asked if it’s possible to do this with opencv.If,yes i need some keywords or helpful tutoriel
    If,no there is other solution and thanks to reply

    • Adrian Rosebrock April 1, 2016 at 3:17 pm #

      Hey Lali — I’m not sure I understand your question. What do you mean by “verify if all circles are detected”?

  25. Palanikumar April 2, 2016 at 3:18 am #

    Hey Adrian.. thanks for the tutorial. I’m having problem with executing the code. i encountered on 20th line
    circles = cv2.HoughCircles(gray, cv2.cv.CV_HOUGH_GRADIENT, 1.2, 100)
    where it shows
    AttributeError: ‘module’ object has no attribute ‘cv
    i tried with the change of cv to cv2 since i’m using opencv3..
    kindly give solution to this problem.. Thanks in advance

    • Adrian Rosebrock April 3, 2016 at 10:30 am #

      Indeed, this is an error related to OpenCV 3 (this blog post was originally written for OpenCV 2.4). You can resolve the error by changing cv2.cv.CV_HOUGH_GRADIENT to cv2.HOUGH_GRADIENT.

  26. bo April 4, 2016 at 6:31 am #

    thanks for your tutorial
    i have a question :if i want to get the coordinate of circle center,what should i do?

    • Adrian Rosebrock April 4, 2016 at 9:22 am #

      Take a look at Line 25. The x and y values contain the center of the circle.

  27. Harshita Mangal May 18, 2016 at 4:41 am #

    Hi, when I try to run this code I am getting an error: module ‘cv2’ has no attribute ‘cv’. I have openCV installed. Also, I tried the suggestion on stackoverflow to write import cv2.cv as cv and then use cv instead of cv2.cv but it still doesn’t work. Your help would be highly appreciated. Thanks in advance.

    • Adrian Rosebrock May 19, 2016 at 6:07 pm #

      It seems like you’re using OpenCV 3 — this tutorial was designed for OpenCV 2.4.X. Just change cv2.cv.CV_HOUGH_GRADIENT to cv2.HOUGH_GRADIENT and it will work.

  28. Tomaz July 23, 2016 at 2:26 pm #

    I would like to detect a circle in an image and after that, would have to convert the circle into a rectangular image using a polar conversion tool for rectangular . I’m working on C ++ , Visual Studio 2012, opencv 2.4.13 .
    The circle I’m managing to find the image but not can do the conversion , someone would have an idea of how to do this ? Thank you very much in advance.

    Sorry about my English.

  29. vinod August 3, 2016 at 7:52 am #

    hello,

    i have a question, how to detect these circles with driod camera,

    • Adrian Rosebrock August 4, 2016 at 10:14 am #

      I haven’t used a Droid camera before, but if you can access the camera via cv2.VideoCapture, you’ll be able to read frames from the camera and process them individually for circles.

  30. vinod August 8, 2016 at 3:02 pm #

    thank you so much Adrian , i developed the code , with help of your code, one more help i need how to calculate distance from camera to circle(object) .

  31. Brian September 5, 2016 at 9:06 am #

    Where are Param1, Param2, MinRadius, and MaxRadius used in your code? Thanks!

    • Adrian Rosebrock September 5, 2016 at 12:47 pm #

      Those parameters are optionally/implicitly supplied to cv2.HoughCircles on Line 17. I used the default values.

  32. LinuxCircle September 13, 2016 at 8:17 pm #

    Your articles have been helping me teach in Australia via LinuxCircle.com
    At the moment we are working on a ball-following robot, in which Raspberry Pi, webcam, OpenCV3, Python 3 and 4WD chassis are used. We want to detect any colour and shape, as long as it is circular object.
    Further question:
    1. How do we increase the chance of detecting just the one ball?
    2. Will image smoothing such as blurring method help in segregating the ball with the background?
    3. What is the role of light in Hough method? If the robot light a LED torch towards the ball will it increase the chance of being detected?

    • Adrian Rosebrock September 15, 2016 at 9:36 am #

      In general, I wouldn’t recommend Hough circles for this. The parameters are tough to get right, especially in a real-time setting. Instead, I would use something like this tutorial for ball tracking.

  33. Bv September 24, 2016 at 6:26 pm #

    Such a nice tutorial,So what is the use circle detection in computer vision and navigation, how important is this.

    • Adrian Rosebrock September 27, 2016 at 8:50 am #

      Can you elaborate on what you mean by “navigation”? What are you trying to accomplish?

  34. irving October 3, 2016 at 11:38 pm #

    where should I put the path of my image?

    • Adrian Rosebrock October 4, 2016 at 6:52 am #

      You can put the image wherever you like it — you just need to supply the path to the image via command line argument. I would suggest using the “Downloads” section of this tutorial to download the code + example images and using that as your starting point.

  35. satria November 17, 2016 at 4:55 am #

    hi adrian…
    i have some problem
    when i run the program

    output = image.copy()
    AttributeError: ‘NoneType’ object has no attribute ‘copy’

    what happend???

    • Adrian Rosebrock November 18, 2016 at 8:55 am #

      If you are getting an error related to “NoneType” right after cv2.imread is being called, then 99% of the time is because you supplied an invalid path to cv2.imread. Double check that the path to your input image is correct.

  36. GK_Bats December 8, 2016 at 4:54 pm #

    Hi Adrian,
    These are awesome tutorials.
    I’m trying to detect droplets in an image. But to start with, I tried executing your code, it worked fairly well for your sample images. But, for my images, it did not work. The cmd simply skipped to the next blank command line. I tried resizing the image size as well. Would you be able to help me with this?

    • Adrian Rosebrock December 10, 2016 at 7:21 am #

      If your Python script exited without error then I would debug the script by doing:

      print(circles)

      My bet is that no circles were actually detected and you need to tune the parameters to HoughCircles.

  37. Miral Desai February 20, 2017 at 5:38 am #

    Hi….

    I want to detect eyeball circle. I dumped the same script. But i got the error message as follows:

    output=image.copy()
    AttributeError: ‘None Type’ object has no attribute ‘copy’

    • Adrian Rosebrock February 20, 2017 at 7:37 am #

      It sounds like your image was not loaded from disk correctly, perhaps due to your command line arguments (i.e., path to an invalid file). Please take a look at this blog post for more information on resolving “NoneType” errors.

  38. Satvik March 14, 2017 at 2:12 am #

    I’m doing a project on smar fuel dispenser . Idea is to develop auto adjusting fuel dispenser . So can a get a code that will detect the fuel tank opening (circular) and which can give the position of it ( X Y Z co ordinates ) plz help me with this . Thank you

  39. Uwe March 15, 2017 at 4:57 am #

    Hello Adrian,
    If I have a Pi camera image, how is a circular detection possible?
    Thanks for the answer
    Uwe Reinersmann

  40. quiqueapolo March 20, 2017 at 1:09 pm #

    Hi Adrian:
    I want to count the number of oranges from this image: http://cmapspublic.ihmc.us/rid=1KMVN1NVZ-1FDS32V-1PMG/naranjos-con-naranjas.jpg
    Is it posiible? Could you give me a demostration if you want.

  41. Eric March 23, 2017 at 7:25 pm #

    HI Adrian, been enjoying you Practical Python and OpenCV book. It was a great starter. Now I’m trying to combine it with some of your blog examples. In the soda can example above, how would you create a mask for the outside of the circle? I could probably use some sort of fill to paint the outside but I would like to be able to create a mask so I can switch the mask on and off.

    Keep up the awesome work!

    • Adrian Rosebrock March 25, 2017 at 9:33 am #

      I would first detect the circle in the image. Then, create a mask for the circle. Then invert the mask. This will give you a mask for the non-circle region of the image.

  42. Zara May 9, 2017 at 2:56 am #

    is there any difference if i read image, apply blur, canny edge then houghcircle?
    I am not getting importance of param1 for providing internal canny? When i used internal canny i was not able to detect circle matrix.
    When i applied canny first then hough circle, false rejection was reduced. What does it make a sense?

    • Adrian Rosebrock May 11, 2017 at 8:58 am #

      It really depends on your input images. If your images are fairly “clean” already you can skip the blurring step. Applying the Canny edge detector further helps clean up the image, giving you only the binary edges. If your edges are well defined, it will improve the accuracy of the circle detector.

  43. Mono June 7, 2017 at 5:48 pm #

    In order to avoid false positives , I am trying to combine this example with your color based “Ball Tracking ” example

    I am facing some challenges to detect a tennis ball, o you have any tutorial or information related to parameter Tuning ?

    • Adrian Rosebrock June 9, 2017 at 1:45 pm #

      Hi Mono — instead of using Hough Circles to detect the tennis ball, why not detect the yellow of the tennis ball? That would be easier than working with Hough Circles.

  44. Debajyoti Dutta June 13, 2017 at 8:58 am #

    Sir,
    I just wanted to ask ,if it is possible to draw a small circle of a fixed radius on all the contours that I have detected? I do not want to find the bounding rectangle or circles for the contours. Pleas sir, help me out.

    • Adrian Rosebrock June 13, 2017 at 10:51 am #

      You would simply need to use the cv2.circle function. You can read about the function here. I also cover how to draw circles around contours inside Practical Python and OpenCV.

  45. Kevin Judd June 16, 2017 at 2:11 pm #

    Hey, thanks for the tutorial. I’m working on a project that requires the detection of a specific circle in an image that could potentially have multiple circles. I set the minimum distance between center points (minDist) to be equal to the length of the image so that the function would only be allowed to find a single circle despite the image having multiple circles in it. So I was wondering how the HoughCircles function decides which circle to output. Does it take the one that most closely resembles a circle, or maybe the circle with the greatest radius? The 8 circle example is a good example of what I’m asking. I understand why the function only returned 7 circles but why did it choose to return the outside circle instead of the inside circle?

    • Adrian Rosebrock June 20, 2017 at 11:19 am #

      It chooses the outside circle instead of the inside circle due to the minDist parameter. It will also filter circles based on any supplied maximum/minimum radius.

  46. Pranita June 22, 2017 at 3:41 am #

    Hey Adrian,
    Thank you for this tutorial.
    I am trying to detect ellipse shaped structures from images. I know there is function for ellipse detection in skimage and I also read your tutorial where you detect different shapes in an image. But my problem is I have images wherein the ellipse are not exact ellipse (like deformed ellipse). These ellipses are cells from some patient data and every patient image will have different size and shape of ellipses. Can it be still detected by hough transform?

    I tried using hough_ellipse but does not work well. I also tried k-means clustering but do not get convincing results. Do you have some suggestions or tutorial wherein I can detect arbitrary shapes?
    Regards
    Pranita

    • Adrian Rosebrock June 22, 2017 at 9:26 am #

      If the objects you are trying to detect are “deformed ellipses”, then I would suggest extracting contours and then computing the aspect ratio, extent, solidity, etc. These can be used to filter your shapes using a series of “if” statements. An example of using solidity/extent/aspect ratio to filter shapes can be found here.

  47. Rajnikant Sharma July 8, 2017 at 1:35 am #

    Hi Adrian,
    I am matlab developer, are we able to detect doors from following floorplan images using opencv?

    https://www.ada.gov/archive/NPRM2008/images/plan2aaccessible.jpg

    and
    http://kesterhouse.com/interior/photos/floorplan_01.png

    thanks

    • Adrian Rosebrock July 11, 2017 at 6:47 am #

      Hi Rajnikant — I am not a MATLAB user. Are you using me how to solve this issue with MATLAB?

  48. Evan July 31, 2017 at 3:37 pm #

    Hello, thanks for this awesome tutorial. Since this seems like a great way to do ball-tracking, I’m interested in your reasoning for choosing a different algorithm for your ball-tracking tutorial, and whether or not you think this would be a suitable algorithm for ball-tracking. Thank you in advance!

    • Adrian Rosebrock August 1, 2017 at 9:38 am #

      The reason is because the parameters of Hough Circles can be a real pain to tune in a case-by-case basis. Using simple color thresholding was a more accurate method to finding the ball and tracking it.

  49. Mohamed O. August 30, 2017 at 1:21 am #

    Hi Adrian,
    Thanks for the great tutorials.
    My question is: what kind of filters are helpful when you try to identify protruded circles made from the same material as the background, for example like the top surface of a child’s building block?
    I tried to convert the image first from color to grayscale, then applied a bilateral filter. I also tried to go one further step by converting the output of the bilateral filter to binary image, but it didn’t help either.

    Below is the code for the filters I used:

    gray = cv2.cvtColor(image, cv2.COLOR_BGR2GRAY)
    blurred = cv2.bilateralFilter(gray, 1, 60, 20)
    thresh = cv2.threshold(blurred, 84, 255, cv2.THRESH_BINARY)[1]

    The values I used in the code are based on tuning using different combinations of values, till I found out that these are the best match for my image.

    Appreciate any recommendations to achieve the best possible result.

    Thanks.

    • Adrian Rosebrock August 31, 2017 at 8:34 am #

      Hi Mohamed — I would have to see an example image of these “protruded circles” to suggest a method.

      • Mohamed O. September 2, 2017 at 10:28 am #

        Hi Adrian,
        I use this images as an example:
        https://ibb.co/bEm3Wv
        and so far, I am only able to correctly identify the leftmost circle in the top row, & the 3 leftmost circles in the bottom row.
        I am not sure why the code is not able to identify the other circles, but I assume it is due to low image quality. Is my assumption correct?
        Thanks in advance for your advice.

        • Adrian Rosebrock September 5, 2017 at 9:35 am #

          For low quality images with shadowing (which will be common with Lego images) using simple circle detection will likely be inaccurate. I would suggest using edge detection + contour processing, as detailed in Practical Python and OpenCV. You might also want to consider training a simple circle detector using the framework discussed in this blog post.

  50. satinder September 18, 2017 at 8:20 am #

    Hello sir, i would like to tell you that your tutorials are by far the best ones i have come across.
    I would like to know how you can detect the color of a circular ring and also i wanted to know how i can know whether something has gone through the ring or not.THANK YOU

    • Adrian Rosebrock September 18, 2017 at 1:59 pm #

      It really depends on your particular setup. I would suggest using color thresholding to identify the actual ring to start.

  51. siriusk September 25, 2017 at 5:12 am #

    This algorithm is not bad when you’ve an image with only circle, but when you’ve an image with many edges, in my tests, it’s not really efficient. There’s a way to made this algorithm more robust?

    • Adrian Rosebrock September 26, 2017 at 8:28 am #

      I demonstrate how to recognize shapes based on their contour properties in this post. I would suggest starting there if you have objects that have vertices.

  52. Anonymous October 8, 2017 at 11:03 am #

    Hello Adrian,
    If I wanted to do this from a raspberry pi using live stream and not one image, how would the code change?

    • Adrian Rosebrock October 9, 2017 at 12:24 pm #

      I would suggest starting with this post on accessing the Raspberry Pi camera module.

  53. Shoba October 26, 2017 at 3:09 am #

    Hi
    I want to detect the Tyre area in truck image and do color transformation over the area since the Tyre color close with shadow of image so it complicate the shadow removal task. Can you please guide how to detect the Tyre. How can i upload the image for your reference here.
    Thanks and Regards,

    • Adrian Rosebrock October 26, 2017 at 11:40 am #

      Hi Shoba — Feel free to post the images on pasteboard and provide a link here.

  54. Shoba October 29, 2017 at 3:02 am #

    Hi Adrian, Thanks for your reply but i cannot upload the image using the mentioned link suggest me how to do it.

    • Adrian Rosebrock October 30, 2017 at 3:10 pm #

      You can drag and drop images into the webpage. If that doesn’t work, try https://imgur.com/.

  55. smtabatabaie November 12, 2017 at 3:35 am #

    Hi Adrian, Thanks for the tutorial. I just had a question. Will this technique also work if circles in the image has perspective and are not completely in front view? So they are not complete circles and in perspective they will become ovals.
    Thanks

    • Adrian Rosebrock November 13, 2017 at 2:02 pm #

      Unfortunately no, this technique will rapidly fail once the viewing angle starts to change. The elliptical transform inside scikit-image might be better in this particular case.

      • Rohit December 7, 2017 at 8:23 am #

        hi Adrian,
        Can you tell me how to detect a ring or a hoop from any viewing angle??

        Thank in advance!!

  56. greatdevaks November 21, 2017 at 6:54 am #

    Hey Adrian,

    Great tutorial.
    Was thinking that what can be done to detect the concentric circles?

    Waiting for your earliest response.

    Thanks

    • Adrian Rosebrock November 21, 2017 at 1:19 pm #

      Yes, you can do this with concentric circles. Start with the largest possible radius. Detect the circle. Mask it out. Detect the next largest circle. Mask it out. Repeat until all circles have been detected.

  57. Ahmad Afghan December 15, 2017 at 5:12 am #

    i detected the circles but i aslo need to count these circles and print it on consol.
    need help

    • Adrian Rosebrock December 15, 2017 at 8:18 am #

      All you need is:

      print(len(circles))

  58. amber January 8, 2018 at 3:30 am #

    i m a beginner in python.. i am confused about argument parsing.. in your tutorial exactly where should i give the path to my image?in help or somewhere else?

    • Adrian Rosebrock January 8, 2018 at 2:37 pm #

      Hey Amber — it’s okay to be new to command line arguments, we all start somewhere! You supply the command line arguments in the terminal. You do not need to update the code. I would suggest reading up on command line arguments to help you get started.

  59. Tanmay Fuse January 26, 2018 at 5:11 pm #

    How to crop hough circle??

    • Adrian Rosebrock January 30, 2018 at 10:42 am #

      You can compute the bounding box of the rectangle and apply array slicing to extract it.

  60. Ashu February 5, 2018 at 6:16 am #

    The code seems to run only for squarish images..For example, this image does not work: https://upload.wikimedia.org/wikipedia/commons/thumb/9/9d/DFAexample.svg/250px-DFAexample.svg.png
    And can you explain how to adjust the parameters for each image and on what basis? Is there a way to automate this?

    • Adrian Rosebrock February 6, 2018 at 10:17 am #

      You might need to tune the parameters to the Hough circle detector in order for it to detect all circles in your images. Unfortunately there isn’t a way to automate this. A more robust method may be to train your own circle detector.

  61. raj February 25, 2018 at 1:06 am #

    hello, the above code is for tracking circular objects like what if we want to track object with different shape?

    • Adrian Rosebrock February 26, 2018 at 1:56 pm #

      There are a few ways to accomplish this, but mostly dependent on the dataset/project. What types of objects are you trying to detect and track?

  62. Hrishi March 1, 2018 at 1:08 am #

    Hi!….your tutorials are very nice and informative.For my project i want to detect only red circles using raspberry and pi cam.Can you help me?

    • Adrian Rosebrock March 2, 2018 at 10:48 am #

      Take a look at this post on shape and color detection.

  63. Juan Giraldo March 15, 2018 at 12:09 pm #

    Good morning.

    First I would like to highlight how informative and creative are your tutorials on artificial vision, really are very entertenidos and didactic, I congratulate you !.

    My question is can you count in a video the number of axles of a truck, 2 axles, 4 axles, 9?. I tried it but several inconvenients arise when trying to separate only the contours of the rim, detect several contours or not detect them with the function cv2.HoughCircles.

    • Adrian Rosebrock March 19, 2018 at 5:48 pm #

      Thank you for the kind words, Juan. I’m glad you are enjoying the blog!

      As for your question, how are you attempting to detect each set of axels?

      • Juan Giraldo March 20, 2018 at 1:06 pm #

        Hello Adrian, what a pleasure you read me 🙂

        Describing quickly what I have tried, it goes like this:

        – I play a video of a truck parade and to this I subtract the fund.
        – Then I perform two commands for Morphological Transformations (opening and closing) and make the video transmission clear.

        – Then I look for contours with the command cv2.RETR_EXTERNAL

        What happens is that many contours medetectan and only need those that are round to be able to count the axes of the truck (as the view is lateral each tire detected would represent an axis).

        – Try to define the minimum area that should have the outline but it is not very accurate and I keep appearing many

        – Then I would like to do it like in a tutorial of yours, I could observe how the trajectory of a green ball was followed and this is adapted for the black colored tires; The problem is that the tire color does not always have the same intensity and the circle on a trowel is not uniform, it’s like a kind of washer.

        With the function cv2.Canny (gray, 200, 300), I see well-defined circles in the transmission of the vine but I can not detect only the circles to follow them visually in the video.

        This I want to do is a hobby way to learn.

        Thank you very much.

        • Adrian Rosebrock March 22, 2018 at 10:15 am #

          Thank you for sharing the details Juan. I get the idea of what you are doing but it would be helpful to see some visuals. Would you be able to share any example images?

  64. Mike Oliver March 15, 2018 at 6:51 pm #

    Good Morning!
    I’m having trouble detecting circles in other images.
    The images “simple.png”, “8circles.ong” and “soda.png” work. But when I try to take a picture, it does not give a damn. The program ends immediately.
    What do I do?

    • Adrian Rosebrock March 19, 2018 at 5:43 pm #

      Hey Mike — it sounds like you’ll need to detect the parameters to cv2.HoughCircles. The function can be a bit of a pain to use. Depending on your input images you may need to utilize machine learning to train your own circle detector.

  65. Sai April 5, 2018 at 4:14 pm #

    Thanks a lot Adrian. Very well explained.

    • Adrian Rosebrock April 6, 2018 at 8:49 am #

      Thanks Sai, I’m glad you enjoyed it 🙂

  66. Mesco June 6, 2018 at 10:31 am #

    Hi, thanks for tutorial.

    OpenCV documentation says: “method – Detection method to use. Currently, the only implemented method is CV_HOUGH_GRADIENT , which is basically 21HT , described in [Yuen90].”

    https://docs.opencv.org/2.4/modules/imgproc/doc/feature_detection.html?highlight=houghcircles#houghcircles

    So now I’m totally confused: why it is called “gradient”?

    Also, despite of reading Yuen article I do not understand what is “accumulator”

  67. inferno June 16, 2018 at 5:51 am #

    how to resolve the problem of minimum distance parameter

    • Adrian Rosebrock June 19, 2018 at 8:59 am #

      Unfortunately for the Hough Circles function it’s a trial and error tuning process.

  68. Malouke July 12, 2018 at 5:45 am #

    hi thank you so much about topics .

    i have a remark about topics the HoughCircles algorithmes it s iterative one .

    here it s easy because the background its monocolor but if you try with balls and multiple color the algorithme its less accurate.
    my quesions can i ask you to do the same things but with multipls balls more than 10 and same color of balls
    you will see its hard to detect the circle shape.

    Thank s

    • Adrian Rosebrock July 13, 2018 at 5:07 am #

      You are correct, once you start creating more complex backgrounds Hough Circles will fail. For more complex objects you may want to consider training a custom object detector. For well defined shapes such as circles HOG + Linear SVM would be a good start.

  69. Abi August 12, 2018 at 5:29 am #

    This tutorial is a great help. However, as a beginner in python programming, may I ask for help on how I can create a 2d and/or 3d graph using the centers of circles as coordinates?

    • Adrian Rosebrock August 15, 2018 at 8:59 am #

      I’m not sure what exactly you’re trying to graph, but matplotlib tends to be a good library for plots and graphs.

      • Abi August 24, 2018 at 9:14 am #

        May I ask for help on how I can store all the coordinates of the centers of the circles detected?

        • Adrian Rosebrock August 30, 2018 at 9:43 am #

          Store as in write them to disk? You could use a CSV file, text file, JSON file, or whatever file format you wish. All you need is simple file I/O. If you’re new to Python and programming in general I would suggest reading up on Python basics before continuing.

  70. hs September 2, 2018 at 11:06 am #

    Hi, can i ask for help how do i make the camera capture once circle detected? thx

    • Adrian Rosebrock September 5, 2018 at 9:05 am #

      What does “capture” mean? Save a single frame to disk? Save a video clip?

  71. Manigandan K P September 4, 2018 at 1:44 am #

    Hello Sir, how to convert python file to Exe Application

  72. Zamra September 25, 2018 at 3:28 am #

    Hi, Is there any ways to find the intersection points of two detected circles using the x,y and radius of those 2 circles. I am trying to extract features from a 2 set Venn diagram therefore there intersection points are needed.

  73. Zamra September 25, 2018 at 3:33 am #

    Hi, Are there ways to store the detected circles to separate variables?

    • Adrian Rosebrock October 8, 2018 at 12:46 pm #

      Hey Zamra, I’m not sure what you mean by “separate variables” — could you elaborate?

  74. Andrea October 3, 2018 at 12:34 pm #

    Could you post a simple example of how to use the MinRadius and MaxRadious parameters please?

  75. Stefano Ceresa October 6, 2018 at 12:35 pm #

    Hello,
    I coded everything and there are no errors but when I send the program from the shell (I use a mac) I do not see anyout

    • Adrian Rosebrock October 8, 2018 at 9:41 am #

      Are you executing via the command line or via a Python shell itself? Try executing the script via the command line.

  76. Aashna October 31, 2018 at 5:00 pm #

    Hi Adrian,
    What if we want to detect just the region between two concentric circles and save that as another image
    Thanks 🙂

    • Adrian Rosebrock November 2, 2018 at 7:22 am #

      You can use the “cv2.imwrite” function to save an image/ROI to disk.

Leave a Reply