Unsupported Pixel Format of source or template image. AForge Imaging

Charlie picture Charlie · Nov 17, 2014 · Viewed 9.2k times · Source

I am getting the following Exception at ProcessImage(bitmap1, bitmap2);

Unsupported Pixel Format of source or template image

and this is my code:

public static double FindComparisonRatioBetweenImages(
    System.Drawing.Image one, System.Drawing.Image two)
{
    Bitmap bitmap1 = new Bitmap(one);
    Bitmap bitmap2 = new Bitmap(two);

    ExhaustiveTemplateMatching tm = new ExhaustiveTemplateMatching(0);
    TemplateMatch[] matchings = null;

    matchings = tm.ProcessImage(bitmap1, bitmap2); // Exception occurs here!

    return matchings[0].Similarity;
}

I have also passed managedImage from the below code into the method, but it still gives error:

UnmanagedImage unmanagedImageA = UnmanagedImage.FromManagedImage(bitmap1);
Bitmap managedImageA = unmanagedImageA.ToManagedImage();
UnmanagedImage unmanagedImageB = UnmanagedImage.FromManagedImage(bitmap2);
Bitmap managedImageB = unmanagedImageB.ToManagedImage();
  1. I have passed Images randomly from my computer, they all give exception.
  2. I have passed Blank Image edited in paint into the method,it still give exception.
  3. Also checked, jpeg, png, bmp formats, nothing work.

Answer

dbc picture dbc · Nov 17, 2014

Try ExhaustiveTemplateMatching:

The class implements exhaustive template matching algorithm, which performs complete scan of source image, comparing each pixel with corresponding pixel of template.

The class processes only grayscale 8 bpp and color 24 bpp images.

So, those are the image formats you must use.

As requested, to convert to a specific pixel format, you can do this:

public static Bitmap ConvertToFormat(this Image image, PixelFormat format)
{
    Bitmap copy = new Bitmap(image.Width, image.Height, format);
    using (Graphics gr = Graphics.FromImage(copy))
    {
        gr.DrawImage(image, new Rectangle(0, 0, copy.Width, copy.Height));
    }
    return copy;
}

The one you would use is System.Drawing.Imaging.PixelFormat.Format24bppRgb.