Ask Your Question

Revision history [back]

Hi @Sayali!

If you want to compare a known shape with an imperfect one then hausdorff distance is the key for your problem. Here is the source code for calculating the Hausdorff distance.

Perform the following steps:

Training Stage:

Crop the Desired object with its bounding Rectangle & save this as Template Image.

Test Image

  1. Load Scene Image
  2. Load Template Image
  3. Create a Temp Image of Size equivalent to Scene image Size.
  4. Find Contours in scene image & Find the Bounding box.
  5. Set the Temp Image ROI to the Current Bounding Box Region.
  6. Copy the Template image into the Temp image.
  7. Find Contours of Template Image
  8. Now compare the Hausdorff distance of the two Objects by using this code snippet.

You can also refer this post

int distance_2( const std::vector<cv::Point> & a, const std::vector<cv::Point>  & b )
{
    int maxDistAB = 0;
    for (size_t i=0; i<a.size(); i++)
    {
        int minB = 1000000;
        for (size_t j=0; j<b.size(); j++)
        {
            int dx = (a[i].x - b[j].x);     
            int dy = (a[i].y - b[j].y);     
            int tmpDist = dx*dx + dy*dy;

            if (tmpDist < minB)
            {
                minB = tmpDist;
            }
            if ( tmpDist == 0 )
            {
                break; // can't get better than equal.
            }
        }
        maxDistAB += minB;
    }
    return maxDistAB;
}

double distance_hausdorff( const std::vector<cv::Point> & a, const std::vector<cv::Point> & b )
{
    int maxDistAB = distance_2( a, b );
    int maxDistBA = distance_2( b, a );   
    int maxDist = std::max(maxDistAB,maxDistBA);

    return std::sqrt((double)maxDist);
}