Template Matching with evaluation

In this sample you will perform Template Matching in order to find a component on a printed circuit board. For this purpose, use:

Application

Remember to add both the input image and the template image to the respective File Source. Via the threshold value fMatchThreshold you can set a limit as to how good a match must be in order to be accepted.

Program

Important in this sample is that you require a template image in addition to the normal input image in order to search for occurrences of the template in the input image.

Template Matching with evaluation 1:

If both images are available, perform the template matching automatically with the function F_VN_MatchTemplateAndEvaluate.

hr := F_VN_MatchTemplateAndEvaluate(ipImageIn, ipImageTemplate, ipMatches, fMatchThreshold, hr);

The matches found whose degree of correlation is higher than the specified threshold value fMatchThreshold are now located as points in the container ipMatches. Each point specifies the top left corner of each occurrence of ipImageTemplate in ipImageIn.

In principle you are now done with the Template Matching. By way of example, access the individual matches in the following in order to paint them into the image. For this purpose, use the construct for accessing container elements as explained in the section Container.

hr := F_VN_GetImageHeight(ipImageTemplate, nHeight, hr);
hr := F_VN_GetImageWidth(ipImageTemplate, nWidth, hr);
hr := F_VN_GetAt_TcVnPoint2_DINT(ipMatches, aPosition, 0, hr);
hr := F_VN_GetForwardIterator(ipMatches, ipIterator, hr);
IF SUCCEEDED(hr) AND ipIterator <> 0 THEN
    hr := ipIterator.TcQueryInterface(IID_ITcVnAccess_TcVnPoint2_DINT, ADR(ipAccess));
    IF SUCCEEDED(hr) AND ipAccess <> 0 THEN
        WHILE SUCCEEDED(hr) AND ipIterator.CheckIfEnd() <> S_OK DO
            hr := ipAccess.Get(aPosition);
            hr := F_VN_DrawRectangle(
                DINT_TO_UDINT(aPosition[0]),
                DINT_TO_UDINT(aPosition[1]),
                DINT_TO_UDINT(aPosition[0])+nWidth,
                DINT_TO_UDINT(aPosition[1])+nHeight,
                ipImageRes,
                aGreen,
                5,
                hr
            );
            hr := F_VN_IncrementIterator(ipIterator, hr);
        END_WHILE
    END_IF
END_IF

Notice

Long execution duration

Depending on the size of the input and template image, the performance of the Template Matching 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!

Original image

Result image

Template Matching with evaluation 2:

Template Matching with evaluation 3: