Open In App

Gradient | Morphological Transformations in OpenCV in C++

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:

Syntax:



morphologyEx (src, dst, op, kernel, anchor, iterations, borderType, borderValue)

Parameters:

Gradient operator is given the expression:



Below is the C++ program to demonstrate the Gradient Morphological Operation:

// C++ program to demonstrate the
// above approach
#include <iostream>
#include <opencv2/core/core.hpp>
  
// Include this library
// for drawing shapes
#include <opencv2/highgui/highgui.hpp>
#include <opencv2/imgproc.hpp>
using namespace cv;
using namespace std;
  
// Driver Code
int main(int argc, char** argv)
{
    // Reading the Image
    Mat image = imread(
        "C:/Users/harsh/Downloads/opencv/sources/samples/data/gfglogo.jpg",
        IMREAD_GRAYSCALE);
  
    // Check if the image is created
    // successfully or not
    if (!image.data) {
        cout << "Could not open or "
             << "find the image" << '\n';
        return 0;
    }
  
    // Create a structuring element
    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;
  
    // Gradient
    morphologyEx(image, output,
                 MORPH_GRADIENT, element,
                 Point(-1, -1), 1);
  
    // Display the image
    imshow("Source", image);
    imshow("Gradient", output);
    waitKey();
  
    return 0;
}

                    
Output:

Article Tags :