目前,我正在使用 SetPixel()
改变位图中每个像素颜色的方法。这在小尺寸的小图像上效果很好,但是当我在大图像上测试时,它确实需要一段时间。
我之前没有在 VB.Net 中处理过图像,所以我可能只是忽略了一些明显的东西。我这样做是为了制作一个将图像转换为灰度的程序。这会产生正确的结果,但速度较低,并且在此期间 UI 卡住,因此我很想最大限度地提高转换速度。
这是我目前的代码:
Dim tmpImg As New Bitmap(img) '"img" is a reference to the original image
For x As Integer = 0 To tmpImg.Width - 1
For y As Integer = 0 To tmpImg.Height - 1
Dim clr As Byte
With tmpImg.GetPixel(x, y)
clr = ConvertToGrey(.R, .G, .B)
End With
tmpImg.SetPixel(x, y, Color.FromArgb(clr, clr, clr))
Next
Next
Private Function ConvertToGrey(ByVal R As Byte, ByVal G As Byte, ByVal B As Byte) As Byte
Return (0.2126 * R) + (0.7152 * B) + (0.0722 * G)
End Function
最佳答案
快速是一个相对术语,但这会在 10-12 毫秒(显然取决于系统)内将 480x270 图像转换为灰度,这似乎不会过长。我很确定它会比 SetPixel 更快。
Private Function GrayedImage(orgBMP As Bitmap) As Bitmap
Dim grayscale As New Imaging.ColorMatrix(New Single()() _
{New Single() {0.3, 0.3, 0.3, 0, 0},
New Single() {0.59, 0.59, 0.59, 0, 0},
New Single() {0.11, 0.11, 0.11, 0, 0},
New Single() {0, 0, 0, 1, 0},
New Single() {0, 0, 0, 0, 1}})
Dim bmpTemp As New Bitmap(orgBMP)
Dim grayattr As New Imaging.ImageAttributes()
grayattr.SetColorMatrix(grayscale)
Using g As Graphics = Graphics.FromImage(bmpTemp)
g.DrawImage(bmpTemp, New Rectangle(0, 0, bmpTemp.Width, bmpTemp.Height),
0, 0, bmpTemp.Width, bmpTemp.Height,
GraphicsUnit.Pixel, grayattr)
End Using
Return bmpTemp
End Function
值从 .299、.587、.114 四舍五入
关于vb.net - 有没有更快的方法将位图像素转换为灰度?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23595258/