Drawing the boundary

We achieve this using a morphological gradient. This is the operation that draws the boundary around a shape by taking the difference between the dilation and erosion of an image:

Let's look at the function to perform morphological gradient:

Mat performMorphologicalGradient(Mat inputImage, int morphologyElement, int morphologySize)
{
Mat outputImage, tempImage1, tempImage2;
int morphologyType;

if(morphologyElement == 0)
morphologyType = MORPH_RECT;
else if(morphologyElement == 1)
morphologyType = MORPH_CROSS;
else if(morphologyElement == 2)
morphologyType = MORPH_ELLIPSE;

// Create the structuring element for erosion
Mat element = getStructuringElement(morphologyType, Size(2*morphologySize + 1, 2*morphologySize + 1), Point(morphologySize, morphologySize));

// Apply morphological gradient to the image using the structuring element
dilate(inputImage, tempImage1, element);
erode(inputImage, tempImage2, element);

// Return the output image
return tempImage1 - tempImage2;
}