Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/python/326.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Python OpenCV:计算椭圆长轴和短轴的方向角_Python_Opencv - Fatal编程技术网

Python OpenCV:计算椭圆长轴和短轴的方向角

Python OpenCV:计算椭圆长轴和短轴的方向角,python,opencv,Python,Opencv,我使用cv2.fitEllipse在轮廓上拟合椭圆。此函数用于返回中心坐标、长轴和短轴以及旋转角度。我想知道旋转角度是否与此处给出的正水平轴的长轴角度相同 如果没有,那么有没有办法得到下式中椭圆的系数: 然后直接计算角度。这将向您展示Python/OpenCV中的fitEllipse角度 输入: 结果: 这将向您展示Python/OpenCV中的椭圆角度 输入: 结果: 要查看角度是否与长轴匹配,只需在报告的角度处绘制一条穿过中心的线。如果它是沿着长轴的,那么你就有了答案。要查看角度是否与长轴匹

我使用cv2.fitEllipse在轮廓上拟合椭圆。此函数用于返回中心坐标、长轴和短轴以及旋转角度。我想知道旋转角度是否与此处给出的正水平轴的长轴角度相同

如果没有,那么有没有办法得到下式中椭圆的系数:


然后直接计算角度。

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

输入:

结果:


这将向您展示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()