Compare Images

The following function can be used to compare two pictures based on size and a pixel-by-pixel comparison.

Function Compare-Images {
    param(
        $ReferenceFile,
        $DifferenceFile
    )
    $ReferenceImage = [System.Drawing.Bitmap]::FromFile($ReferenceFile)
    $DifferenceImage = [System.Drawing.Bitmap]::FromFile($DifferenceFile)

    if ($ReferenceImage.Size -ne $DifferenceImage.Size) {
        Write-Host "Images are of different sizes"
        $false
    }
    else {
        # Set the difference to 0
        [float]$Difference = 0;
        # Parse through each pixel
        for ($y = 0; $y -lt $ReferenceImage.Height; $y++) {
            for ($x = 0; $x -lt $ReferenceImage.Width; $x++) {
                $ReferencePixel = $ReferenceImage.GetPixel($x, $y);
                $DifferencePixel = $DifferenceImage.GetPixel($x, $y);
                # Caculate the difference in the Red, Green, and Blue colors
                $Difference += [System.Math]::Abs($ReferencePixel.R - $DifferencePixel.R);
                $Difference += [System.Math]::Abs($ReferencePixel.G - $DifferencePixel.G);
                $Difference += [System.Math]::Abs($ReferencePixel.B - $DifferencePixel.B);
            }
        }
        # Caculate the precentage of difference between the photos
        $Difference = $(100 * ($Difference / 255) / ($ReferenceImage.Width * $ReferenceImage.Height * 3))
        if ($Difference -gt 0) {
            Write-Host "Difference: $Difference %" 
            $false
        }
        else {
            $true
        }
    }
}
PS C:\>Compare-Images "C:\Pictures\Pic01a.png" "C:\Pictures\Pic01b.png"
Difference: 0.01859266 %
False

The this post of part of the series Automation Authoring. Refer the main article for more details on use cases and additional content in the series.