|Title||Find the difference between two images in VB .NET|
|Description||This example shows how to find the difference between two images in VB .NET.|
|Keywords||image, bitmap, VB.NET, compare, difference, imagediff|
When you select two images to compare and click the Go button, the program executes the following code. It loads the two image files into Bitmaps. It finds the smaller of the Bitmaps' widths and heights, and makes a new Bitmap of that size.
Next the program loops over the pixels in the smaller area. It gets the red, green, and blue components of the pixels in one image and subtracts them from the corresponding values in the other image. It divides the result by 2 and adds 128. This makes the result lie between 1 and 255, and pixels that are the same in both images become gray.
When it has examined all of the pixels, the program displays the result image.
You can use this code to perform edge enhancement. Take an image, shift it one pixel to the right and down, and then use the program to compare the images. Areas with large changes in color (edges) are enhanced. Areas where the color is relatively stable are gray in the result.
Private Sub btnGo_Click(ByVal sender As System.Object, _
ByVal e As System.EventArgs) Handles btnGo.Click
Me.Cursor = Cursors.WaitCursor
' Load the images.
Dim bm1 As Bitmap = Image.FromFile(txtFile1.Text)
Dim bm2 As Bitmap = Image.FromFile(txtFile2.Text)
' Make a difference image.
Dim wid As Integer = Math.Min(bm1.Width, bm2.Width)
Dim hgt As Integer = Math.Min(bm1.Height, bm2.Height)
Dim bm3 As New Bitmap(wid, hgt)
' Create the difference image.
Dim are_identical As Boolean = True
Dim r1, g1, b1, r2, g2, b2, r3, g3, b3 As Integer
Dim color1, color2, color3 As Color
For x As Integer = 0 To wid - 1
For y As Integer = 0 To hgt - 1
color1 = bm1.GetPixel(x, y)
r1 = color1.R : g1 = color1.G : b1 = color1.B
color2 = bm2.GetPixel(x, y)
r2 = color2.R : g2 = color2.G : b2 = color2.B
r3 = 128 + (r1 - r2) \ 2
g3 = 128 + (g1 - g2) \ 2
b3 = 128 + (b1 - b2) \ 2
color3 = Color.FromArgb(255, r3, g3, b3)
bm3.SetPixel(x, y, color3)
If (r1 <> r2) OrElse (g1 <> g2) OrElse (b1 <> _
b2) Then are_identical = False
' Display the result.
picResult.Image = bm3
Me.Cursor = Cursors.Default
If (bm1.Width <> bm2.Width) OrElse (bm1.Height <> _
bm2.Height) Then are_identical = False
If are_identical Then
MessageBox.Show("The images are identical")
MessageBox.Show("The images are different")