【问题标题】:Is there a faster method to convert bitmap pixels to greyscale?有没有更快的方法将位图像素转换为灰度?
【发布时间】:2014-06-29 00:03:44
【问题描述】:

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

【问题讨论】:

标签: vb.net performance bitmap processing-efficiency


【解决方案1】:

快速是一个相对术语,但这会在 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

值从 0.299、0.587、0.114 四舍五入

【讨论】:

  • 1280*720 图像的时间约为 80 毫秒。考虑到它在做什么,我对此没有任何问题。
  • 谢谢,我以前从不知道ColorMatrix,我发现它非常复杂。然而结果非常棒,我在 3008 x 2000 图像上得到了 1028 毫秒(~1 秒),而我正在得到 297273 毫秒(4 分 57 秒) 在同一图像上。显然是一个巨大的改进,我只需要阅读 this 直到我得到它。
猜你喜欢
  • 1970-01-01
  • 2018-11-28
  • 2019-03-11
  • 1970-01-01
  • 2018-03-16
  • 1970-01-01
  • 1970-01-01
  • 2017-02-17
  • 2010-11-20
相关资源
最近更新 更多