Gradient | Morphological Transformations in OpenCV in C++
Last Updated :
10 Feb, 2021
In this article, a Morphological Operator called Gradient is discussed. The gradient is defined as the difference between the Dilation and Erosion of an image. Every pixel inside the Gradient image represents the contrast intensity in the neighborhood of a pixel. It is used for image segmentation and edge detection. It is of two types:
- Internal Gradient: It enhances the internal boundaries of objects brighter than the background and for binary image generates a mask of the internal boundaries of the foreground image object.
- External Gradient: It enhances the external boundaries of objects darker than their background.
Syntax:
morphologyEx (src, dst, op, kernel, anchor, iterations, borderType, borderValue)
Parameters:
- src: It is the input image.
- dst: It is the output image.
- op: Type of morphological operation.
- kernel: Structuring element used for Closing.
- anchor: Anchor position inside the structuring element. The default value is [-1, -1} signifying position as the center of the structuring element.
- iterations: Number of times Closing is applied.
- borderType: Type of border ( BORDER_CONSTANT, BORDER_REPLICATE, etc.)
- borderValue: Border value
- Return: Output Image (Mat Object)
Gradient operator is given the expression:
Below is the C++ program to demonstrate the Gradient Morphological Operation:
C++
#include <iostream>
#include <opencv2/core/core.hpp>
#include <opencv2/highgui/highgui.hpp>
#include <opencv2/imgproc.hpp>
using namespace cv;
using namespace std;
int main( int argc, char ** argv)
{
Mat image = imread(
"C:/Users/harsh/Downloads/opencv/sources/samples/data/gfglogo.jpg" ,
IMREAD_GRAYSCALE);
if (!image.data) {
cout << "Could not open or "
<< "find the image" << '\n' ;
return 0;
}
int morph_size = 2;
Mat element = getStructuringElement(
MORPH_RECT,
Size(2 * morph_size + 1,
2 * morph_size + 1),
Point(morph_size,
morph_size));
Mat output;
morphologyEx(image, output,
MORPH_GRADIENT, element,
Point(-1, -1), 1);
imshow( "Source" , image);
imshow( "Gradient" , output);
waitKey();
return 0;
}
|
Output:
Like Article
Suggest improvement
Share your thoughts in the comments
Please Login to comment...