在 OpenCv 中以给定角度测量轮廓宽度
Measuring width of contour at given angle in OpenCv
给定 OpenCV 中的轮廓,我可以使用 cv2.boundingRect(contour)
提取宽度和高度。这 returns 边界矩形的宽度和高度,如左图所示。
给定一个角度,是否可以提取旋转后的外接矩形的width/height,如右图所示?
我想测量运动物体的长度,但我需要测量运动方向的长度,有时可能与水平线成 45 度角。
我知道有一种方法可以让 a 旋转边界矩形,使用 cv2.minAreaRect
和 cv2.boxPoints
,但我需要的旋转并不总是匹配最小面积矩形,所以我需要能够以某种方式指定角度。
我只需要旋转的宽度和高度值,我真的不需要旋转的轮廓,如果这样更容易的话。
使用
cv2.minAreaRect(cnt)
在这里你可以找到here完整的例子和解释。
编辑:minAreaRect 实际上是您所需要的,从定向矩形中获取宽度和高度有什么问题?
作为我的评论:Why not. Support you have an angle, then you can make two orthogonality lines. Calculate the distance between pts and each line, then calc max_dist - min_dict, you will get width and height.
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.]
现在是2017.12.14 00:20:55 CST
,晚安。
给定 OpenCV 中的轮廓,我可以使用 cv2.boundingRect(contour)
提取宽度和高度。这 returns 边界矩形的宽度和高度,如左图所示。
给定一个角度,是否可以提取旋转后的外接矩形的width/height,如右图所示?
我想测量运动物体的长度,但我需要测量运动方向的长度,有时可能与水平线成 45 度角。
我知道有一种方法可以让 a 旋转边界矩形,使用 cv2.minAreaRect
和 cv2.boxPoints
,但我需要的旋转并不总是匹配最小面积矩形,所以我需要能够以某种方式指定角度。
我只需要旋转的宽度和高度值,我真的不需要旋转的轮廓,如果这样更容易的话。
使用
cv2.minAreaRect(cnt)
在这里你可以找到here完整的例子和解释。
编辑:minAreaRect 实际上是您所需要的,从定向矩形中获取宽度和高度有什么问题?
作为我的评论:Why not. Support you have an angle, then you can make two orthogonality lines. Calculate the distance between pts and each line, then calc max_dist - min_dict, you will get width and height.
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.]
现在是2017.12.14 00:20:55 CST
,晚安。