How to Find the Minimum Enclosing Circle of an Object in OpenCV Python?
Image processing is the heart of Computer Vision, and processing the object inside images is the most crucial task. When it comes to object detection and recognition, it is essential to find the minimum boundary that covers the object of interest. One of the essential shapes for this purpose is the minimum enclosing circle. In this tutorial, we will learn how to find the minimum enclosing circle of an object in OpenCV Python.
What is a minimum enclosing circle?
A minimum enclosing circle is a circle that encloses a set of points such that the radius of the circle is the smallest possible. In other words, it is the smallest circle that covers all the points in a set.
How to find the minimum enclosing circle?
To find the minimum enclosing circle, we can use the OpenCV Python library. The cv2.minEnclosingCircle() method is used to obtain the minimum enclosing circle of a set of points or contours.
Let’s take a look at the following Python code:
import cv2
import numpy as np
# Reading the image
img = cv2.imread("image.jpg")
# Converting the image to grayscale
gray = cv2.cvtColor(img,cv2.COLOR_BGR2GRAY)
# Applying the Canny edge detection
edges = cv2.Canny(gray,50,150)
# Finding the contours of the object
contours, hierarchy = cv2.findContours(edges,cv2.RETR_EXTERNAL,cv2.CHAIN_APPROX_SIMPLE)
# Drawing the contours on the image
cv2.drawContours(img, contours, -1, (0, 255, 0), 2)
# Finding the minimum enclosing circle for each contour
for i in range(len(contours)):
(x,y),radius = cv2.minEnclosingCircle(contours[i])
center = (int(x),int(y))
radius = int(radius)
img = cv2.circle(img,center,radius,(0,255,0),2)
# Displaying the image
cv2.imshow("Minimum Enclosing Circle", img)
cv2.waitKey(0)
In the above code:
- We first read the input image using cv2.imread() method.
- Then convert it to grayscale using cv2.cvtColor() method.
- After that, we detect edges of the object using cv2.Canny() method.
- Next, we find contours of the object using cv2.findContours() method.
- Then, we draw the contours on the image using cv2.drawContours() method.
- Finally, we find the minimum enclosing circle using cv2.minEnclosingCircle() method and draw it on the image using cv2.circle() method.
Conclusion
In conclusion, we have learned how to find the minimum enclosing circle of an object in OpenCV Python using the cv2.minEnclosingCircle() method. The minimum enclosing circle is the smallest circle that covers all the points in a set. This technique is very helpful in object detection and recognition.