Rosmarine Popcorn
Rosmarine Popcorn

Reputation: 10967

Image Comparing and return Percentage

int DiferentPixels = 0;
Bitmap first = new Bitmap("First.jpg");
Bitmap second = new Bitmap("Second.jpg");
Bitmap container = new Bitmap(first.Width, first.Height);
for (int i = 0; i < first.Width; i++)
{
    for (int j = 0; j < first.Height; j++)
    {
    int r1 = second.GetPixel(i, j).R;
    int g1 = second.GetPixel(i, j).G;
    int b1 = second.GetPixel(i, j).B;

    int r2 = first.GetPixel(i, j).R;
    int g2 = first.GetPixel(i, j).G;
    int b2 = first.GetPixel(i, j).B;

    if (r1 != r2 && g1 != g2 && b1 != b2)
    {
    DiferentPixels++;
    container.SetPixel(i, j, Color.Red);
    }
    else
    container.SetPixel(i, j, first.GetPixel(i, j));
    }
}
int TotalPixels = first.Width * first.Height;
float dierence = (float)((float)DiferentPixels / (float)TotalPixels);
float percentage = dierence * 100;

With this portion of Code im comparing 2 Images foreach Pixels and yes it work's it return's Percentage of difference ,so it compares each Pixel of First Image with pixel in same index of Second Image .But what is wrong here ,i have a huge precision maybe it should not work like that ,the comparison ,and maybe there are some better algorithms which are faster and more flexible . So anyone has an idea how can i transform the comparison ,should i continue with that or should i compare Colors of Each Pixels or ....

PS : If anyone has a solution how to make Parallel this code ,i would also accept it ! Like expanding this to 4 Threads would they do it faster right in a Quad Core?

Upvotes: 3

Views: 9923

Answers (2)

xpda
xpda

Reputation: 15813

For speed, resize the images to something very small (16x12, for example) and do the pixel comparison. If it is a near match, then try it at higher resolution.

Upvotes: 6

dlev
dlev

Reputation: 48596

One obvious change would be call GetPixel only once per Bitmap, and then work with the returned Color structs directly:

for (int i = 0; i < first.Width; ++i)
{
    for (int j = 0; j < first.Height; ++j)
    {
        Color secondColor = second.GetPixel(i, j);
        Color firstColor = first.GetPixel(i, j);

        if (firstColor != secondColor)
        {
            DiferentPixels++;
            container.SetPixel(i, j, Color.Red);
        }
        else
        {
            container.SetPixel(i, j, firstColor);
        }
    }
}

Upvotes: 7

Related Questions