Rate This Document
Findability
Accuracy
Completeness
Readability

morphologyEx

Usage

Performs advanced morphological transformations, such as opening, closing, gradient, top-hat, and black-hat operations, using erosion and dilation as basic operations. It is widely used in noise removal, edge detection, and structure extraction in image processing.

Interface

1
void morphologyEx(InputArray src, OutputArray dst, int op, InputArray kernel, Point anchor = Point(-1, -1), int iterations = 1, int borderType = BORDER_CONSTANT, const Scalar& borderValue = morphologyDefaultBorderValue());

Parameters

Parameter

Description

Value Range

Input/Output

src

Input image.

Not null

Input

dst

Output image.

Mat class

Input

op

Morphological operation type.

  • MORPH_OPEN
  • MORPH_CLOSE
  • MORPH_GRADIENT
  • MORPH_TOPHAT
  • MORPH_BLACKHAT

Input

kernel

Morphological kernel.

Not null

Input

anchor

Anchor position.

(-1, -1) by default, indicating the kernel center

Input

iterations

Number of iterations.

(1, inf)

Input

borderType

Border type.

  • BORDER_CONSTANT
  • BORDER_REPLICATE
  • BORDER_REFLECT, etc.

Input

borderValue

Constant value used to fill the border (valid only for a constant border).

(-inf, inf)

Input

Example

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
#include <opencv2/opencv.hpp>
#include <iostream>

using namespace cv;

int main() {
    // Read the image.
    Mat src = imread("input.jpg", IMREAD_GRAYSCALE);
    if (src.empty()) {
        std::cerr << "Failed to load the image!" << std::endl;
        return -1;
    }

    // Define the morphological kernel.
    Mat kernel = getStructuringElement(MORPH_RECT, Size(5, 5));

    // Perform opening (erosion and then dilation).
    Mat dst;
    morphologyEx(src, dst, MORPH_OPEN, kernel);

    // Display the result.
    imshow("Original image", src);
    imshow("Image after processing", dst);
    waitKey(0);

    return 0;
}