Reputation: 21
I have a matrix that is consists of some points of image.look at below
Cout=
[215,59;165,126;215,72;236,65;258,60;296,71;296,84;246,77;240,120;228,120;225,74;176,58;178,72];
Now I want to find points in rectangle below [x,y,width,height]
rec=[105,210,31,31]
How should I code it in Matlab? Thanks.
Upvotes: 1
Views: 1197
Reputation: 44
Use inpolygon.[https://www.mathworks.com/help/matlab/ref/inpolygon.html]
HOW IT WORKS:
in = inpolygon(xq,yq,xv,yv) returns in indicating if the query points specified by xq and yq are inside or on the edge of the polygon area defined by xv and yv.
xq: x-coordinates of query points, specified as a scalar, vector, matrix, or multidimensional array(The size of xq must match the size of yq).
yq: y-coordinates of query points, specified as a scalar, vector, matrix, or multidimensional array.
xv: x-coordinates of polygon vertices, specified as a vector(The size of xv must match the size of yv).
yv: y-coordinates of polygon vertices, specified as a vector.
in: Indicator for the points inside or on the edge of the polygon area, returned as a logical array. in is the same size as xq and yq.
% points of image you're searching
% (x,y) are not the coordinates of matrices in MATLAB! And images are
% matrices. The coordinates of matrices are (row, column) which is NOT (x,y) - it's (y,x).
yq=Cout(:,1)
xq=Cout(:,2)
xv=[rec(1);rec(1);rec(1)+rec(3);rec(1)+rec(3);rec(1)];
yv=[rec(2);rec(2)+rec(4);rec(2)+rec(4);rec(2);rec(2)];
in = inpolygon(xq,yq,xv,yv)
I find 2 points by this way.
Upvotes: 1
Reputation: 26069
here is what you need (I think):
Cout= [235,65;296,71;296,84;240,120;229,119;224,74;165,126];
Rec=[105,210,31,31];
% set the range of the rectangle in x and y
xr=[Rec(2) (Rec(2)+Rec(4))];
yr=[Rec(1) (Rec(1)+Rec(3))];
% draw the rectangle for ref
rectangle('Position',Rec); hold on
% the next line is what you asked for, checking if points fall in the
% rectangle I chose here limits with < and >, but you may want <= and >= ...
id = Cout(:,1)<xr(end) & Cout(:,1)>xr(1) & Cout(:,2)<yr(end) & Cout(:,2)>yr(1);
% let's check:
plot(Cout(:,2),Cout(:,1),'x',Cout(id,2),Cout(id,1),'ro')
Upvotes: 0