.net 从像素搜索方法检索坐标?
我一直在研究一种方法来搜索图像中的像素颜色,然后得到找到的像素颜色的(相对)坐标 我开始编写像素搜索方法,我对其进行了一些修改,试图检索每个像素的有价值的信息,如像素索引,但问题是,如果我通过一个与我的屏幕分辨率相同的图像(例如:桌面屏幕截图),我用此方法在该图像中找到一个像素颜色,得到坐标的算术公式应该是什么 这就是我所做的:.net 从像素搜索方法检索坐标?,.net,vb.net,math,coordinates,pixel,.net,Vb.net,Math,Coordinates,Pixel,我一直在研究一种方法来搜索图像中的像素颜色,然后得到找到的像素颜色的(相对)坐标 我开始编写像素搜索方法,我对其进行了一些修改,试图检索每个像素的有价值的信息,如像素索引,但问题是,如果我通过一个与我的屏幕分辨率相同的图像(例如:桌面屏幕截图),我用此方法在该图像中找到一个像素颜色,得到坐标的算术公式应该是什么 这就是我所做的: Public Class PixelData Public Index As Integer Public Color As Color Pub
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
您可以通过给定的公式获得
X
,Y
坐标:
x = (index Mod width)
y = ((index - x) / width)