Reputation: 20464
I've been working in a method to search a pixel color in a image and then get the (relative) coordinates of the found pixel color.
I've taken this example from MSDN to write the pixel search method that I've modified it a little bit to try to retrieve valuable information of each pixel such as the pixel index, but the question is if I pass an image that has the same resolution of my screen (Ex: a DeskTop Screenshot) and I find a pixel-color in that image with this method, what should be the arithmetic formula to get the coordinates?.
This is what I've done:
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
This is an example usage:
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
Upvotes: 1
Views: 601
Reputation: 9981
You get the X
, Y
coordinates by the given formulas:
x = (index Mod width)
y = ((index - x) / width)
Upvotes: 2