在Winform中需要显示视频流的时候,会遇到YUV420编码的情况。思路是将YUV420的图像转换为BGR格式,然后给PictureBox控件渲染。因此可以使用OpenCvSharp库(NuGet获取)将YUV420编码的字节数组转换为BGR编码的字节数组,然后构建Image对象进行渲染。
/// <summary> /// YUV图像转换为BGR图像 /// </summary> /// <param name="yuvData">YUV格式字节数组</param> /// <param name="width">图像宽度</param> /// <param name="height">图像高度</param> /// <returns>BGR格式字节数组</returns> private static byte[] ConvertYuv2Bgr(byte[] yuvData, int width, int height) { using (var imgYuv = new Mat(height + height / 2, width, MatType.CV_8UC1, yuvData)) using (var imgDst = new Mat(height, width, MatType.CV_8UC3)) { Cv2.CvtColor(imgYuv, imgDst, ColorConversionCodes.YUV2BGR_I420, 0); return imgDst.ToBytes(); } } var bgrBytes = ConvertYuv2Bgr(yuvData, info.nWidth, info.nHeight); var stream = new MemoryStream(bgrBytes); var image = Image.FromStream(stream);