我应该如何检测多个具有相同颜色的像素

时间:2014-03-23 05:02:33

标签: vb.net bitmap pixels

此问题与Visual Basic .NET 2010

有关

好的,我制作了这个程序,可以在屏幕的任何表面上重绘图像。我正在使用一些Win32 API移动鼠标并模拟点击等。

问题是,我过去只是为每个像素点击,这在flash或javascript表面上使用会导致很多延迟。

我需要检测像素的“线条”,如果我列举像素并检查它们的颜色,如果当前像素是黑色,接下来的10个也是黑色,我需要能够检测它并画一条线而不是点击每一条线,以防止滞后。

这是我当前的代码,这是我枚举像素的方式。

Private Sub Draw()
    If First Then
        Pos = New Point(Me.Location)
        MsgBox("Position set, click again to draw" & vbCrLf _
               & "Estimated time: " & (Me.BackgroundImage.Width * Me.BackgroundImage.Height) / 60 & " seconds (1ms/pixel)")
        First = False
    Else
        Using Bmp As New Bitmap(Me.BackgroundImage)
            Using BmpSize As New Bitmap(Bmp.Width, Bmp.Height, System.Drawing.Imaging.PixelFormat.Format32bppPArgb) 'Use to get size of bitmap
                For y As Integer = 0 To BmpSize.Height - 1
                    For x = 0 To BmpSize.Width - 1
                        Dim curPixColor As Color = Bmp.GetPixel(x, y)
                        If curPixColor = Color.White Then Continue For 'Treat white as nothing
                        If IsColorBlack(curPixColor) Then
                            'TODO:
                            'If more than 1 black pixel in a row, use _Drag() to draw line
                            'If 1 pixel followed by white, use _Click() to draw 1 pixel
                        End If
                    Next
                Next
                MsgBox("Drawn")
                First = True 'Nevermind this, used for resetting the program
            End Using
        End Using
    End If
End Sub

Private Sub _Drag(ByVal From As Point, ByVal _To As Point)
    SetCursorPos(From.X, From.Y)
    mouse_event(MOUSEEVENTF_LEFTDOWN, 0, 0, 0, 0)
    SetCursorPos(_To.X, _To.Y)
    mouse_event(MOUSEEVENTF_LEFTUP, 0, 0, 0, 0)
End Sub

Private Sub _Click(ByVal At As Point)
    SetCursorPos(At.X, At.Y)
    mouse_event(MOUSEEVENTF_LEFTDOWN, 0, 0, 0, 0)
    mouse_event(MOUSEEVENTF_LEFTUP, 0, 0, 0, 0)
End Sub

与往常一样,非常感谢帮助。这是一个相当复杂的问题,但我希望我有所了解。

1 个答案:

答案 0 :(得分:2)

您可以尝试像这样计算

'Count of the black pixels
Dim BlackCount As Integer = 1
'Another intermediate X variable
Dim ThisX As Integer = x + 1
'Run along until reaching the right edge or a not black pixel
While ThisX < Bmp.Width AndAlso IsColorBlack(Bmp.GetPixel(ThisX, y))
    BlackCount += 1
    ThisX += 1
End While
'Act accordingly
If BlackCount > 1 Then
   'Drag from x to Thisx-1
Else
   'Click
End If
x = ThisX 'Update the X variable to skip over the covered area

还要尝试确定导致延迟的原因。 GetPixel和SetPixel非常慢。为了提高性能,请查看LockBits读取像素值的方法。首次尝试谷歌或http://msdn.microsoft.com/de-de/library/ms229672%28v=vs.90%29.aspx。它的幅度更快,应该在读取任何大量像素时使用。