You have seen that image processing happens up to 30 frames per second. This means that memory allocation and clean-up is happening around 30 times per second. This makes performance trail, though it does not matter for a small application; but for a more complex application where there is major work involved other than only a color camera, it could be a big concern.
To make your application perform better, the alternative way is to process images using the WriteableBitmap
object, which serves the purpose of frequently updating the image pixel. You can find this WriteableBitmap
object in the System.Windows.Media.Imaging
namespace. The WriteableBitmap
object works in a different way than BitmapSource
. The WriteableBitmap
object allocates the memory at once and updates only the pixel data on frame change. WriteableBitmap
improves the performance by reducing the memory consumption as well as memory allocation and deallocation.
The overall implementation approach for WriteableBitmap
can be performed very easily. First create the WriteableBitmap
object:
private WriteableBitmap writeableBitmap;
Then enable the ColorStream
channel and initialize the writeableBitmap
object with the frame width, height, and pixel formats. Then assign the writeableBitmap
object to the source property of image control. Then attach the ColorFrameReady
event:
if (this.sensor !=null & this.sensor.IsRunning && !this.sensor.ColorStream.IsEnabled) { this.sensor.ColorStream.Enable(); this.writeableBitmap = new WriteableBitmap(this.sensor.ColorStream.FrameWidth, this.sensor.ColorStream.FrameHeight, 96, 96, PixelFormats.Bgr32, null); VideoControl.Source = this.writeableBitmap; this.sensor.ColorFrameReady += sensor_ColorFrameReady; }
Use the following code block for the ColorFrameReady
event handler. The only difference you will find in this event handler is the WritePixels()
method, which is being updated with the pixel data for every frame.
void sensor_ColorFrameReady(object sender, ColorImageFrameReadyEventArgs e) { using (ColorImageFrame imageFrame = e.OpenColorImageFrame()) { if (imageFrame != null) { byte[] pixelData = new byte[imageFrame.PixelDataLength]; imageFrame.CopyPixelDataTo(pixelData); int stride = imageFrame.Width * imageFrame.BytesPerPixel; this.writeableBitmap.WritePixels( new Int32Rect(0, 0, this.writeableBitmap.PixelWidth, this.writeableBitmap.PixelHeight), pixelData, stride, 0); } } }
You can see that with the WritePixels()
method, the reference to writeableBitmap
is getting updated with the new frame from the sensor. This is just updating the frame's pixels and keeping other things unchanged.
3.133.12.172