Open In App

Finding minimum enclosing circle in OpenCV Python

In this article, we are going to see how to draw the minimum enclosing circle covering the object using OpenCV Python. For that, we will be using the concepts of Contours

Let’s start with the code :



Import-Module and read images

In this step, we will import the OpenCV library and then read the image with its help.




import cv2
  
# To read image
img = cv2.imread("cloud.png", cv2.IMREAD_COLOR)
cv2.imshow("Image", img)
cv2.waitKey(0)
cv2.destroyAllWindows()

Output:



 

Convert image to grayscale

To get a clear image we need to convert it into grayscale.




gray = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)
ret, thresh = cv2.threshold(gray, 127, 255, 0)

Find the contours in the image 

Contours can be extracted by using cv2.findContours() function. We can select a contour cnt or loop over the all contour




# finding the contours
contours, _ = cv2.findContours(thresh, cv2.RETR_TREE,
                               cv2.CHAIN_APPROX_SIMPLE)
  
# take the first contour
count = contours[0]

Printing moments

Let’s print the moments for the contours we get.




M = cv2.moments(count)
print(M)

Output:

{'m00': 4781.5, 'm10': 554065.5, 'm01': 684678.6666666666, 'm20': 66858944.916666664,
 'm11': 78978179.04166666, 'm02': 99446416.41666666, 'm30': 8363188151.05, 'm21': 9486949067.266666,
 'm12': 11421819195.433332, 'm03': 14643992682.300001, 'mu20': 2655540.4849506766, 'mu11': -360277.0465901643,
 'mu02': 1405032.6273862273, 'mu30': 347729.0371904373, 'mu21': -3306939.5028494596, 'mu12': 1453113.8002238572, 
 'mu03': 1551705.8647060394, 'nu20': 0.11615144219852615, 'nu11': -0.015758260433092374,
 'nu02': 0.061455122575518134, 'nu30': 0.00021995333829451466, 'nu21': -0.002091779245894235,
 'nu12': 0.0009191560010733997, 'nu03': 0.0009815196560831125}

Drawing and Displaying Circle Boundary

In this step, we will see how the circle will cover the cloud in the image using cv2.minEnclosingCircle().

Syntax : (x,y),radius = cv2.minEnclosingCircle(cnt)

where “cnt” are the contour points.




(x_axis,y_axis),radius = cv2.minEnclosingCircle(count)
  
center = (int(x_axis),int(y_axis))
radius = int(radius)
  
cv2.circle(img,center,radius,(0,255,0),2)
cv2.imshow("Image",img)
cv2.waitKey(0)
cv2.destroyAllWindows()

Output:

 


Article Tags :