有没有更快的方法将位图像素转换为灰度?

时间:2014-05-11 16:45:04

标签: vb.net performance bitmap processing-efficiency

目前,我正在使用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

1 个答案:

答案 0 :(得分:4)

快速是一个相对术语,但这会将一个480x270的图像转换为10-12毫秒的灰度(显然取决于系统),这似乎并不过分。我很确定它会比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

四舍五入