OpenCV matchTemplate threshold values for differen

2020-07-23 08:55发布

问题:

I searched a lot for finding the threshold values for the below mention methods.

methods = ['cv2.TM_CCOEFF', 'cv2.TM_CCOEFF_NORMED', 'cv2.TM_CCORR',
            'cv2.TM_CCORR_NORMED', 'cv2.TM_SQDIFF', cv2.TM_SQDIFF_NORMED']

I also tried to figure them out by myself but I could only find thresholds for 3 methods which have max value of 1.0. The other methods values were in range of 10^5. I would like to know the bounds of these methods.

Can somebody point me in the right direction. My agenda is to loop through all the methods for template matching and get the best outcome.I went through the documentation and source code, but no luck.

These are the values I got , I could understand that *NORMED methods have values 0-1.

cv2.TM_CCOEFF -- 25349100.0
cv2.TM_CCOEFF_NORMED -- 0.31208357214927673
cv2.TM_CCORR -- 616707328.0
cv2.TM_CCORR_NORMED -- 0.9031367897987366
cv2.TM_SQDIFF -- 405656000.0
cv2.TM_SQDIFF_NORMED -- 0.737377941608429

回答1:

As described in opencv documentation matchTemplate result is a sum of differences (varies with method) for each pixel, so for not normalized methods - thresholds would vary with size of template.

You can see formulas for each method and calculate thresholds for your template type considering that max difference between pixels is 255 for CV_8UC1 image.

So lets say you have 2 grayscale images and smallest one is 10x10.
In that case for TM_SQDIFF minimum distance would be 10x10x0^2=0 (images are identical) and maximum would be 10x10x255^2=6502500 (one image is completely black and other is white), which results in [0, 6502500] boundaries.

Of course it is possible to calculate that for the undefined sizes [A, B].

For TM_CCORR it would be AxBxmax(T(x',y')I(x+x',y+y')) = 65025AB

You can go on and calculate that for remaining methods, remember that if you have different from CV_8UC image types (like 32FC or 32SC) - you would need to replace 255 with corresponding values (max(float) max(int32))