Skip to content

Instantly share code, notes, and snippets.

@rexxiang
Created July 11, 2016 03:49
Show Gist options
  • Save rexxiang/c85da4da46acaef4b59bd2666542aa36 to your computer and use it in GitHub Desktop.
Save rexxiang/c85da4da46acaef4b59bd2666542aa36 to your computer and use it in GitHub Desktop.

Revisions

  1. rexxiang created this gist Jul 11, 2016.
    37 changes: 37 additions & 0 deletions YuvBytesToBpp24Bitmap.cs
    Original file line number Diff line number Diff line change
    @@ -0,0 +1,37 @@
    public static Bitmap YuvBytesToBpp24Bitmap(byte[] yuvBytes, int width, int height) {
    if (yuvBytes == null || yuvBytes.Length == 0) {
    return null;
    }

    const PixelFormat format = PixelFormat.Format24bppRgb;

    var image = YuvBytesToIplImage(yuvBytes, width, height);
    var bitmap = new Bitmap(image.Width, image.Height, image.WidthStep, format, image.ImageData);
    return bitmap;
    }

    public static IplImage YuvBytesToIplImage(byte[] yuvBytes, int width, int height) {
    var yuv = Mat.FromArray(yuvBytes);
    var data = yuv.Data;

    var y = new Mat(new Size(width, height), Depth.U8, 1);
    var u = new Mat(new Size(width / 2, height / 2), Depth.U8, 1);
    var v = new Mat(new Size(width / 2, height / 2), Depth.U8, 1);

    y.SetData(data, width);
    u.SetData(data + width * height, width / 2);
    v.SetData(data + (int)(width * height * 1.25), width / 2);

    var uu = new Mat(new Size(width, height), Depth.U8, 1);
    var vv = new Mat(new Size(width, height), Depth.U8, 1);
    CV.Resize(u, uu);
    CV.Resize(v, vv);

    var merge = new IplImage(new Size(width, height), IplDepth.U8, 3);
    CV.Merge(y, uu, vv, null, merge);

    var rgb = new IplImage(new Size(width, height), IplDepth.U8, 3);
    CV.CvtColor(merge, rgb, ColorConversion.YCrCb2Rgb);

    return rgb;
    }