python - OpenCV:计算椭圆长轴和短轴的方向角
问题描述
我cv2.fitEllipse()
用来在轮廓上拟合椭圆。此函数返回中心坐标、长轴和短轴以及旋转角度。我想知道旋转角度是否与主轴与此处给出的正水平轴的角度相同(src:Wikipedia):
如果没有,那么有什么方法可以在下面的等式中获得椭圆的系数:
然后直接计算角度。
解决方案
这将向您展示 Python/OpenCV 中的 fitEllipse 角度。
输入:
import cv2
import numpy as np
import math
# read input
img = cv2.imread('labrador.jpg')
# convert to gray
gray = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)
# threshold
thresh = cv2.threshold(gray, 100 , 255, cv2.THRESH_BINARY)[1]
# find largest contour
contours = cv2.findContours(thresh, cv2.RETR_EXTERNAL, cv2.CHAIN_APPROX_SIMPLE)
contours = contours[0] if len(contours) == 2 else contours[1]
big_contour = max(contours, key=cv2.contourArea)
# fit contour to ellipse and get ellipse center, minor and major diameters and angle in degree
ellipse = cv2.fitEllipse(big_contour)
(xc,yc),(d1,d2),angle = ellipse
print(xc,yc,d1,d1,angle)
# draw ellipse
result = img.copy()
cv2.ellipse(result, ellipse, (0, 255, 0), 3)
# draw circle at center
xc, yc = ellipse[0]
cv2.circle(result, (int(xc),int(yc)), 10, (255, 255, 255), -1)
# draw vertical line
# compute major radius
rmajor = max(d1,d2)/2
if angle > 90:
angle = angle - 90
else:
angle = angle + 90
print(angle)
xtop = xc + math.cos(math.radians(angle))*rmajor
ytop = yc + math.sin(math.radians(angle))*rmajor
xbot = xc + math.cos(math.radians(angle+180))*rmajor
ybot = yc + math.sin(math.radians(angle+180))*rmajor
cv2.line(result, (int(xtop),int(ytop)), (int(xbot),int(ybot)), (0, 0, 255), 3)
cv2.imwrite("labrador_ellipse.jpg", result)
cv2.imshow("labrador_thresh", thresh)
cv2.imshow("labrador_ellipse", result)
cv2.waitKey(0)
cv2.destroyAllWindows()
结果:
推荐阅读
- android - Android:附件到电子邮件应用程序后何时删除文件?
- sql - 在 utl_mail.send 中传递电子邮件时出错 (Oracle 11g - sql) 06502 - 06512
- javascript - 如何更新特定 URL 上的元素值?
- azure - 如何将多个图像推送到 Azure 注册表
- java - OpenCV java alpha 混合
- php - 固定总购物车优惠券
- c# - C# - 在我的数据网格中,当我使用按 'Id' Desc 排序的存储过程时,我的表单不显示 Desc
- windows - 在具有 uber-jar 依赖项 (javafx-graphics) 的 Windows 10 上使用 javafx-maven-plugin 构建运行时映像时出错
- c# - 循环遍历 2 个数组(Unity3d)
- vue.js - 即使页面重新加载,我如何在整个 SPA 中维护数据