Hololens 2 UWP C#:2272x1278下NV12图像损坏
结论
图像损坏很可能是因为读取 NV12 亮度平面时,没有处理行步幅(Stride)和起始偏移(StartIndex)。
NV12 的 Y 平面位于 UV 平面之前,但每行占用的空间未必等于 PixelWidth 字节,Y 平面也未必从缓冲区偏移 0 开始。摄像头驱动通常会将每行按 16、32 或 64 字节边界对齐。
图像宽度为 2272 像素时,实际 Stride 很可能是 2304。当前代码按照 2272 × 1278 连续复制缓冲区,没有跳过每行末尾的 32 字节填充,导致后续各行的读取位置逐渐偏移,形成斜向条纹。896 恰好能被 64 整除,该分辨率下的 Stride 可能就是 896,因此原来的读取方式没有暴露问题。
正确读取 NV12 的 Y 平面
锁定缓冲区后,使用 GetPlaneDescription(0) 获取 Y 平面的布局,再逐行复制有效像素:
private void OnFrameArrived(
MediaFrameReader sender,
MediaFrameArrivedEventArgs args)
{
if (sender == null)
throw new ArgumentNullException(nameof(sender));
using (MediaFrameReference frame = sender.TryAcquireLatestFrame())
{
SoftwareBitmap softwareBitmap =
frame?.VideoMediaFrame?.SoftwareBitmap;
if (softwareBitmap == null)
return;
try
{
int width = softwareBitmap.PixelWidth;
int height = softwareBitmap.PixelHeight;
byte[] luminance = new byte[checked(width * height)];
using (BitmapBuffer buffer =
softwareBitmap.LockBuffer(BitmapBufferAccessMode.Read))
using (IMemoryBufferReference reference = buffer.CreateReference())
{
BitmapPlaneDescription yPlane =
buffer.GetPlaneDescription(0);
if (yPlane.Width < width ||
yPlane.Height < height ||
yPlane.Stride < width ||
yPlane.StartIndex < 0)
{
throw new InvalidOperationException(
"Unexpected NV12 luminance plane layout.");
}
unsafe
{
byte* baseAddress;
uint capacity;
((IMemoryBufferByteAccess)reference)
.GetBuffer(out baseAddress, out capacity);
long requiredLength =
(long)yPlane.StartIndex +
(long)(height - 1) * yPlane.Stride +
width;
if (requiredLength > capacity)
{
throw new InvalidOperationException(
"The NV12 buffer is smaller than its plane description.");
}
for (int row = 0; row < height; row++)
{
int sourceOffset = checked(
yPlane.StartIndex + row * yPlane.Stride);
int destinationOffset = checked(row * width);
Marshal.Copy(
(IntPtr)(baseAddress + sourceOffset),
luminance,
destinationOffset,
width);
}
}
}
FrameArrived?.Invoke(
this,
new FrameArrivedEventArgs(luminance, width, height));
}
finally
{
softwareBitmap.Dispose();
}
}
}
复制公式如下:
源地址 = bufferAddress + StartIndex + row × Stride
目标地址 = outputBuffer + row × PixelWidth
复制长度 = PixelWidth
每行复制 PixelWidth 个亮度字节,随后按 Stride 定位到下一行。
如何确认问题
可以临时输出平面信息:
BitmapPlaneDescription yPlane = buffer.GetPlaneDescription(0);
Debug.WriteLine(
$"Y plane: StartIndex={yPlane.StartIndex}, " +
$"Stride={yPlane.Stride}, " +
$"Width={yPlane.Width}, " +
$"Height={yPlane.Height}");
如果在 2272×1278 分辨率下得到类似结果,说明每行末尾确实有填充:
Width=2272
Stride=2304
原代码处理完第一行后,会从偏移 2272 开始读取第二行,而第二行实际位于偏移 2304。每行都会多错开 32 字节,所以图像中会出现规律性的斜纹。
NV12 平面布局说明
NV12 通常有两个平面:
- Plane 0:完整分辨率的 Y 亮度数据,每像素 1 字节。
- Plane 1:交错排列的 UV 色度数据,水平和垂直分辨率均减半。
只读取灰度时,无须访问 UV 平面,但仍需通过 GetPlaneDescription(0) 获取 Y 平面的实际布局。Y 平面可能有行填充,两个平面之间也可能有额外偏移,因此不能直接根据 width × height 推算 UV 平面的起点。
其他需要修正的细节
计算帧率前应先转换为浮点数,否则表达式中的 Numerator / Denominator 可能先执行整数除法:
double frameRate =
format.FrameRate.Numerator /
(double)format.FrameRate.Denominator;
bool matches =
Math.Abs(frameRate - parameters.FrameRate) < Tolerance;
选定格式后还要检查 selectedFormat,以免在没有匹配格式时把 null 传给 SetFormatAsync:
var selectedFormat = preferredFormat.FirstOrDefault();
if (selectedFormat == null)
{
throw new InvalidOperationException(
"The requested NV12 camera format is not supported.");
}
await source.SetFormatAsync(selectedFormat);
OnFrameArrived 中没有使用 await,所以不必声明为 async void。如果帧到达速度超过处理速度,应尽快释放 MediaFrameReference 和 SoftwareBitmap,同时避免在回调线程中执行耗时的图像处理。
NV12 的亮度值也可能采用视频范围,黑色和白色大致对应 16 和 235,而非 0 和 255。这会影响灰度显示的对比度,但不会产生斜向条纹。
备注:内容仅供参考。
