在C#中将Bitmap转换为布尔数组的快速方法?

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

这是获取位图的代码:

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; } } 

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

 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; } 

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

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