nervousDev
nervousDev

Reputation: 72

Check if a matrix contains another matrix

I'm trying to find pattern in a image (the type of image is not important).

In my code, the image is an array where any pixel is given by:

(x * y.length + y)

At the moment I can't get the code to work because almost everytime it finds 0 occurrences..

So here it's current code:

int search_pattern(PPMImage * img, PPMImage * patt)
{
    int cont = 0, i, j, k, p, tmp;

    //iterate image
    for(i=0; i <= (img->x - patt->x); i++)
    {
        for(j=0; j <= (img->y - patt->y); j++)
        {
            tmp = 0;
            //iterate pattern
            for(k = 0; k  < patt->x; k++)
            {
                for(p = 0; p < patt->y; p++)
                {
                    PPMPixel * image_pixel = getPixelPPM(i + k, j + p, img);
                    PPMPixel * pattern_pixel = getPixelPPM(k, p, patt);
                    tmp += cmp_pixel(image_pixel, pattern_pixel);
                }
            }
            if(tmp == (patt->x * patt->y))                  
                cont++;
        }
    }

    return cont;
}

I know the error is in the iteration itself because everything else is correct.

Info:

...->x is the x length of the image
getPixelPPM  returns the pixel in the given place
cmp_pixel returns 1 if the 2 pixels are equal (not important how) and 0 if not

More strange is that if I try using the pattern image as both of the images, I get 1 occurrence but if I try with a valid image I get 0. Again, I'm 100% sure that external factors aren't the error.

Thank you.

Upvotes: 0

Views: 463

Answers (1)

Huan-Yu Tseng
Huan-Yu Tseng

Reputation: 566

I have tried your code, and I think the problem is the image type.

For example, the image type JPGE is a lossy compression. Even after you cropping one part of the source image into the pattern image, the pixels at the same position will probably not have exactly the same value.

I tried two image types: JPGE and BMP. I got the result 0 from JPGE, and result 1 from BMP. In these two cases, I used the same image sample as source image (but different image type) and cropped one part of the source images into the pattern images.

The result showed that you could not match the pattern image to the valid image, but could match the pattern image to itself might be caused by the image type, which let the pattern image and valid image have image distortion and become not totally the same in the area considered should be the same.

Hope it helps.

Upvotes: 1

Related Questions