如何在 OpenCV Python 中找到对象的最小外接圆?
对象的最小外接圆(circumcircle)是完全覆盖具有最小面积的对象的圆。我们可以使用函数 cv2.minEnclosingCircle() 找到对象的最小外接圆。
语法
此函数的语法是 −
(x,y),radius = cv2.minEnclosingCircle(cnt)
其中,"cnt"是轮廓点。它表示为轮廓点数组。
输出− 返回中心坐标 (x,y) 和最小外接圆的半径。(x,y) 和半径为浮点型。因此,要在图像上绘制一个圆,我们将它们转换为整数。
要绘制最小外接圆,我们使用与在图像上绘制圆相同的函数 -
cv2.circle(img,center,radius,(0,255,0),2)
步骤
您可以使用以下步骤找到对象的最小外接圆 -
导入所需的库。在以下所有 Python 示例中,所需的 Python 库是 OpenCV。确保您已安装它。
import cv2
使用 cv2.imread() 读取输入图像并将其转换为灰度。这里我们加载一个名为 fourpoint-star.png 的图像。
img = cv2.imread('fourpoint-star.png') gray = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)
对灰度图像应用阈值处理以创建二值图像。调整第二个参数以实现更好的轮廓检测。
ret,thresh = cv2.threshold(gray,150,255,0)
使用 cv2.findContours() 函数查找图像中的轮廓。
contours, _ = cv2.findContours(thresh, cv2.RETR_TREE,cv2.CHAIN_APPROX_SIMPLE)
选择轮廓 cnt 或循环遍历所有轮廓。使用 cv2.minEnclosingCircle(cnt) 函数找到轮廓 cnt 的最小外接圆。
cnt = contours[0] (x,y),radius = cv2.minEnclosingCircle(cnt)
将中心和半径传递给以下函数,在输入图像上绘制最小外接圆。第三和第四个参数是所绘制圆的颜色和粗细。
center = (int(x),int(y)) radius = int(radius) cv2.circle(img,center,radius,(0,255,0),2)
显示已绘制凸包的图像。
cv2.imshow("Circle", img) cv2.waitKey(0) cv2.destroyAllWindows()
让我们看一些例子以便更清楚地理解。
示例 1
在下面的 Python 程序中,我们检测图像中对象的轮廓并找到该对象的最小外接圆。我们还在输入图像上绘制最小外接圆。
# import required libraries import cv2 # load the input image img = cv2.imread('fourpoint-star.png') gray = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY) # apply thresholding to convert grayscale to binary image ret,thresh = cv2.threshold(gray,150,255,0) # find the contours contours,hierarchy = cv2.findContours(thresh, cv2.RETR_TREE,cv2.CHAIN_APPROX_SIMPLE) print("Number of contours detected:", len(contours)) # select the first contour cnt = contours[0] # find the minimum enclosing circle (x,y),radius = cv2.minEnclosingCircle(cnt) # convert the radius and center to integer number center = (int(x),int(y)) radius = int(radius) # Draw the enclosing circle on the image cv2.circle(img,center,radius,(0,255,0),2) cv2.imshow("Circle", img) cv2.waitKey(0) cv2.destroyAllWindows()
我们将在此程序中使用此图像作为输入文件 -
输出
执行上述代码时,将产生以下输出 -
Number of contours detected: 1
并且,我们得到以下输出窗口 -
检测到的物体的最小外接圆以绿色绘制。
示例 2
在此例如,我们检测图像中物体的轮廓并找到物体的最小包围圆。我们还在输入图像上绘制所有最小包围圆。
import cv2 import matplotlib.pyplot as plt img = cv2.imread('shape.png') img1 = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY) ret,thresh = cv2.threshold(img1,150,255,0) contours,hierarchy = cv2.findContours(thresh, cv2.RETR_TREE,cv2.CHAIN_APPROX_SIMPLE) print("Number of objects detected:", len(contours)) # find the enclosing circle for all the contours in the image for cnt in contours: (x,y),radius = cv2.minEnclosingCircle(cnt) center = (int(x),int(y)) radius = int(radius) img = cv2.circle(img,center,radius,(0,0,255),3) # Display the image cv2.imshow("Circle", img) cv2.waitKey(0) cv2.destroyAllWindows()
我们将在此程序中使用此图像作为输入文件 -
输出
当我们执行上述代码时,它将产生以下输出 -
Number of contours detected: 3
我们得到以下输出窗口 -
检测到的对象的最小包围圆以红色显示。