我一直在我的程序中使用图像识别,并一直认为这是我的应用程序中实际图像识别代码的问题。在深入研究之后,我意识到我用来创建屏幕截图的代码,屏幕的全屏和部分矩形都在创建模糊图像。图像模糊且像素化。
我通常不保存图像,我只是使用内存中的位图进行图像识别检查。虽然以多种格式保存这些屏幕截图后,我可以看到问题。
这是我用来生成屏幕截图的代码。第一个函数创建一个完整的屏幕截图,第二个函数从屏幕上的坐标创建一个。
Public Shared Function GetScreen() As Bitmap
Dim screenSize As Size = New Size(My.Computer.Screen.Bounds.Width, My.Computer.Screen.Bounds.Height)
Dim screenGrab As New Bitmap(My.Computer.Screen.Bounds.Width, My.Computer.Screen.Bounds.Height)
Using g As Graphics = Graphics.FromImage(screenGrab)
g.CopyFromScreen(New Point(0, 0), New Point(0, 0), screenSize)
Return screenGrab
End Using
End Function
Public Shared Function
GetScreenXY(TopLeft As Point, BottomRight As Point) As Bitmap
Dim w As Integer = BottomRight.X - TopLeft.X
Dim h As Integer = BottomRight.Y - TopLeft.Y
Dim screenGrab As New Bitmap(w, h) 'width and height of the rectangle you want to grab
Using g As Graphics = Graphics.FromImage(screenGrab)
g.CopyFromScreen(TopLeft, New Point(0, 0), screenGrab.Size)
Return screenGrab
End Using
End Function
我最近添加的应用程序中还有一个屏幕截图工具。它有一个可以调整大小的表格,它可以截屏并保存它。这些也很模糊。它使用第二个功能。
Visible = False
Dim screenShot As Bitmap = ImageFinder.GetScreenXY(New Point(Left, Top), New Point(Right, Bottom))
Dim sfd As New SaveFileDialog
sfd.Filter = "Jpeg image (*.jpg)|*.jpg|Bitmap image (*.bmp)|*.bmp| PNG image (*.png)|*.png"
sfd.Title = "Save image"
If sfd.ShowDialog() = DialogResult.OK Then
If sfd.FileName <> String.Empty Then
'Set to Jpeg by default.
Dim MyImageFormat As System.Drawing.Imaging.ImageFormat = System.Drawing.Imaging.ImageFormat.Jpeg
If sfd.FileName.ToString.ToUpper.EndsWith("JPG") Then
MyImageFormat = System.Drawing.Imaging.ImageFormat.Jpeg
ElseIf sfd.FileName.ToString.ToUpper.EndsWith("BMP") Then
MyImageFormat = System.Drawing.Imaging.ImageFormat.Bmp
ElseIf sfd.FileName.ToString.ToUpper.EndsWith("PNG") Then
MyImageFormat = System.Drawing.Imaging.ImageFormat.Png
End If
screenShot.Save(sfd.FileName, MyImageFormat)