基于坐标变换的旋转矩形点遍历存在空缺与越界问题求解
遍历旋转矩形内点时出现空缺与点超出范围的问题
我需要遍历旋转矩形内的点(对应包含特定像素值的图像矩阵区域),并按特定条件修改这些点,但循环未能完整覆盖矩形区域,存在未被遍历的空缺部分。
实现思路
非旋转矩形内的点可通过嵌套for循环轻松遍历,因此我先生成非旋转矩形内的点,再通过旋转矩阵进行坐标变换,将其映射到旋转后的角度(旋转角度通过计算得到)。
代码实现
% 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
问题现象
运行代码后,绘制出的点未能完整填充矩形区域(为便于观察,循环步长设为10):
- 存在明显的未填充空缺区域
- 部分点超出了目标矩形的范围
我怀疑是旋转角度计算有误,但无法确定,请问该如何修正此问题?
内容的提问来源于stack exchange,提问作者Soham
相关产品推荐
相关产品推荐

