我已经实现了以下简单代码:
import cv2
import numpy as np
nr_im = 9876
font = cv2.FONT_HERSHEY_SIMPLEX
fontScale = 1
colorText = (0, 0, 255)
thickness = 2
img = cv2.imread('testing/' + str(nr_im) + '.jpg')
original = img.copy()
blured_img = cv2.GaussianBlur(img,(17,17),5)
image = cv2.cvtColor(img, cv2.COLOR_BGR2HSV)
lower = np.array([0, 0, 140], dtype="uint8")
upper = np.array([0, 0, 255], dtype="uint8")
mask = cv2.inRange(image, lower, upper)
# Morphological Closing: Get rid of the noise inside the object
mask = cv2.morphologyEx(mask, cv2.MORPH_CLOSE, cv2.getStructuringElement(cv2.MORPH_ELLIPSE, (25, 25)))
# Find contours
cnts, _ = cv2.findContours(mask, cv2.RETR_EXTERNAL, cv2.CHAIN_APPROX_NONE)
print(len(cnts))
cntsElps = []
for num_cnt, cnt in enumerate(cnts):
genElipse = cv2.fitEllipse(cnt)
cntsElps.append(genElipse)
cv2.ellipse(original,genElipse,(0,255,0),2)
cv2.putText(original, str(num_cnt+1), (int(genElipse[0][0]),int(genElipse[0][1])), font, fontScale, colorText, thickness, cv2.LINE_AA)
print("Ellipse nb: " + str(num_cnt+1) + " has angle: " + str(genElipse[2]) + "\n")
cv2.imwrite('testing/' + str(nr_im) + '_' + 'trash2' + '.png', original)
我以这张图片为例:

我得到了以下图像结果:

每个椭圆的旋转角度为:
- 椭圆 nb:1 有角度:55.63788986206055
- 椭圆 nb:2 有角度:108.58539581298828
- 椭圆 nb:3 有角度:170.23861694335938
- 椭圆 nb:4 有角度:73.59089660644531
所以,我的结论是,垂直轴和矩形长边之间的角度(=椭圆长轴)是 fitEllipse() 方法中的旋转角度。