opencv 旋转矩形的角度问题

在处理旋转矩形时,常常遇到角度如何计算、宽高如何确定问题,本文进行解释

1
2
3
4
5
# 生成模拟图片
image = np.zeros((400, 400,3), dtype='uint8')
image[180:251, 100:301,:] = 255
cv2.circle(image,(301,251),10,(255,0,0),thickness=-1)
show_images([image])

png

以下代码依次旋转图片,然后使用 cv2.findContours 查找轮廓,并计算旋转矩形的旋转角、宽高

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
# 模拟旋转角度
images=[image]
titles=['init']
for angle1 in list(range(0, 360, 45)):
rotated = imutils.rotate(image.copy(), angle1)
rotated=cv2.cvtColor(rotated,cv2.COLOR_RGB2GRAY)
try:
_, contours, hierarchy = cv2.findContours(rotated, cv2.RETR_TREE, cv2.CHAIN_APPROX_SIMPLE)
except ValueError:
contours, hierarchy = cv2.findContours(rotated, cv2.RETR_TREE, cv2.CHAIN_APPROX_SIMPLE)
rotatedRect = cv2.minAreaRect(contours[0])

angle = rotatedRect[-1]
w, h = rotatedRect[1]
x,y = rotatedRect[0]

# print('x:{}\t,x:{}\t,x:{}\t,x:{}\t,x:{}\t,'.format(x,y,w,h,angle))
cv2.putText(rotated, 'angle:' + str(int(angle)), (100, 25), cv2.FONT_HERSHEY_SIMPLEX, 1, 255)
cv2.putText(rotated, '(h,w):({0},{1})'.format(int(h), int(w)), (80, 60), cv2.FONT_HERSHEY_SIMPLEX, 1, 255)

images.append(rotated)
titles.append(str(angle1))

show_images(images,titles=titles)

png

从上图可以得出结论:

  1. 返回的角度在 [0,90] 之间,宽高也不固定
  2. 角度为 x 轴顺时针旋转,第一次接触到矩形边界时的值,范围:0~90°,第一次接触的边界为宽