【发布时间】:2017-12-15 05:53:19
【问题描述】:
我正在尝试获取 Kinect v2 中每个 CameraSpacePoint 的 RGB 值。在尝试访问转换后的帧数据时,代码正在抛出 IndexOutOfRangeException。我发现以下几行抛出了这个错误:
byte red = pixels[4 * pixelsBaseIndex + 0];
byte green = pixels[4 * pixelsBaseIndex + 1];
byte blue = pixels[4 * pixelsBaseIndex + 2];
byte alpha = pixels[4 * pixelsBaseIndex + 3];
请看下面的完整代码:
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));
}
}
代码看起来不错,但是我不确定我在这里缺少什么! 如何避免IndexOutOfRangeException 异常?有什么建议吗?
【问题讨论】:
-
您是否尝试控制台记录pixelBaseIndex 和pixels.Length,我猜colorPoints 可能会导致奇怪的索引,据我了解CopyConvertedFrameDataToArray 使字节数组为4 个字节
-
@whoisthis:非常感谢。我做到了。请看这个
Console.WriteLine("pixelsBaseIndex:" + pixelsBaseIndex + ", pixels.Length:" + pixels.Length + ", minValue:" + minValue + ", maxValue:" + maxValue);printspixelsBaseIndex:2074817, pixels.Length:8294400, minValue:8299268, maxValue:8299271pixelsBaseIndex 正在改变,因此上面的输出只是一个 sn-p -
@whoisthis:有什么建议吗?