如何使用MATLAB在图像上插值矢量的坐标?

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循环来编写代码?

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


正确地说,xy不是向量,而是2列矩阵。 - yuk
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,并警告矩形像素偏移。


太好了!唯一的问题是“out”的排序。 “out”的相邻元素必须是2D曲线的相邻点 :'( - EnneKappa
那么您应该使用bwtraceboundary而不是bwperim。 - Jonas
使用boundary=bwboundaries(img);进行操作。 - EnneKappa

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];

但我只想要周长和通用向量xy来描述一个多边形,而不仅仅是矩形。 - EnneKappa
抱歉,没有理解最后一句话。您需要循环遍历多边形的每条边(只需要n次循环),并通过线性回归计算坐标。 - yuk

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)

矩阵st是一个w*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)]

我们刚刚手动绘制了一条单独的线,没有任何显式循环。但是代码效率方面不能保证 :-)

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


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接