public bool CheckIfPointsFitShape( List<IntPoint> edgePoints, List<IntPoint> corners )
{
int cornersCount = corners.Count;
// lines coefficients (for representation as y(x)=k*x+b)
float[] k = new float[cornersCount];
float[] b = new float[cornersCount];
float[] div = new float[cornersCount]; // precalculated divisor
bool[] isVert = new bool[cornersCount];
for ( int i = 0; i < cornersCount; i++ )
{
IntPoint currentPoint = corners[i];
IntPoint nextPoint = ( i + 1 == cornersCount ) ? corners[0] : corners[i + 1];
if ( !( isVert[i] = nextPoint.X == currentPoint.X ) )
{
k[i] = (float) ( nextPoint.Y - currentPoint.Y ) / ( nextPoint.X - currentPoint.X );
b[i] = currentPoint.Y - k[i] * currentPoint.X;
div[i] = (float) Math.Sqrt( k[i] * k[i] + 1 );
}
}
// calculate distances between edge points and polygon sides
float meanDistance = 0;
for ( int i = 0, n = edgePoints.Count; i < n; i++ )
{
float minDistance = float.MaxValue;
for ( int j = 0; j < cornersCount; j++ )
{
float distance = 0;
if ( !isVert[j] )
{
distance = (float) Math.Abs( ( k[j] * edgePoints[i].X + b[j] - edgePoints[i].Y ) / div[j] );
}
else
{
distance = Math.Abs( edgePoints[i].X - corners[j].X );
}
if ( distance < minDistance )
minDistance = distance;
}
meanDistance += minDistance;
}
meanDistance /= edgePoints.Count;
// get bounding rectangle of the corners list
IntPoint minXY, maxXY;
PointsCloud.GetBoundingRectangle( corners, out minXY, out maxXY );
IntPoint rectSize = maxXY - minXY;
float maxDitance = Math.Max( minAcceptableDistortion,
( (float) rectSize.X + rectSize.Y ) / 2 * relativeDistortionLimit );
return ( meanDistance <= maxDitance );
}