2014-01-23 6 views
0

Я пытаюсь переписать следующий код из silverlight в wpf. найдено здесь https://slmotiondetection.codeplex.com/получить пиксели изображения в массив

моя проблема в том, что WritaeableBitmap.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

спасибо. что помогло мне –

Смежные вопросы