使用边框矩形获取旋转角度无效(OpenCV/Python)

6

我正在尝试整理这封信件,但我不确定如何使用边界矩形来完成。

以下是我的进展:

import cv2
import numpy as np

img = cv2.imread('rtes.jpg',0)

ret,thresh = cv2.threshold(img,127,255,0)
ret,contours,hierarchy = cv2.findContours(thresh, 1, 2)

cnt = contours[0]
M = cv2.moments(cnt)
print M
cx = int(M['m10']/M['m00'])
cy = int(M['m01']/M['m00'])
#cnt = contours[2]
#cv2.drawContours(img, [cnt], 0, (0,255,0), 3)
rect = cv2.minAreaRect(cnt)
box = cv2.boxPoints(rect)
box = np.int0(box)
cv2.drawContours(img,[box],0,(255,0,0),2)
cv2.imshow('img',img)

k = cv2.waitKey(0)
if k == 27:         # wait for ESC key to exit
    cv2.destroyAllWindows()

这是结果: enter image description here

我查阅了OpenCV文档,但无法让它工作。最终我会尝试写一个循环,尝试4个角度来判断是否直线。

1个回答

12
cv2.minAreaRect(cnt)

返回一个已经存储旋转信息的Box2D对象。

(x,y),(width,height),theta

其中 θ 是水平线和 Box2D 对象的第一条边之间的夹角,在您的示例中为内轮廓的较短侧。

这取决于您试图实现的最终结果,但如果您只想旋转此特定示例,可以按照以下方式操作:

rows, cols = img.shape
rect = cv2.minAreaRect(cnt)
center = rect[0]
angle = rect[2]
rot = cv2.getRotationMatrix2D(center, angle-90, 1)
print(rot)
img = cv2.warpAffine(img, rot, (rows,cols))

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接