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**

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

```
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);
}
```