如何使用 OpenCV Python 将椭圆拟合到图像中的对象?
我们可以使用函数 cv2.fitEllipse() 将椭圆拟合到对象。椭圆内接于旋转的矩形。旋转的矩形是包围对象的最小面积的边界矩形。
语法
此函数使用的语法是 −
ellipse = cv2.fitEllipse(cnt)
其中,"cnt"是轮廓点。它表示为轮廓点数组。
输出 − 它以 ((x,y), (majorAxis, minorAxis), angle) 格式返回一个元组的元组。 (x,y) 是中心坐标,(majorAxis, minorAxis) 是短轴和长轴的长度,angle 是椭圆的旋转角度。
要在输入图像上绘制椭圆,我们使用以下函数 -
cv2.ellipse(img,ellipse, (0,0,255), 3)
步骤
您可以使用以下步骤将椭圆拟合到对象 -
导入所需的库。在以下所有 Python 示例中,所需的 Python 库是 OpenCV。确保您已安装它。
import cv2
使用 cv2.imread() 读取输入图像并将其转换为灰度。这里我们加载一个图像 naledstar1.png。
img = cv2.imread('star1.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.fitEllipse(cnt)"函数将椭圆拟合到对象轮廓"cnt"。
cnt = contours[0] ellipse = cv2.fitEllipse(cnt)
在输入图像上绘制椭圆。
cv2.ellipse(img,ellipse, (0,0,255), 3)
显示绘制了凸包的图像。
cv2.imshow("Ellipse", img) cv2.waitKey(0) cv2.destroyAllWindows()
让我们看一些例子,以便更清楚地了解理解。
我们使用以下图像作为以下示例的输入文件。
示例 1
在下面的 Python 程序中,我们检测图像中对象的轮廓并找到适合该对象的椭圆。我们在输入图像上绘制椭圆。
# import required libraries import cv2 import numpy as np # load the input image img = cv2.imread('star1.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] # fit the ellipse to the selected object ellipse = cv2.fitEllipse(cnt) # draw the ellipse on the input image cv2.ellipse(img,ellipse, (0,0,255), 3) # display the image with an ellipse drawn on it. cv2.imshow("Ellipse", img) cv2.waitKey(0) cv2.destroyAllWindows()
输出
执行上述代码时,将产生以下输出 −执行上述代码时,将产生以下输出 −
Number of contours detected: 1
我们得到以下输出窗口 −
与检测到的物体相符的椭圆以红色绘制。
让我们找到椭圆内切的旋转矩形。
示例 2
在此 Python 程序中,我们检测图像中物体的轮廓并找到适合该物体的椭圆。我们还找到了椭圆内切的旋转矩形。我们在输入图像上绘制椭圆和旋转的矩形。
# import required libraries import cv2 import numpy as np # load the input image img = cv2.imread('star1.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 area rectangle rect = cv2.minAreaRect(cnt) box = cv2.boxPoints(rect) box = np.int0(box) cv2.drawContours(img,[box],0,(0,255,255),2) # fit the ellipse ellipse = cv2.fitEllipse(cnt) cv2.ellipse(img,ellipse, (0,0,255), 3) # display the image with an ellipse drawn on it. cv2.imshow("ellipse", img) cv2.waitKey(0) cv2.destroyAllWindows()
输出
当我们执行上述代码时,它将产生以下输出 −
Number of contours detected: 1
我们得到以下输出窗口 −
椭圆用红色绘制,旋转矩形(最小面积)用黄色绘制。请注意,椭圆内接于旋转矩形内。