Get absolute difference from a picture and template. [Template matching]

59 views Asked by At

I have the two methods which should write pixel values of the absolute difference of a template and the same size patch from the original picture into the pixel where both patch and template coordinates are 0,0.

Here are my 2 methods.

private void normalizeAndDraw(double biggest, double[] temporaryPixels, int[] dstPixels  ){
         double normalize = 255 / biggest;
            for (int c = 0; c < temporaryPixels.length; c++) {
            int value = (int) (temporaryPixels[c] * normalize);
            dstPixels[c] = 0xFF000000 | (value << 16) | (value << 8) | value;
        }
    }

    private void getAbsolutePicture(int srcPixels[], int srcWidth, int srcHeight, int dstPixels[], int dstWidth, int dstHeight, int templatePixels[], int tmpHeight, int tmpWidth) {
        double temporaryPixels[] = new double[dstHeight * dstWidth];
        double biggest = 0;

        double sumR = 0;
        for (int j = 0; j < tmpHeight; j++) {
            for (int i = 0; i < tmpWidth; i++) {

                int posTmp = j * tmpWidth + i;
                sumR += templatePixels[posTmp] & 0xFF;
            }
        }

        for (int y = 0; y < dstHeight; y++) {
            for (int x = 0; x < dstWidth; x++) {
                double sumI = 0;
                for (int j = 0; j < tmpHeight; j++) {
                    for (int i = 0; i < tmpWidth; i++) {
                        int pos = (y + j) * dstWidth + (x + i);
                        sumI += srcPixels[pos] & 0xFF;
                    }
                }
                double absDifference = Math.abs(sumI - sumR);

                biggest = Math.max(absDifference, biggest);

                temporaryPixels[y * dstWidth + x] = absDifference;
            }
        }

         normalizeAndDraw(biggest, temporaryPixels, dstPixels);

    }

They get called like this.

getAbsolutePicture(srcPixels, srcWidth, srcHeight, dstPixels, dstWidth, dstHeight, templatePixels, templateWidth, templateHeight);

If values are written into the dstPixels array they will automatically be displayed.

Unfortunately instead of the correct solution which looks like this

https://i.stack.imgur.com/cqlD3.png

I get a result which looks like this

https://i.stack.imgur.com/2Cjhz.png

I am pretty sure that my error lies in the calculation of sumR and sumI but I just cant figure it out?

What exactly is wrong in my code?

1

There are 1 answers

0
b-m-f On BEST ANSWER

My code was actually okay. The biggest problem was that when I called getAbsolutePicture() I mixed up tmpWdith and tmpHeight.