从像素搜索方法中检索坐标?

时间:2014-07-10 07:58:07

标签: .net vb.net math coordinates pixel

我一直在研究一种方法来搜索图像中的像素颜色,然后得到找到的像素颜色的(相对)坐标。

我已经this example from MSDN编写了我稍微修改过的像素搜索方法,试图检索每个像素的有价值的信息,比如像素索引,但问题是我是否通过了我的屏幕具有相同分辨率的图像(例如:DeskTop屏幕截图),我使用此方法在该图像中找到像素颜色,获取坐标的算术公式应该是什么?

这就是我所做的:

Public Class PixelData
    Public Index As Integer
    Public Color As Color
    Public Coordinates As Point
End Class

Friend Function GetPixelData(ByVal bmp As Bitmap) As List(Of PixelData)

    If Not bmp.PixelFormat = Imaging.PixelFormat.Format24bppRgb Then
        Throw New Exception("PixelFormat not supported by this function.")
    End If

    ' Lock the bitmap's bits.   
    Dim rect As New Rectangle(0, 0, bmp.Width, bmp.Height)
    Dim bmpdata As Drawing.Imaging.BitmapData =
        bmp.LockBits(rect, Imaging.ImageLockMode.ReadWrite, bmp.PixelFormat)

    ' Get the address of the first line. 
    Dim ptr As IntPtr = bmpdata.Scan0

    ' Declare an array to hold the bytes of the bitmap. 
    ' This code is specific to a bitmap with 24 bits per pixels. 
    Dim bytes As Integer = Math.Abs(bmpdata.Stride) * bmp.Height
    Dim rgbValues(bytes - 1) As Byte

    ' Copy the RGB values into the array.
    Runtime.InteropServices.Marshal.Copy(ptr, rgbValues, 0, bytes)

    ' Unlock the bits.
    bmp.UnlockBits(bmpdata)

    ' Set the Data to return.
    Dim Pixels As New List(Of PixelData)

    ' Loop through each 24bpp-RGB value.
    For Index As Integer = 2 To rgbValues.Length - 1 Step 3

        Pixels.Add(New PixelData With
                   {
                       .Index = Index \ 3I,
                       .Color = Color.FromArgb(rgbValues(Index), rgbValues(Index - 1I), rgbValues(Index - 2I)),
                       .Coordinates = Point.Empty
                   })

    Next Index

    Return Pixels

End Function

这是一个示例用法:

Private Sub Test() Handles Button1.Click

    ' Create a new bitmap (of my screen resolution). 
    Dim bmp As Bitmap = Me.GetDesktopScreenshot

    ' Specify the RGB PixelColor to search.
    Dim FindColor As Color = Color.FromArgb(181, 230, 29)

    ' Get the pixel data.
    Dim Pixels As List(Of PixelData) = Me.GetPixelData(bmp)

    For Each Pixel As PixelData In Pixels

        If Pixel.Color = FindColor Then
            MessageBox.Show(String.Format("Color found at pixel index {0}", 
                                          CStr(Pixel.Index)))
        End If

    Next Pixel

End Sub

1 个答案:

答案 0 :(得分:2)

您可以通过给定的公式获得XY坐标:

x = (index Mod width)
y = ((index - x) / width)