将图像像素转换为数组

时间:2014-01-23 08:34:58

标签: c# wpf silverlight

我正在尝试将以下代码重写为silverlight到wpf。在这里找到https://slmotiondetection.codeplex.com/

我的问题是wpf缺少WritaeableBitmap.Pixels。怎么实现呢?我明白它是如何工作的,但我开始使用C#就像一周前一样。

你能指点我正确的方向吗?

    public WriteableBitmap GetMotionBitmap(WriteableBitmap current)
    {
        if (_previousGrayPixels != null && _previousGrayPixels.Length > 0)
        {
            WriteableBitmap motionBmp = new WriteableBitmap(current.PixelWidth, current.PixelHeight);

            int[] motionPixels = motionBmp.Pixels;
            int[] currentPixels = current.Pixels;
            int[] currentGrayPixels = ToGrayscale(current).Pixels;

            for (int index = 0; index < current.Pixels.Length; index++)
            {
                byte previousGrayPixel = BitConverter.GetBytes(_previousGrayPixels[index])[0];
                byte currentGrayPixel = BitConverter.GetBytes(currentGrayPixels[index])[0];

                if (Math.Abs(previousGrayPixel - currentGrayPixel) > Threshold)
                {
                    motionPixels[index] = _highlightColor;
                }
                else
                {
                    motionPixels[index] = currentPixels[index];
                }
            }

            _previousGrayPixels = currentGrayPixels;

            return motionBmp;
        }
        else
        {
            _previousGrayPixels = ToGrayscale(current).Pixels;

            return current;
        }
    }
    public WriteableBitmap ToGrayscale(WriteableBitmap source)
    {
        WriteableBitmap gray = new WriteableBitmap(source.PixelWidth, source.PixelHeight);

        int[] grayPixels = gray.Pixels;
        int[] sourcePixels = source.Pixels;

        for (int index = 0; index < sourcePixels.Length; index++)
        {
            int pixel = sourcePixels[index];

            byte[] pixelBytes = BitConverter.GetBytes(pixel);
            byte grayPixel = (byte)(0.3 * pixelBytes[2] + 0.59 * pixelBytes[1] + 0.11 * pixelBytes[0]);
            pixelBytes[0] = pixelBytes[1] = pixelBytes[2] = grayPixel;

            grayPixels[index] = BitConverter.ToInt32(pixelBytes, 0);
        }

        return gray;
    }

`

1 个答案:

答案 0 :(得分:0)

为了获取位图的原始像素数据,您可以使用BitmapSource.CopyPixels方法之一,例如像这样:

var bytesPerPixel = (source.Format.BitsPerPixel + 7) / 8;
var stride = source.PixelWidth * bytesPerPixel;
var bufferSize = source.PixelHeight * stride;
var buffer = new byte[bufferSize];
source.CopyPixels(buffer, stride, 0);

可以通过WritePixels方法之一写入WriteableBitmap

或者,您可以通过WriteableBitmap的BackBuffer属性访问位图缓冲区。

要将位图转换为灰度,您可以使用FormatConvertedBitmap,如下所示:

var grayscaleBitmap = new FormatConvertedBitmap(source, PixelFormats.Gray8, null, 0d);