在OpenCv中以给定角度测量轮廓宽度

时间:2017-12-13 14:16:33

标签: python opencv opencv-contour

给定OpenCV中的轮廓,我可以使用cv2.boundingRect(contour)提取宽度和高度。这将返回边界矩形的宽度和高度,如左图所示。

给定一个角度,是否可以提取旋转的边界矩形的宽度/高度,如右图所示?

Contour illustration

我正在尝试测量移动物体的长度,但我需要测量移动方向的长度,有时距离水平线最多可达45度。

我知道有一种方法可以使用cv2.minAreaRectcv2.boxPoints来获取一个旋转的边界矩形,但我需要的旋转并不总是与最小面积矩形相匹配,所以我需要能够以某种方式指定角度。

我只需要旋转的宽度和高度值,我不需要旋转的轮廓,如果这样可以更容易。

2 个答案:

答案 0 :(得分:1)

使用

cv2.minAreaRect(cnt)

在这里,您可以找到here完整示例和解释。

编辑:minAreaRect实际上是你需要的,从面向矩形获取宽度和高度的问题是什么?

答案 1 :(得分:1)

正如我的评论:My mother language is Chinese

#!/usr/bin/python3 # 2017.12.13 22:50:16 CST # 2017.12.14 00:13:41 CST import numpy as np def calcPointsWH(pts, theta=0): # 计算离散点在特定角度的长宽 # Measuring width of points at given angle th = theta * np.pi /180 e = np.array([[np.cos(th), np.sin(th)]]).T es = np.array([ [np.cos(th), np.sin(th)], [np.sin(th), np.cos(th)], ]).T dists = np.dot(pts,es) wh = dists.max(axis=0) - dists.min(axis=0) print("==> theta: {}\n{}".format(theta, wh)) ,而不是我擅长英语写作。所以我把它变成代码:

pts = np.array([[100, 200],[200,  26],[300, 200],[200, 373]], np.int32)
for theta in range(0,91, 30):
    calcPointsWH(pts, theta)


==> theta: 0
[ 200.  347.]
==> theta: 30
[ 173.60254038  300.51081511]
==> theta: 60
[ 300.51081511  173.60254038]
==> theta: 90
[ 347.  200.]

将此钻石用于测试:

enter image description here

2017.12.14 00:20:55 CST

现在它是multip_result1,晚安。

相关问题