Morphological operators

In this sample you apply morphological operators to an image. For this you use:

Explanation

Objects in an image can be changed according to certain rules with a morphological operator. Morphological operators are mostly applied to binary images; however, application to grayscale images is generally also possible. Through combined operators such as OPENING and CLOSING it is possible, for example, to supplement missing parts in objects and small outliers can be removed.

Variables

ipElement   :  ITcVnImage; 
eSEShape    :  ETcVnStructuringElementShape := TCVN_SES_RECTANGLE;
aSESize     :  ARRAY [0..1] OF UDINT := [29, 29];
eOperator   :  ETcVnMorphologicalOperator := TCVN_MO_OPENING;

Program

A morphological operator requires a structure element in order to define its area of influence for each pixel. For this purpose you can select various shapes from the enum ETcVnStructuringElementShape and in different sizes.

hr := F_VN_CreateStructuringElement(
    ipStructuringElement    :=  ipElement,
    eShape                  :=  eSEShape,
    nWidth                  :=  aSESize[0],
    nHeight                 :=  aSESize[1],
    hrPrev                  :=  hr);

You then define a morphological operation by means of the enum ETcVnMorphologicalOperator and apply it with the structure element created to the input image.

hr := F_VN_MorphologicalOperator(
    ipSrcImage              :=  ipImageIn,
    ipDestImage             :=  ipImageRes,
    eOperator               :=  eOperator,
    ipStructuringElement    :=  ipElement,
    hrPrev                  :=  hr);

A morphological opening with a rectangular structure element of the size [31; 31] and previous threshold value, for example, produces the following result. It removes smaller or narrower objects from the image.

Input image

Result image

Morphological operators 1:

Morphological operators 2:

Notice

Long execution duration

Depending on the size of the input image and of the structure element, the execution of the morphological operator can take a very long time in comparison with other functions. Make sure that you set the cycle time accordingly and use a watchdog if necessary!