OpenCV:计算椭圆长轴和短轴的方向角 [英] OpenCV: calculating orientation angle of major and minor axis of ellipse

查看:455
本文介绍了OpenCV:计算椭圆长轴和短轴的方向角的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在使用 cv2.fitEllipse() 在轮廓上拟合椭圆.此函数返回中心坐标、长短轴和旋转角度.我想知道旋转角度是否与此处给出的正水平轴的主轴角度相同(来源:维基百科):

I am using cv2.fitEllipse() to fit an ellipse over a contour. This function returns the center coordinates, major and minor axis, and rotation angle. I want to know if the rotation angle is the same as the angle of the major axis from the positive horizontal axis given here(src: Wikipedia):

如果不是,那么有什么办法可以得到下面等式中椭圆的系数:

If not, then is there any way to get the coefficients of the ellipse in the equation below:

然后直接计算角度.

推荐答案

这将向您展示 Python/OpenCV 中的 fitEllipse 角度.

This will show you about the fitEllipse angle in Python/OpenCV.

输入:

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()

结果:

这篇关于OpenCV:计算椭圆长轴和短轴的方向角的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆