2014-01-23 72 views
0

我想重写下面的代码从silverlight到wpf。这里发现https://slmotiondetection.codeplex.com/获取图像像素到阵列

我的问题是,WriterableBitmap.Pixels从wpf丢失。如何实现这一目标?我明白它是如何工作的,但我像一周前从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; 
    } 

`

回答

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); 

写一个WriteableBitmap可以通过其WritePixels方法之一来完成。

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

对于转换位为灰度图像,你可以使用一个FormatConvertedBitmap这样的:

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

谢谢。那帮助了我 –