Search code examples
c#emgucvsurfmatchtemplate

emgu finding image a in image b


I'm new to emgu and would like some advice on where to start.

I've looked through the shape detection but its far too complex for what i need .. i think.. and my surfexample isn't working. I get this error:

Cannot get SURF example in EMGU.CV to work?

Anyway, this is what i would like to do: Find image A in image B. Image A is a simple square which always has the same grey 1 pixel border and always the same size (i believe) but the inner colour could be black or one of about 7 other colours (only ever a solid colour). i need to find the coordinates of image A in image b when i press a button. see the below images.

Image B

image b

And

Image A

image a


Solution

  • Goosebumps answer is correct, but I thought that a bit of code might be helpful also. This is my code using MatchTemplate to detect a template (image A) inside a source image (image B). As Goosebumps noted, you probably want to include some grey around the template.

    Image<Bgr, byte> source = new Image<Bgr, byte>(filepathB); // Image B
    Image<Bgr, byte> template = new Image<Bgr, byte>(filepathA); // Image A
    Image<Bgr, byte> imageToShow = source.Copy();
    
    using (Image<Gray, float> result = source.MatchTemplate(template, Emgu.CV.CvEnum.TM_TYPE.CV_TM_CCOEFF_NORMED))
    {
        double[] minValues, maxValues;
        Point[] minLocations, maxLocations;
        result.MinMax(out minValues, out maxValues, out minLocations, out maxLocations);
    
        // You can try different values of the threshold. I guess somewhere between 0.75 and 0.95 would be good.
        if (maxValues[0] > 0.9)
        {
            // This is a match. Do something with it, for example draw a rectangle around it.
            Rectangle match = new Rectangle(maxLocations[0], template.Size);
            imageToShow.Draw(match, new Bgr(Color.Red), 3);
        }
    }
    
    // Show imageToShow in an ImageBox (here assumed to be called imageBox1)
    imageBox1.Image = imageToShow;