I am trying to get the RGB values of each CameraSpacePoint in Kinect v2. While trying to access converted frame data, the code is throwing IndexOutOfRangeException
. I found out that following lines are throwing this error:
byte red = pixels[4 * pixelsBaseIndex + 0];
byte green = pixels[4 * pixelsBaseIndex + 1];
byte blue = pixels[4 * pixelsBaseIndex + 2];
byte alpha = pixels[4 * pixelsBaseIndex + 3];
Please see the complete code below:
int depthWidth = kinectSensor.DepthFrameSource.FrameDescription.Width;
int depthHeight = kinectSensor.DepthFrameSource.FrameDescription.Height;
int colorWidth = kinectSensor.ColorFrameSource.FrameDescription.Width;
int colorHeight = kinectSensor.ColorFrameSource.FrameDescription.Height;
ushort[] depthData = new ushort[depthWidth * depthHeight];
CameraSpacePoint[] cameraPoints = new CameraSpacePoint[depthData.Length];
ColorSpacePoint[] colorPoints = new ColorSpacePoint[depthData.Length];
// Assuming RGBA format here
byte[] pixels = new byte[colorWidth * colorHeight * 4];
depthFrame = multiSourceFrame.DepthFrameReference.AcquireFrame();
colorFrame = multiSourceFrame.ColorFrameReference.AcquireFrame();
if ((depthFrame == null) || (colorFrame == null))
{
return;
}
depthFrame.CopyFrameDataToArray(depthData);
coordinateMapper.MapDepthFrameToCameraSpace(depthData, cameraPoints);
coordinateMapper.MapDepthFrameToColorSpace(depthData, colorPoints);
// We are using RGBA format
colorFrame.CopyConvertedFrameDataToArray(pixels, ColorImageFormat.Rgba);
for (var index = 0; index < depthData.Length; index++)
{
var u = colorPoints[index].X;
var v = colorPoints[index].Y;
if (u < 0 || u >= colorWidth || v < 0 || v >= colorHeight) continue;
int pixelsBaseIndex = (int)(v * colorWidth + u);
try
{
byte red = pixels[4 * pixelsBaseIndex + 0];
byte green = pixels[4 * pixelsBaseIndex + 1];
byte blue = pixels[4 * pixelsBaseIndex + 2];
byte alpha = pixels[4 * pixelsBaseIndex + 3];
}
catch (IndexOutOfRangeException ex)
{
int minValue = 4 * pixelsBaseIndex;
int maxValue = 4 * pixelsBaseIndex + 3;
Console.WriteLine((minValue > 0) + ", " + (maxValue < pixels.Length));
}
}
The code looks fine however I am not sure what am I missing here! How to avoid IndexOutOfRangeException
exception? Any suggestions, please?