Reputation:
I am making an XNA application where I capture the screenshot from a webcam 4 times a second and then I try to convert it into an Boolean array when the pixel color Red is below a certain threshold. When I convert it into a Texture2D it doesn't lag but when I try to get the individual pixels it does lag, even when the webcam resolution is 176x144.
This is the code to grab the Bitmap:
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;
}
}
This is the code to convert the Bitmap to a Boolean array:
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;
}
Upvotes: 1
Views: 1893
Reputation: 10896
The answer provided by Hans Passant is correct, it is better to use LockBits and process the data all at once.
You might also try writing a shader that thresholds the data and thereby utilize the power of the GPU to parallel-process the input image stream much, much faster.
Upvotes: 1