【问题标题】:Fast way to convert a Bitmap into a Boolean array in C#?在 C# 中将位图转换为布尔数组的快速方法?
【发布时间】:2012-05-11 23:45:13
【问题描述】:

我正在制作一个 XNA 应用程序,我每秒从网络摄像头捕获屏幕截图 4 次,然后当像素颜色红色低于某个阈值时,我尝试将其转换为布尔数组。当我将其转换为 Texture2D 时,它不会滞后,但是当我尝试获取单个像素时,它确实会滞后,即使网络摄像头分辨率为 176x144。

这是获取位图的代码:

public Bitmap getBitmap()
    {
        if (!panelVideoPreview.IsDisposed)
        {
            Bitmap b = new Bitmap(panelVideoPreview.Width, panelVideoPreview.Height, PixelFormat.Format32bppRgb);
            using (Graphics g = Graphics.FromImage(b))
            {
                Rectangle rectanglePanelVideoPreview = panelVideoPreview.Bounds;
                Point sourcePoints = panelVideoPreview.PointToScreen(new Point(panelVideoPreview.ClientRectangle.X, panelVideoPreview.ClientRectangle.Y));
                g.CopyFromScreen(sourcePoints, Point.Empty, rectanglePanelVideoPreview.Size);
            }

            return b;
        }
        else
        {
            Bitmap b = new Bitmap(panelVideoPreview.Width, panelVideoPreview.Height);
            return b;
        }
    }

这是将位图转换为布尔数组的代码:

public bool[,] getBoolBitmap(uint treshold)
    {
        Bitmap b = getBitmap();

        bool[,] ar = new bool[b.Width, b.Height];

        for (int y = 0; y < b.Height; y++)
        {
            for (int x = 0; x < b.Width; x++)
            {
                if (b.GetPixel(x, y).R < treshold)
                {
                    ar[x, y] = false;
                }
                else
                {
                    ar[x, y] = true;
                }
            }
        }

        return ar;
    }

【问题讨论】:

  • GetPixel() 非常慢,它必须锁定每个像素的位图数据。请改用 Bitmap.LockBits()。当你把它放在搜索框中时,会有很多点击。

标签: c# arrays performance bitmap boolean


【解决方案1】:

Hans Passant 提供的答案是正确的,最好使用 LockBits 并一次性处理所有数据。

您也可以尝试编写一个着色器,对数据进行阈值处理,从而利用 GPU 的强大功能以更快、更快的速度并行处理输入图像流。

【讨论】:

    猜你喜欢
    • 2021-02-16
    • 1970-01-01
    • 2022-01-18
    • 2015-04-14
    • 1970-01-01
    • 2016-07-04
    • 1970-01-01
    • 2012-06-15
    • 2015-08-23
    相关资源
    最近更新 更多