Point in polygon algorithm explanation - algorithm

Hi I came across this algorithm from Mathhelpforum which determines whether a point is inside or outside a polygon. The code works perfectly so far but I don't fully understand the logic. Kindly provide an explanation if you do, especially on the method...whether ray casting, or winding number, etc. Thanks.
function [ inside ] = inpoly(polygon,xt,yt)
rows = size(polygon);
npoints = rows(1);
disp (npoints);
inside = 0;
xold = polygon(npoints,1);
yold = polygon(npoints,2);
for i = 1:1:npoints
xnew = polygon(i,1);
ynew = polygon(i,2);
if (xnew > xold)
x1=xold;
x2=xnew;
y1=yold;
y2=ynew;
else
x1=xnew;
x2=xold;
y1=ynew;
y2=yold;
end
if ((xnew < xt) == (xt <= xold) & (yt-y1)*(x2-x1) < (y2-y1)*(xt-x1) )
inside=~inside;
end
xold=xnew;
yold=ynew;
end
endfunction
To test the function e.g. :
inpoly([p,q],x,y)
Where p and q are vertices of the polygon and x, y coordinates of the point.

Seems a ray casting to me. Varaibles x1, y1, x2, y2 are the polygon side's endpoints sorted with respect to X. The condition (xnew < xt) == (xt <= xold) tests whether the Y-parallel line from the point xt,yt meets the side. The other part of the condition tests if xt,yt is at the proper side of the polygon's side.
Condition
(yt-y1)*(x2-x1) < (y2-y1)*(xt-x1)
is equivalent to
(yt-y1)*(x2-x1) - (y2-y1)*(xt-x1) < 0
which is a matrix determinant
| yt-y1 xt-x1 |
| | < 0
| y2-y1 x2-x1 |
and the matrix is a vector cross product
(pointT - point1) times (point2 - point1)

Related

Solving linear equations

I have to find out the integral solution of a equation ax+by=c such that x>=0 and y>=0 and value of (x+y) is minimum.
I know if c%gcd(a,b)}==0 then it's always possible. How to find the values of x and y?
My approach
for(i 0 to 2*c):
x=i
y= (c-a*i)/b
if(y is integer)
ans = min(ans,x+y)
Is there any better way to do this ? Having better time complexity.
Using the Extended Euclidean Algorithm and the theory of linear Diophantine equations there is no need to search. Here is a Python 3 implementation:
def egcd(a,b):
s,t = 1,0 #coefficients to express current a in terms of original a,b
x,y = 0,1 #coefficients to express current b in terms of original a,b
q,r = divmod(a,b)
while(r > 0):
a,b = b,r
old_x, old_y = x,y
x,y = s - q*x, t - q*y
s,t = old_x, old_y
q,r = divmod(a,b)
return b, x ,y
def smallestSolution(a,b,c):
d,x,y = egcd(a,b)
if c%d != 0:
return "No integer solutions"
else:
u = a//d #integer division
v = b//d
w = c//d
x = w*x
y = w*y
k1 = -x//v if -x % v == 0 else 1 + -x//v #k1 = ceiling(-x/v)
x1 = x + k1*v # x + k1*v is solution with smallest x >= 0
y1 = y - k1*u
if y1 < 0:
return "No nonnegative integer solutions"
else:
k2 = y//u #floor division
x2 = x + k2*v #y-k2*u is solution with smallest y >= 0
y2 = y - k2*u
if x2 < 0 or x1+y1 < x2+y2:
return (x1,y1)
else:
return (x2,y2)
Typical run:
>>> smallestSolution(1001,2743,160485)
(111, 18)
The way it works: first use the extended Euclidean algorithm to find d = gcd(a,b) and one solution, (x,y). All other solutions are of the form (x+k*v,y-k*u) where u = a/d and v = b/d. Since x+y is linear, it has no critical points, hence is minimized in the first quadrant when either x is as small as possible or y is as small as possible. The k above is an arbitrary integer parameter. By appropriate use of floor and ceiling you can locate the integer points with either x as small as possible or y is as small as possible. Just take the one with the smallest sum.
On Edit: My original code used the Python function math.ceiling applied to -x/v. This is problematic for very large integers. I tweaked it so that the ceiling is computed with just int operations. It can now handle arbitrarily large numbers:
>>> a = 236317407839490590865554550063
>>> b = 127372335361192567404918884983
>>> c = 475864993503739844164597027155993229496457605245403456517677648564321
>>> smallestSolution(a,b,c)
(2013668810262278187384582192404963131387, 120334243940259443613787580180)
>>> x,y = _
>>> a*x+b*y
475864993503739844164597027155993229496457605245403456517677648564321
Most of the computation takes place in the running the extended Euclidean algorithm, which is known to be O(min(a,b)).
First let assume a,b,c>0 so:
a.x+b.y = c
x+y = min(xi+yi)
x,y >= 0
a,b,c > 0
------------------------
x = ( c - b.y )/a
y = ( c - a.x )/b
c - a.x >= 0
c - b.y >= 0
c >= b.y
c >= a.x
x <= c/x
y <= c/b
So naive O(n) solution is in C++ like this:
void compute0(int &x,int &y,int a,int b,int c) // naive
{
int xx,yy;
xx=-1; yy=-1;
for (y=0;;y++)
{
x = c - b*y;
if (x<0) break; // y out of range stop
if (x%a) continue; // non integer solution
x/=a; // remember minimal solution
if ((xx<0)||(x+y<=xx+yy)) { xx=x; yy=y; }
}
x=xx; y=yy;
}
if no solution found it returns -1,-1 If you think about the equation a bit then you should realize that min solution will be when x or y is minimal (which one depends on a<b condition) so adding such heuristics we can increase only the minimal coordinate until first solution found. This will speed up considerably the whole thing:
void compute1(int &x,int &y,int a,int b,int c)
{
if (a<=b){ for (x=0,y=c;y>=0;x++,y-=a) if (y%b==0) { y/=b; return; } }
else { for (y=0,x=c;x>=0;y++,x-=b) if (x%a==0) { x/=a; return; } }
x=-1; y=-1;
}
I measured this on my setup:
x y ax+by x+y a=50 b=105 c=500000000
[ 55.910 ms] 10 4761900 500000000 4761910 naive
[ 0.000 ms] 10 4761900 500000000 4761910 opt
x y ax+by x+y a=105 b=50 c=500000000
[ 99.214 ms] 4761900 10 500000000 4761910 naive
[ 0.000 ms] 4761900 10 500000000 4761910 opt
The ~2.0x difference for naive method times is due to a/b=~2.0and selecting worse coordinate to iterate in the second run.
Now just handle special cases when a,b,c are zero (to avoid division by zero)...

Implement Adaptive watershed segmentation in Matlab

I will like to implement "Adaptive Watershed Segmentation" in Matlab.
There are six steps in this algorithm. Input is figure(a) and result is figure(d).
Would you please to help me check is there any mistake in my code, and I don't know how to implement the sixth step.
Thank you so much!
Load image:
input_image = imread('test.gif');
Step 1 : Calculate D(x,y) at each (x,y), obtain the Euclidian distance map of the binary image and assign each value of M(x,y) as 0.
DT = bwdist(input_image,'euclidean'); % Trandform distance:Euclidian distance
[h,w]=size(DT);
M = zeros(h,w);
Step 2 : Smooth the distance map using Gaussian filter to merge the adjacent maxima, set M(x,y) as 1 if D(x,y) is a local maximum, and then obtain the marker map of the distance map.
H = fspecial('gaussian');
gfDT = imfilter(DT,H);
M = imregionalmax(gfDT); % maker map, M = local maximum of gfDT
Step3 : Scan the marker map pixel by pixel. If M(x0,y0) is 1, seek the spurious maxima in its neighbourhood with a radius of D(x ,y ).When M(x,y) equals 1 and sqr((x − x0)^2 + (y − y0)^2 ) ≤ D(x0, y0) , set M(x,y) as 0 if D(x,y) < D(x0,y0).
for x0 = 1:h
for y0 = 1:w
if M(x0,y0) == 1
r = ceil(gfDT(x0,y0));
% range begin:(x0-r,y0-r) end:(x0+r,y0+r)
xb = x0-r;
if xb <= 0
xb =1;
end
yb = y0-r;
if yb <= 0
yb =1;
end
xe = x0+r;
if xe > w
xe = w;
end
ye = y0+r;
if ye > h
ye = h;
end
for x = yb:ye
for y = xb:xe
if M(x,y)==1
Pos = [x0,y0 ;x,y];
Dis = pdist(Pos,'euclidean');
IFA = Dis<= (gfDT(x0,y0));
IFB = gfDT(x,y)<gfDT(x0,y0);
if ( IFA && IFB)
M(x,y) = 0;
end
end
end
end
end
end
end
Step 4:
Calculate the inverse of the distance map,and the local maxima turn out to be the local minima.
igfDT = -(gfDT);
STep5:
Segment the distance map according to the markers by the conventional watershed algorithm and obtain the segmentation of binary image.
I2 = imimposemin(igfDT,M);
L = watershed(I2);
igfDT (L==0)=0;
Step 6 : Straighten the watershed lines by linking the ends of the watershed lines with a straight line and reclassifying the pixels along the straight line.
I don't know how to implement this step
Try distance transform and then watershed transform.
im=imread('n6BRI.gif');
imb=bwdist(im);
sigma=3;
kernel = fspecial('gaussian',4*sigma+1,sigma);
im2=imfilter(imb,kernel,'symmetric');
L = watershed(max(im2(:))-im2);
[x,y]=find(L==0);
lblImg = bwlabel(L&~im);
figure,imshow(label2rgb(lblImg,'jet','k','shuffle'));

How to compute the intersection between a quadratic bezier curve and a horizontal line?

What I am trying to do get the X coordinates at which a certain bezier curve crosses a horizontal line (a y coordinate). For the moment, I have this code:
function self.getX(y)
if y > maxY or y < minY then
return
end
local a = y1 - y
if a == 0 then
return
end
local b = 2*(y2 - y1)
local c = (y3 - 2*y2 + y1)
local discriminant = (b^2 - 4*a*c )
if discriminant < 0 then
return
else
local aByTwo = 2*a
if discriminant == 0 then
local index1 = -b/aByTwo
if 0 < index1 and index1 < 1 then
return (1-index1)^2*x1+2*(1-index1)*index1*x2+index1^2*x3
end
else
local theSQRT = math.sqrt(discriminant)
local index1, index2 = (-b -theSQRT)/aByTwo, (-b +theSQRT)/aByTwo
if 0 < index1 and index1 < 1 then
if 0 < index2 and index2 < 1 then
return (1-index1)^2*x1+2*(1-index1)*index1*x2+index1^2*x3, (1-index2)^2*x1+2*(1-index2)*index2*x2+index2^2*x3
else
return (1-index1)^2*x1+2*(1-index1)*index1*x2+index1^2*x3
end
elseif 0 < index2 and index2 < 1 then
return (1-index2)^2*x1+2*(1-index2)*index2*x2+index2^2*x3
end
end
end
end
A few specifications:
This is Lua code.
local means the variable is local to the chunk of code, so it does not affect the code's functionality.
y1, y2, and y3 are the y coordinate of the 3 points. The same applies to x1, x2, x3.
y is the y coordinate of the horizontal line I am computing.
maxY is the biggest of the 3 y's.
minY is the smallest.
For the moment this code gives me this:
There are 8 bezier curves
The green ones are generated using the normal method: (1-t)^2*x1+2*(1-t)*t*x2+t^2*x3
The red dots are the control points.
The white lines are what is generated using the method described with the code above.
The straight lines are lines, ignore them.
There should be 8 curves, but only 4 are rendered.
Thanks in advance,
Creator!
The Bézier curve has
y(t)=(1-t)^2*y1+2(1-t)*t*y2+t^2*y
which expands to
(y1-2*y2+y3)*t^2+2(y2-y1)*t+y1
You have swapped a and c in the quadratic equation a*t^2+b*t+c=0 required for solving y(t)=y.

Can this operation be vectorized in Octave?

I have a matrix A and B. I want to take the sum of squares errors between them ss = sum(sum( (A-B).^2 )), but I only want to do so if NEITHER matrix elements are identically zero. For now, I am going through each matrix as follows:
for i = 1:N
for j = 1:M
if( A(i,j) == 0 )
B(i,j) = 0;
elseif( B(i,j) == 0 )
A(i,j) = 0;
end
end
end
and then taking the sum of squares after that. Is there a way to vectorize the comparison and reassigning of values?
If you were just trying to achieve what the listed code is doing, but in a vectorized fashion, you can use this approach -
%// Create mask to set elements in both A and B to zeros
mask = A==0 | B==0
%// Set A and B to zeros at places where mask has TRUE values
A(mask) = 0
B(mask) = 0
If the bigger context of finding the sum of squares errors after the listed code could be considered, you can do so with this -
df = A - B;
df(A==0 | B==0) = 0;
ss_vectorized = sum(df(:).^2);
Or as #carandraug commented, you can use the built-in sumsq for the sum of squares calculation at the last step -
ss_vectorized = sumsq(df(:));

Fast computation of warp matrices

For a fixed and given tform, the imwarp command in the Image Processing Toolbox
B = imwarp(A,tform)
is linear with respect to A, meaning there exists some sparse matrix W, depending on tform but independent of A, such that the above can be equivalently implemented
B(:)=W*A(:)
for all A of fixed known dimensions [n,n]. My question is whether there are fast/efficient options for computing W. The matrix form is necessary when I need the transpose operation W.'*B(:), or if I need to do W\B(:) or similar linear algebraic things which I can't do directly through imwarp alone.
I know that it is possible to compute W column-by-column by doing
E=zeros(n);
W=spalloc(n^2,n^2,4*n^2);
for i=1:n^2
E(i)=1;
tmp=imwarp(E,tform);
E(i)=0;
W(:,i)=tmp(:);
end
but this is brute force and slow.
The routine FUNC2MAT is somewhat more optimal in that it uses the loop to compute/gather the sparse entry data I,J,S of each column W(:,i). Then, after the loop, it uses this to construct the overall sparse matrix. It also offers the option of using a PARFOR loop. However, this is still slower than I would like.
Can anyone suggest more speed-optimal alternatives?
EDIT:
For those uncomfortable with my claim that imwarp(A,tform) is linear w.r.t. A, I include the demo script below, which tests that the superposition property is satisfied for random input images and tform data. It can be run repeatedly to see that the nonlinearityError is always small, and easily attributable to floating point noise.
tform=affine2d(rand(3,2));
%tform=projective2d(rand(3));
fun=#(A) imwarp(A,tform,'cubic');
I1=rand(100); I2=rand(100);
c1=rand; c2=rand;
LHS=fun(c1*I1+c2*I2); %left hand side
RHS=c1*fun(I1)+c2*fun(I2); %right hand side
linearityError = norm(LHS(:)-RHS(:),'inf')
That's actually pretty simple:
W = sparse(B(:)/A(:));
Note that W is not unique, but this operation probably produces the most sparse result. Another way to calculate it would be
W = sparse( B(:) * pinv(A(:)) );
but that results in a much less sparse (yet still valid) result.
I constructed the warping matrix using the optical flow fields [u,v] and it is working well for my application
% this function computes the warping matrix
% M x N is the size of the image
function [ Fw ] = generateFwi( u,v,M,N )
Fw = zeros(M*N, M*N);
k =1;
for i=1:M
for j= 1:N
newcoord(1) = i+u(i,j);
newcoord(2) = j+v(i,j);
newi = newcoord(1);
newj = newcoord(2);
if newi >0 && newj >0
newi1x = floor(newi);
newi1y = floor(newj);
newi2x = floor(newi);
newi2y = ceil(newj);
newi3x = ceil(newi); % four nearest points to the given point
newi3y = floor(newj);
newi4x = ceil(newi);
newi4y = ceil(newj);
x1 = [newi,newj;newi1x,newi1y];
x2 = [newi,newj;newi2x,newi2y];
x3 = [newi,newj;newi3x,newi3y];
x4 = [newi,newj;newi4x,newi4y];
w1 = pdist(x1,'euclidean');
w2 = pdist(x2,'euclidean');
w3 = pdist(x3,'euclidean');
w4 = pdist(x4,'euclidean');
if ceil(newi) == floor(newi) && ceil(newj)==floor(newj) % both the new coordinates are integers
Fw(k,(newi1x-1)*N+newi1y) = 1;
else if ceil(newi) == floor(newi) % one of the new coordinates is an integer
w = w1+w2;
w1new = w1/w;
w2new = w2/w;
W = w1new*w2new;
y1coord = (newi1x-1)*N+newi1y;
y2coord = (newi2x-1)*N+newi2y;
if y1coord <= M*N && y2coord <=M*N
Fw(k,y1coord) = W/w2new;
Fw(k,y2coord) = W/w1new;
end
else if ceil(newj) == floor(newj) % one of the new coordinates is an integer
w = w1+w3;
w1 = w1/w;
w3 = w3/w;
W = w1*w3;
y1coord = (newi1x-1)*N+newi1y;
y2coord = (newi3x-1)*N+newi3y;
if y1coord <= M*N && y2coord <=M*N
Fw(k,y1coord) = W/w3;
Fw(k,y2coord) = W/w1;
end
else % both the new coordinates are not integers
w = w1+w2+w3+w4;
w1 = w1/w;
w2 = w2/w;
w3 = w3/w;
w4 = w4/w;
W = w1*w2*w3 + w2*w3*w4 + w3*w4*w1 + w4*w1*w2;
y1coord = (newi1x-1)*N+newi1y;
y2coord = (newi2x-1)*N+newi2y;
y3coord = (newi3x-1)*N+newi3y;
y4coord = (newi4x-1)*N+newi4y;
if y1coord <= M*N && y2coord <= M*N && y3coord <= M*N && y4coord <= M*N
Fw(k,y1coord) = w2*w3*w4/W;
Fw(k,y2coord) = w3*w4*w1/W;
Fw(k,y3coord) = w4*w1*w2/W;
Fw(k,y4coord) = w1*w2*w3/W;
end
end
end
end
else
Fw(k,k) = 1;
end
k=k+1;
end
end
end

Resources