<< filter2D | Image filtering | threshold >>

scicv >> Image filtering > morphologyEx

# morphologyEx

Applies a morphological filter on an image

### Syntax

    img_out = morphologyEx(img_in, op, element[, anchor[, iterations[, borderType[, borderValue]]]])

### Parameters

img_in

  Input image (Mat).

op

  Type of morphological operation:

  - MORPH_OPEN: opening operation.
  - MORPH_CLOSE: closing operation.
  - MORPH_GRADIENT: morphological gradient.
  - MORPH_TOPHAT: top hat.
  - MORPH_BLACKHAT: black hat.
  - MORPH_HITORMISS: hit or miss.
element

  Structuring element used for filtering (double matrix or Mat) (default 3x3 matrix).

anchor

  Position of the anchor in the element (double 1x2 matrix) (default the anchor is at the element center).

iterations

  number of times dilation/erosion is applied (double).

borderType

  Pixel extrapolation method (double) (default `BORDER_DEFAULT`).

borderValue

  Border value (double matrix 1xn n=1..4).

img_out

  Output image (Mat).

### Description

`morphologyEx` performs a specified morphological filter on the image.:

The available morphological filters can be summarized like this:

- Opening: `open(img) = dilate(erode(img))`.
- Closing: `close(img) = erode(dilate(img))`.
- Gradient: `gradient(img) = dilate(img) - erode(img)`.
- Top hat: `top_hat(img) = img - open(image)`.
- Black cat: `black_hat = close(img) - img`.

### Examples

    scicv_Init();

    // Remove noise with an opening filter
    img = imread(getSampleImage("noise.png"), CV_LOAD_IMAGE_GRAYSCALE);

    subplot(1,2,1);
    matplot(img);

    // convert to black/white and reverse, image information is white pixels (value 1) but we want to filter black pixels (value 0)
    [res, img_bw] = threshold(img, 128, 255, THRESH_BINARY_INV);

    element = getStructuringElement(MORPH_RECT, [5 5]);
    img_open = morphologyEx(img_bw, MORPH_OPEN, element);

    // we need to reverse again before display
    img_open_reverse = bitwise_not(img_open);

    subplot(1,2,2);
    matplot(img_open_reverse);

    delete_Mat(img);
    delete_Mat(img_bw);
    delete_Mat(element);
    delete_Mat(img_open);
    delete_Mat(img_open_reverse);

### See also

- dilate
- erode

Report an issue
<< filter2D | Image filtering | threshold >>