用matlab自写一个二维OBB包围盒代码
时间: 2023-10-18 12:05:31 浏览: 95
以下是用matlab自写的二维OBB包围盒代码:
function [OBB, corners] = computeOBB(points)
% 计算二维OBB包围盒
% points: n x 2 的点集矩阵,每行代表一个点的坐标
% 计算点集在x轴和y轴上的均值和协方差矩阵
meanX = mean(points(:,1));
meanY = mean(points(:,2));
covMat = cov(points);
% 计算协方差矩阵的特征向量和特征值
[V, D] = eig(covMat);
% 选取特征值最大的特征向量作为包围盒的长轴方向
if D(1,1) > D(2,2)
longAxis = V(:,1);
else
longAxis = V(:,2);
end
% 计算包围盒的宽度和高度
width = sqrt(max(D(1,1), 0));
height = sqrt(max(D(2,2), 0));
% 构造包围盒的四个顶点
corners = [meanX, meanY] + [-longAxis(2), longAxis(1)] * height/2 + [-longAxis(1), -longAxis(2)] * width/2;
corners(2,:) = corners(1,:) + longAxis * height;
corners(3,:) = corners(2,:) - [-longAxis(2), longAxis(1)] * width;
corners(4,:) = corners(1,:) - [-longAxis(2), longAxis(1)] * width;
% 构造包围盒结构体
OBB.center = [meanX, meanY];
OBB.longAxis = longAxis;
OBB.width = width;
OBB.height = height;
OBB.corners = corners;
end
使用示例:
points = [1,1; 2,3; 4,5; 7,6; 10,4];
[OBB, corners] = computeOBB(points);
disp(OBB);
disp(corners);
阅读全文