Home > Software design >  how to exclude part of the image [VB.NET]
how to exclude part of the image [VB.NET]

Time:03-04

please see this images

Green Background

Red Background

This person's picture has a green background. When I replace the green color to another color, it also replaces the color of the card I drew a rectangle on the card, how do I exclude the rectangle from the replacement

replace color code:

  Public Function ReplaceColor(ByVal _image As Image, ByVal _colorOld As Color, ByVal _colorNew As Color, ByVal _tolerance As Integer) As Image
     Dim bmap As Bitmap = CType(_image.Clone(), Bitmap)
     Dim c As Color
     Dim iR_Min, iR_Max As Integer
     Dim iG_Min, iG_Max As Integer
     Dim iB_Min, iB_Max As Integer
     iR_Min = Math.Max(CInt(_colorOld.R) - _tolerance, 0)
     iR_Max = Math.Min(CInt(_colorOld.R)   _tolerance, 255)
     iG_Min = Math.Max(CInt(_colorOld.G) - _tolerance, 0)
     iG_Max = Math.Min(CInt(_colorOld.G)   _tolerance, 255)
     iB_Min = Math.Max(CInt(_colorOld.B) - _tolerance, 0)
     iB_Max = Math.Min(CInt(_colorOld.B)   _tolerance, 255)

     For x As Integer = 0 To bmap.Width - 1

         For y As Integer = 0 To bmap.Height - 1
             c = bmap.GetPixel(x, y)

             If (c.R >= iR_Min AndAlso c.R <= iR_Max) AndAlso (c.G >= iG_Min AndAlso c.G <= iG_Max) AndAlso (c.B >= iB_Min AndAlso c.B <= iB_Max) Then

                 If _colorNew = Color.Transparent Then
                     bmap.SetPixel(x, y, Color.FromArgb(0, _colorNew.R, _colorNew.G, _colorNew.B))
                 Else
                     bmap.SetPixel(x, y, Color.FromArgb(c.A, _colorNew.R, _colorNew.G, _colorNew.B))
                 End If

             End If
         Next
     Next

     Return CType(bmap.Clone(), Image)
 End Function

my rectangle mastk info:

Private Rct2 As New Rectangle(247, 378, 100, 70)

CodePudding user response:

how do I exclude the rectangle from the replacement

Just use Rectangle.Contains(), but put a Not in front like this:

Public Function ReplaceColor(ByVal _image As Image, ByVal _colorOld As Color, ByVal _colorNew As Color, ByVal _tolerance As Integer) As Image

    ' ... other code ...

    For x As Integer = 0 To bmap.Width - 1
        For y As Integer = 0 To bmap.Height - 1
            If Not Rct2.Contains(New Point(x, y)) Then

                ' ... other code ...

            End If
        Next
    Next

    Return CType(bmap.Clone(), Image)
End Function
  • Related