3

例如,如果我有一个描述矩形的向量

xy=[165  88; 
    401  88; 
    401 278; 
    165 278];

在图像上。

如何获得以下向量

[165  88; % increase X -     hold y
 166  88; 
 167  88;
   ...  ;
 399  88;
 400  88;
 401  88; % hold     x - increase y
 401  89;
 401  90;
 401  91;
   ...  ;
 401 276;
 401 277;
 401 278; % decrease X -     hold y
 400 278;
 399 278;
 398 278;
   ...  ;
 167 278;
 166 278;
 165 278; % hold     x - decrease y
 165 277;
 165 276;
   ...  ;
 165  87];

使用 MATLAB 内置函数还是需要使用 FOR LOOPS 编写它?

该算法必须适用于具有 n 点和 xy 坐标的通用向量。

4

3 回答 3

4

如果你有图像处理工具箱,你可以通过创建多边形图像然后找到轮廓来做到这一点:

xy=[165 88; 401 88; 401 278; 165 278];
%# create the image - check the help for impolygon for how to make sure that
%# your line is inside the pixel
img = poly2mask(xy(:,1),xy(:,2),max(xy(:,1))+3,max(xy(:,2))+3);
figure,imshow(img) %# show the image

%# extract the perimeter. Note that you have to inverse x and y, and that I had to
%# add 1 to hit the rectangle - this shows one has to be careful with rectangular 
%# polygons
boundary = bwtraceboundary(logical(img),xy(1,[2,1])+1,'n',8,inf,'clockwise');

%# overlay extracted boundary
hold on, plot(boundary(:,2),boundary(:,1),'.r')

编辑显示如何使用 bwtraceboundary 并警告像素偏移与矩形。

于 2010-03-01T19:53:19.080 回答
0

使用 IND2SUB 的一种解决方案:

xy=[165 88; 401 88; 401 278; 165 278];
xmin = min(xy(:,1))-1;
xmax = max(xy(:,1));
ymin = min(xy(:,2))-1;
ymax = max(xy(:,2));

ncol=xmax-xmin;
nrow=ymax-ymin;

[xn yn]=ind2sub([nrow ncol],1:nrow*ncol);
xypairs = [xn'+xmin yn'+ymin];
于 2010-03-01T19:16:47.080 回答
0

将直线绘制到屏幕外矩阵中的快速而肮脏的方法是评估公式a*X+b*Y=c

让 h 和 w 成为缓冲区的宽度和高度:

X = repmat([0:w-1], h, 1)
Y = repmat([0:h-1]', 1, w)

对于每对点 (x1,y1)->(x2,y2),a、b 和 c 为:

a = y2-y1
b = x1-x2
c = x1*y2-x2*y1

现在计算直线:

st = a*X+b*Y-c
st(abs(st)>1) = 1
st = 1 - abs(st)

Matrixst是 aw*h 矩阵,包含通过点 (x1,y1) 和 (x2,y2) 的抗锯齿直线。现在让我们通过屏蔽不需要的部分来直接进入直线:

[xs] = sort([x1 x2])
st = st .* [zeros(h, xs(1)) ones(h, xs(2)-xs(1)) zeros(h, w-xs(2))]
[ys] = sort([y1 y2])
st = st .* [zeros(ys(1), w) ; ones(ys(2)-ys(1), w) ; zeros(h-ys(2), w)]

我们刚刚手动绘制了一条没有任何显式循环的线。虽然不能保证代码的效率:-)

最后:为上面的每个公式添加另一个维度(留给读者作为练习)。

于 2010-03-01T19:53:11.380 回答