Skip to content
Related Articles

Related Articles

Gradient | Morphological Transformations in OpenCV in C++

Improve Article
Save Article
  • Last Updated : 10 Feb, 2021
Improve Article
Save Article

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.


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


  • 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:

{\displaystyle G(f)=f\oplus b-f\ominus b}

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(
    // Check if the image is created
    // successfully or not
    if (! {
        cout << "Could not open or "
             << "find the image" << '\n';
        return 0;
    // Create a structuring element
    int morph_size = 2;
    Mat element = getStructuringElement(
        Size(2 * morph_size + 1,
             2 * morph_size + 1),
    Mat output;
    // Gradient
    morphologyEx(image, output,
                 MORPH_GRADIENT, element,
                 Point(-1, -1), 1);
    // Display the image
    imshow("Source", image);
    imshow("Gradient", output);
    return 0;


My Personal Notes arrow_drop_up
Related Articles

Start Your Coding Journey Now!