How to interpolate the coordinates of a vector in an image using MATLAB?

For example, if I have a vector that describes a rectangle

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

in the image.

How to get the following vector

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

using the built-in MATLAB function or do I need to write it using FOR LOOPS?

The algorithm should work for a common vector with n-points and xy coordinates.

+3
source share
3 answers

If you have an image processing toolbar, you can do this by creating a polygon image and then finding the path:

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')

Edited to show how to use bwtraceboundary and prevent pixel offsets from rectangles.

+4
source

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

- a*X+b*Y=c.

Let h and w be the width and height of your buffer:

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

For each pair of points (x1, y1) โ†’ (x2, y2) a, b and c:

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

Now calculate straigt:

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

A matrix stis a w * h matrix containing a smooth line passing through the points (x1, y1) and (x2, y2). Now release right from the line, masking the unnecessary parts:

[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)]

We simply manually drew one line without an explicit loop. There are no guarantees for the effectiveness of the code :-)

Finally: add another dimension to each formula above (on the left as an exercise for the reader).

0
source

Source: https://habr.com/ru/post/1734928/


All Articles