Greyscale Image from YUV420p data

Posted by fergs on Stack Overflow See other posts from Stack Overflow or by fergs
Published on 2010-03-30T07:48:31Z Indexed on 2010/03/30 7:53 UTC
Read the original article Hit count: 970

From what I have read on the internet the Y value is the luminance value and can be used to create a grey scale image. The following link: http://www.bobpowell.net/grayscale.htm, has some C# code on working out the luminance of a bitmap image :

{
  Bitmap bm = new Bitmap(source.Width,source.Height);
  for(int y=0;y<bm.Height;y++)        public Bitmap ConvertToGrayscale(Bitmap source)
  {
    for(int x=0;x<bm.Width;x++)
    {
      Color c=source.GetPixel(x,y);
      int luma = (int)(c.R*0.3 + c.G*0.59+ c.B*0.11);
      bm.SetPixel(x,y,Color.FromArgb(luma,luma,luma));
    }
  }
  return bm;
}

I have a method that returns the YUV values and have the Y data in a byte array. I have the current piece of code and it is failing on Marshal.Copy – attempted to read or write protected memory.

public Bitmap ConvertToGrayscale2(byte[] yuvData, int width, int height)
        {
            Bitmap bmp;
            IntPtr blue = IntPtr.Zero;

            int inputOffSet = 0;
            long[] pixels = new long[width * height];

            try
            {
                for (int y = 0; y < height; y++)
                {
                    int outputOffSet = y * width;
                    for (int x = 0; x < width; x++)
                    {
                        int grey = yuvData[inputOffSet + x] & 0xff;
                        unchecked
                        {
                            pixels[outputOffSet + x] = UINT_Constant | (grey * INT_Constant);
                        }
                    }

                    inputOffSet += width;
                }

                blue = Marshal.AllocCoTaskMem(pixels.Length);
                Marshal.Copy(pixels, 0, blue, pixels.Length); // fails here : Attempted to read or write protected memory


                bmp = new Bitmap(width, height, width, PixelFormat.Format24bppRgb, blue);

            }
            catch (Exception)
            {

                throw;
            }
            finally
            {
                if (blue != IntPtr.Zero)
                {
                    Marshal.FreeHGlobal(blue);
                    blue = IntPtr.Zero;
                }

            }

            return bmp;
        }

Any help would be appreciated?

© Stack Overflow or respective owner

Related posts about marshal

Related posts about greyscale