I was looking for help with checking the similarity between 2 images and I came across this SO post, which referred to this SO post. While both posts have helpful information I decided to use the approach found on this site here - which is remarkably straightforward.
With this background in mind I have decided to use the below approach for comparing 2 images. My question is - should this approach scale well? By scale well I mean is it thread safe? If it is not thread safe what should I change to make it thread safe?
using System;
using System.Drawing;
class Program
{
static void Main()
{
Bitmap img1 = new Bitmap("Lenna50.jpg");
Bitmap img2 = new Bitmap("Lenna100.jpg");
if (img1.Size != img2.Size)
{
Console.Error.WriteLine("Images are of different sizes");
return;
}
float diff = 0;
for (int y = 0; y < img1.Height; y++)
{
for (int x = 0; x < img1.Width; x++)
{
Color pixel1 = img1.GetPixel(x, y);
Color pixel2 = img2.GetPixel(x, y);
diff += Math.Abs(pixel1.R - pixel2.R);
diff += Math.Abs(pixel1.G - pixel2.G);
diff += Math.Abs(pixel1.B - pixel2.B);
}
}
Console.WriteLine("diff: {0} %", 100 * (diff / 255) / (img1.Width * img1.Height * 3));
}
}
UPDATE: Here is the updated class with the threading code. I have not used threading much. It works fine when I test locally. I am wondering if this is an okay method to use. I was also, wondering if I should use Thread.Sleep so that this thread does not block other threads.
using System;
using System.Drawing;
using System.Threading;
public class CompareImages
{
public static string statusmsg = string.Empty;
public static void CheckImages(string imagepath1, string imagepath2)
{
// Create thread
Thread thread = new Thread(() => CheckImageDiff(imagepath1, imagepath2));
thread.Start();
thread.Join(); // Does this mean I don't have to do Thread.Sleep(__)?
}
public static void CheckImageDiff(string path1, string path2)
{
Bitmap img1 = new Bitmap(path1);
Bitmap img2 = new Bitmap(path2);
if (img1.Size != img2.Size)
{
statusmsg = "Images are of different sizes. Images should be the same size.";
}
else
{
float diff = 0;
for (int y = 0; y < img1.Height; y++)
{
for (int x = 0; x < img1.Width; x++)
{
Color pixel1 = img1.GetPixel(x, y);
Color pixel2 = img2.GetPixel(x, y);
diff += Math.Abs(pixel1.R - pixel2.R);
diff += Math.Abs(pixel1.G - pixel2.G);
diff += Math.Abs(pixel1.B - pixel2.B);
}
}
statusmsg = "diff: {0} %";
statusmsg = string.Format(statusmsg, 100 * (diff / 255) / (img1.Width * img1.Height * 3));
}
// Write status msg to database or make available to other method...
}
}