Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 325
Rosmarine Popcorn Avatar asked Feb 21 '26 10:02

Rosmarine Popcorn


1 Answers

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);
        }
    }
}
like image 172
dlev Avatar answered Feb 23 '26 22:02

dlev