AForge.Net – Similar images

AForge.NET is a C# framework designed for developers and researchers in the fields of Computer Vision and Artificial Intelligence – image processing, neural networks, genetic algorithms, machine learning, robotics.

Years ago I wrote a small post using AForge.net for detecting motion and calculating average color AForge.Net – Examples for average color and motion detection. In this post I’ll use AForge.Net for calculating the similarity grad between 2 images.

1. Similiar images

In code listing below I use ExhaustiveTemplateMatching instance with similarityThreshold of 50%. The higher this value is, the more accurate the comparision is.

I take 2 images below as sample file.

Microsoft 1

Microsoft 2

The texts are almost same. The differences are the white part around the text. However even with a pretty low similarityThreshold, the Similarity is just about 93,8%.

static void Main(string[] args)
{
	const string imageCase11 = @"Images\Case1_1.jpg";
	const string imageCase12 = @"Images\Case1_2.jpg";

	const float similarityThreshold = 0.50f;
  

	ExhaustiveTemplateMatching exhaustiveTemplateMatching = new ExhaustiveTemplateMatching(similarityThreshold);

	if (File.Exists(imageCase11) || File.Exists(imageCase12))
	{

		Bitmap bitmap1 = new Bitmap(imageCase11);
		Bitmap bitmap2 = new Bitmap(imageCase12);

		Size size = GetSize(bitmap1.Size, bitmap2.Size);
		ResizeBilinear filter = new ResizeBilinear(size.Width, size.Height);
		bitmap2 = filter.Apply(bitmap2);
		TemplateMatch[] matches = exhaustiveTemplateMatching.ProcessImage(bitmap1, bitmap2);
		if (matches.Length <= 0)
			Console.WriteLine("Not even matched");
		else
		{
			float similarity = 0.95f;
			bool isMatch = matches[0].Similarity >= similarity;
			Console.WriteLine(isMatch ? $"Images matched over {similarity}" :
				$"Images not matched with similarity of {similarity}");

			similarity = 0.90f;
			isMatch = matches[0].Similarity >= similarity;
			Console.WriteLine(isMatch ? $"Images matched over {similarity}" :
				$"Images not matched with similarity of {similarity}");
		}
	}
	else
	{
		Console.WriteLine("Files not exist");
	}
	Console.ReadLine();
}

2. Source code

– Source code: https://bitbucket.org/hintdesk/dotnet-aforge-net-similiar-images

Leave a Reply

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.