Skip to content Skip to sidebar Skip to footer

Draw Cocentric Circles in Jupyter Notebook

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 well-nigh circle detection. See below for the gist:

Hey Adrian,

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

Thanks.

Great question.

Every bit you lot've probably already institute out, detecting circles in images using OpenCV is substantially harder than detecting other shapes with abrupt edges.

Only don't worry!

In this blog post I'll show yous how to utilise the cv2.HoughCircles office to observe circles in images using OpenCV.

To learn how to detect circles with OpenCV, just keep reading!

Looking for the source code to this post?

Leap Right To The Downloads Department

The cv2.HoughCircles Function

In club 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, simply with a fiddling caption, I retrieve you lot'll get the hang of it.

Take a look at the role signature beneath:

cv2.HoughCircles(image, method, dp, minDist)          
  • image: viii-bit, single aqueduct epitome. If working with a colour prototype, convert to grayscale start.
  • method: Defines the method to observe circles in images. Currently, the just 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 altitude between the center (ten, y) coordinates of detected circles. If the minDist is besides minor, multiple circles in the same neighborhood every bit the original may exist (falsely) detected. If the minDist is also large, then some circles may not be detected at all.
  • param1: Slope value used to handle border 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'southward really not also bad.

But I volition say this — exist fix to play around with the parameter values from paradigm 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

Set to utilise the cv2.HoughCircles function to detect circles in images?

Dandy. Let's leap into some code:

# import the necessary packages import numpy as np import argparse import cv2  # construct the argument parser and parse the arguments ap = argparse.ArgumentParser() ap.add_argument("-i", "--image", required = Truthful, assist = "Path to the image") args = vars(ap.parse_args())          

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

Then, on Lines seven-ix we parse our control line arguments. We'll demand only a single switch, --image, which is the path to the image we want to detect circles in.

Allow's go ahead and load the image:

# load the image, clone information technology for output, and then convert it to grayscale image = cv2.imread(args["paradigm"]) output = image.copy() grey = cv2.cvtColor(paradigm, cv2.COLOR_BGR2GRAY)          

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

Equally we'll see, the cv2.HoughCircles function requires an 8-scrap, single channel epitome, then we'll go ahead and convert from the RGB color space to grayscale on Line 14.

Okay, time to observe the circles:

# detect circles in the image circles = cv2.HoughCircles(grey, cv2.HOUGH_GRADIENT, 1.2, 100)  # ensure at to the lowest degree some circles were establish if circles is not None: 	# convert the (x, y) coordinates and radius of the circles to integers 	circles = np.round(circles[0, :]).astype("int")  	# loop over the (x, y) coordinates and radius of the circles 	for (x, y, r) in circles: 		# describe the circle in the output image, then draw a rectangle 		# corresponding to the middle of the circumvolve 		cv2.circumvolve(output, (x, y), r, (0, 255, 0), 4) 		cv2.rectangle(output, (ten - five, y - 5), (x + v, y + v), (0, 128, 255), -1)  	# show the output epitome 	cv2.imshow("output", np.hstack([paradigm, output])) 	cv2.waitKey(0)          

Detecting the circles is handled past the cv2.HoughCircles function on Line 17. Nosotros pass in the image nosotros want to detect circles as the beginning argument, the circumvolve detection method as the 2d argument (currently, the cv2.cv.HOUGH_GRADIENT method is the merely circle detection method supported by OpenCV and will likely be the only method for some fourth dimension), 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 i circle was found in the paradigm.

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

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

We draw the bodily detected circle on Line 28 using the cv2.circle function, followed past drawing a rectangle at the middle of the circumvolve on Line 29.

Finally, Lines 32 and 33 display our output image.

Then there you take information technology — detecting circles in images using OpenCV.

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

Burn upwards a vanquish, and execute the following command:

$ python detect_circles.py --paradigm images/simple.png          

We'll start with something elementary, detecting a red circumvolve on a black groundwork:

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

Non bad! Our Python script has detected the red circumvolve, outlined it in green, and and so placed an orange foursquare at the center of information technology.

Let'due south move on to something else:

$ python detect_circles.py --image images/soda.png          
Figure 2: Detecting the top of a soda can using circle detection with OpenCV.
Figure two: Detecting the peak of a soda can using circle detection with OpenCV.

Once again, our Python script is able to detect the round region of the can.

Now, let'due south try the viii circumvolve problem.

In this problem nosotros have one big circle, followed byseven circles placed inside the big one.

Since this is a much smaller image than the previous ones (and we are detecting multiple circles), I'm going to arrange 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 nosotros take ran into a problem.

The cv2.HoughCircles function was able to discover merely 7 of the circles instead of alleight, leaving out the one in the centre.

Why did this happen?

Information technology'due south due to the minDist parameter. The heart(x, y) coordinates for the large outer circle are identical to the heart inner circle, thus the center inner circumvolve is discarded.

Unfortunately, in that location is non a way around this problem unless nosotros make minDist unreasonably small, and thus generating many "false" circle detections.

What's side by side? I recommend PyImageSearch University.

Course information:
35+ total classes • 39h 44m video • Concluding updated: April 2022
★★★★★ 4.84 (128 Ratings) • 3,000+ Students Enrolled

I strongly believe that if you had the right teacher y'all could master reckoner vision and deep learning.

Do you lot think learning calculator vision and deep learning has to be time-consuming, overwhelming, and complicated? Or has to involve complex mathematics and equations? Or requires a degree in informatics?

That's not the instance.

All you need to master computer vision and deep learning is for someone to explain things to you in simple, intuitive terms. And that's exactly what I do. My mission is to change education and how complex Artificial Intelligence topics are taught.

If you lot're serious nearly learning computer vision, your next stop should be PyImageSearch University, the about comprehensive computer vision, deep learning, and OpenCV course online today. Hither yous'll learn how to successfully and confidently utilize estimator vision to your work, inquiry, and projects. Join me in computer vision mastery.

Inside PyImageSearch Academy you'll discover:

  • 35+ courses on essential figurer vision, deep learning, and OpenCV topics
  • 35+ Certificates of Completion
  • 39+ hours of on-demand video
  • Make new courses released regularly , ensuring yous can keep upward with land-of-the-art techniques
  • Pre-configured Jupyter Notebooks in Google Colab
  • ✓ Run all code examples in your web browser — works on Windows, macOS, and Linux (no dev environment configuration required!)
  • ✓ Access to centralized code repos for all 450+ tutorials on PyImageSearch
  • Easy one-click downloads for code, datasets, pre-trained models, etc.
  • Admission on mobile, laptop, desktop, etc.

Click hither to bring together PyImageSearch University

Summary

In this blog postal service I showed y'all how to employ the cv2.HoughCircles role in OpenCV to find circles in images.

Dissimilar 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 kickoff, I would debate that the most important parameter to play with is the minDist, or the minimum distance between the center (ten, y) coordinates of detected circles.

If you lot set minDist too modest, you may cease up with many falsely detected circles. On the other manus, if minDist is as well large, then you may stop up missing some circles. Setting this parameter definitely takes some fine tuning.

Have a Question?

Practise yous have a question about OpenCV and Python? Just send me a message. And I'll practise my best to answer it on this blog.

Download the Source Lawmaking and FREE 17-folio Resource Guide

Enter your email address below to go a .cypher of the code and a Free 17-page Resource Guide on Computer Vision, OpenCV, and Deep Learning. Inside you'll notice my paw-picked tutorials, books, courses, and libraries to help you master CV and DL!

mooreuppelve.blogspot.com

Source: https://pyimagesearch.com/2014/07/21/detecting-circles-images-using-opencv-hough-circles/

Post a Comment for "Draw Cocentric Circles in Jupyter Notebook"