从已知的边界框坐标计算旋转的矩形大小

时间:2012-04-02 05:20:24

标签: math geometry rotation bounding-box

我读了Calculate Bounding box coordinates from a rotated rectangle以了解如何从旋转的矩形计算边界框坐标。但在特殊情况下如下图:

http://i.stack.imgur.com/3UNfD.png

如果获得了边界框大小,坐标和旋转度,如何获得旋转的矩形尺寸?

我尝试在javascript中编写代码

//assume w=123,h=98,deg=35 and get calculate box size
var deg = 35;
var bw = 156.9661922099485;
var bh = 150.82680201149986;

//calculate w and h
var xMax = bw / 2;
var yMax = bh / 2;
var radian = (deg / 180) * Math.PI;
var cosine = Math.cos(radian);
var sine = Math.sin(radian);
var cx = (xMax * cosine) + (yMax * sine)   / (cosine * cosine + sine * sine);
var cy =  -(-(xMax * sine)  - (yMax * cosine) / (cosine * cosine + sine * sine));
var w = (cx * 2 - bw)*2;
var h = (cy * 2 - bh)*2;

但......答案与w和h不匹配

2 个答案:

答案 0 :(得分:42)

enter image description here

解决方案

根据bx给定边框尺寸bytx的矩形尺寸y的逆时针旋转:

x = (1/(cos(t)^2-sin(t)^2)) * (  bx * cos(t) - by * sin(t))
y = (1/(cos(t)^2-sin(t)^2)) * (- bx * sin(t) + by * cos(t))

推导

为什么会这样?

首先,考虑长度为bx的{​​{1}}长度为ab。使用三角法以bxxy来表达theta

bx = b          + a
bx = x * cos(t) + y * sin(t)            [1]

,同样适用于by

by = c          + d
by = x * sin(t) + y * cos(t)            [2]

12可以矩阵形式表示为:

[ bx ] = [ cos(t)  sin(t) ] * [ x ]     [3]
[ by ]   [ sin(t)  cos(t) ]   [ y ]

请注意,矩阵几乎一个旋转矩阵(但不完全 - 它是一个减号。)

左侧划分矩阵,给出:

[ x ] = inverse ( [ cos(t)  sin(t) ]    * [ bx ]                        [4]
[ y ]             [ sin(t)  cos(t) ] )    [ by ]

矩阵逆是easy to evaluate for a 2x2 matrix并扩展为:

[ x ] = (1/(cos(t)^2-sin(t)^2)) * [ cos(t) -sin(t) ] * [ bx ]           [5]
[ y ]                             [-sin(t)  cos(t) ]   [ by ]

[5]给出了两个公式:

x = (1/(cos(t)^2-sin(t)^2)) * (  bx * cos(t) - by * sin(t))             [6]
y = (1/(cos(t)^2-sin(t)^2)) * (- bx * sin(t) + by * cos(t))

简单就是馅饼!

答案 1 :(得分:-1)

您可能需要affine transformation之类的东西来发现点坐标。然后使用标准几何公式计算尺寸。