Home
Search
 
What's New
Index
Books
Links
Q & A
Newsletter
Banners
 
Feedback
Tip Jar
 
C# Helper...
 
XML RSS Feed
Follow VBHelper on Twitter
 
 
 
MSDN Visual Basic Community
 
 
 
 
 
TitleCompare two images to find differences greater than a threshold value in VB .NET
DescriptionThis example shows how to compare two images to find differences greater than a threshold value in VB .NET.
Keywordsimage, bitmap, VB.NET, compare, difference, imagediff
CategoriesGraphics, VB.NET
 
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, comparing the the images' pixels. For each pixel, the program calculates the sum of the squares of the differences between the pixels' red, green, and blue components. It then colors the result pixel depending on whether the value is greater than or less than the threshold value.

 
Private Sub btnGo_Click(ByVal sender As System.Object, _
    ByVal e As System.EventArgs) Handles btnGo.Click
    Me.Cursor = Cursors.WaitCursor
    Application.DoEvents()

    ' Get the threshold.
    Dim threshold As Integer = _
        Integer.Parse(txtThreshold.Text)

    ' 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 As Color
    Dim eq_color As Color = Color.White
    Dim ne_color As Color = Color.Red
    Dim dr, dg, db, diff As Integer
    For x As Integer = 0 To wid - 1
        For y As Integer = 0 To hgt - 1
            color1 = bm1.GetPixel(x, y)
            color2 = bm2.GetPixel(x, y)
            dr = CInt(color1.R) - color2.R
            dg = CInt(color1.G) - color2.G
            db = CInt(color1.B) - color2.B
            diff = dr * dr + dg * dg + db * db
            If diff <= threshold Then
                bm3.SetPixel(x, y, eq_color)
            Else
                bm3.SetPixel(x, y, ne_color)
                are_identical = False
            End If
        Next y
    Next x

    ' 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")
    Else
        MessageBox.Show("The images are different")
    End If

    bm1.Dispose()
    bm2.Dispose()
End Sub
 
 
Copyright © 1997-2010 Rocky Mountain Computer Consulting, Inc.   All rights reserved.
  Updated