matlab 使用坐标变换迭代旋转矩形中的点

svmlkihl  于 2023-06-23  发布在  Matlab
关注(0)|答案(1)|浏览(142)

我试图迭代旋转矩形内的点,它基本上是一个包含某些像素值的图像矩阵,并根据某些条件修改它们。但是循环计数器没有正确地填充矩形,并且矩形中存在未被跟踪的“空白空间”。

我的方法:

很容易使用嵌套的for循环对非旋转矩形内的各个点进行迭代。我的方法是在一个未旋转的矩形中生成点,并使用坐标变换,使用旋转矩阵将这些点Map到旋转的Angular 。旋转Angular 很容易找到。

代码如下-

% Define the coordinates of the vertices of the rectangle
x1 = 100;  % X-coordinate of vertex 1
y1 = 200;  % Y-coordinate of vertex 1
x2 = 400;  % X-coordinate of vertex 2
y2 = 300;  % Y-coordinate of vertex 2
x3 = 300;  % X-coordinate of vertex 3
y3 = 500;  % Y-coordinate of vertex 3
x4 = x1 + (x3 - x2);  % X-coordinate of vertex 4
y4 = y1 + (y3 - y2);  % Y-coordinate of vertex 4

% Calculate the rotation angle
angle = -atan2(y2 - y1, x2 - x1);  

% Calculate the center of the rectangle
centerX = (x1 + x2 + x3 + x4) / 4;
centerY = (y1 + y2 + y3 + y4) / 4;

% Define the dimensions of the rectangle
width = (x2 - x1);
height = (y4 - y1);

xv = [x1 x2 x3 x4 x1];
yv = [y1 y2 y3 y4 y1];
plot(xv,yv,'r','LineWidth',2)

% Iterate over points within the rectangle boundaries
for i = round(centerY - height/2):10: round(centerY + height/2)
    for j = round(centerX - width/2):10: round(centerX + width/2)
        

        % Apply inverse rotation transformation
        x = (cos(angle) * (j - centerX)) + (sin(angle) * (i - centerY)) + centerX;
        y = (-sin(angle) * (j - centerX)) + (cos(angle) * (i - centerY)) + centerY;
        
        x11=round(x);
        y11=round(y);

        hold on
        plot(x11,y11,'b*')
    end
end

**输出及问题:**x1c 0d1x

我已经展示了如何使用反正切函数计算旋转Angular 。
很明显,我画的点并没有完全填满矩形。注意:为了清楚起见,我在每次迭代中将循环计数器设置为5个点,但如黄色箭头所示,有一些空白的地方没有被填充。紫色箭头还显示了一些刚好滑到预期矩形之外的点。我该怎么做才能纠正这个错误呢?显然,它看起来像有一些错误的旋转Angular ,但我不确定。
先谢谢你了!

h6my8fg2

h6my8fg21#

你的坐标x1y1..不是矩形而是平行四边形(你可以检查两个相邻边之间的Angular 不是Pi/2)。
所以这个变换的仿射矩阵不是简单的旋转而是包含了剪切,你的Apply inverse rotation transformation是不正确的。
您可以选择-或精确计算旋转矩形顶点,或者使用给定的平行四边形与相应的仿射矩阵。
您可以得到正确的仿射变换矩阵,如这里所述或here with ready formulas
(for矩形源表达式由于一些相等的坐标而变得更简单,但在Matlab中,您可以使用内置的方法来逆矩阵和多重矩阵)

相关问题