Recently, a customer needed to find the differences between two images. More specifically the customer needed to find what changed between the two images and crop to leave only the change. From there, the LEADTOOLS OCR engine converted the cropped image to text to create a screen reader for visually impaired users. Additionally, animation and compression algorithms use similar techniques to improve performance and efficiency.
Support quickly responded to the customer with a C# console application example that finds the bounding rectangle of the differences and then crops the image.
The core function of the project finds the absolute difference between the pixels in the image. This changes all unchanged pixels to black. Because all pixels that did not change are black, the function creates a region based on color black to find the bounding rectangle of the change. Finally, the function crops the changed image to the bounding rectangle and returns the results.
static RasterImage Differences(RasterImage original, RasterImage changed)
{
// Make a copy of changed image for cropping later
RasterImage temp = changed.Clone();
// Get absolute difference of all the pixels
// leaving only what is different between the two
new CombineCommand(original,
LeadRect.Create(0, 0, original.ImageWidth, original.ImageHeight),
LeadPoint.Create(0, 0),
CombineCommandFlags.AbsoluteDifference)
.Run(changed);
// select all non-black colors (these are all the colors that
// are different between the two images)
changed.AddColorToRegion(
RasterColor.Black,
RasterRegionCombineMode.SetNot);
// Crop the original image to the bounding rectangle to
// obtain all that has changed.
new CropCommand(changed.GetRegionBounds(null))
.Run(temp);
// Free the region
changed.MakeRegionEmpty();
// return the cropped image
return temp;
}
The Visual Studio C# console project can be found on the LEADTOOLS Support Forums, here:
http://support.leadtools.com/SupportPortal/CS/forums/44815/ShowPost.aspx#44815
Pre-requisites needed to run the project:
- LEADTOOLS V19 with evaluation, Imaging Pro or better license file.
- Visual Studio 2010 or later. (Visual Studio 2012/2013 recommended).