2016-04-29 53 views
2

我想將自己的自定義效果應用於圖片,因此我需要能夠訪問圖像的各個像素。使用MediaCapture我可以將CapturedPhoto.Frame作爲流或軟件位圖獲取,但我無法找到我如何編輯它們。如何從捕獲的圖像訪問/編輯像素C#

//initialize mediacapture with default camera 
var mediaCapture = new MediaCapture(); 
await mediaCapture.InitializeAsync(); 

//create low lag capture and take photo 
var lowLagCapture = await mediaCapture.PrepareLowLagPhotoCaptureAsync(ImageEncodingProperties.CreateUncompressed(MediaPixelFormat.Bgra8)); 
var capturedPhoto = await lowLagCapture.CaptureAsync(); 

capturedPhoto.Frame.AsStream() 
capturedPhoto.Frame.SoftwareBitmap 

回答

3

要訪問圖像的像素,您可以使用SoftwareBitmap。要訪問RGB顏色空間中的像素,您可以使用Bgra8顏色格式。要轉換到Bgra8使用

var softwareBitmap = SoftwareBitmap.Convert(capturedPhoto.Frame.SoftwareBitmap, BitmapPixelFormat.Bgra8, BitmapAlphaMode.Premultiplied); 

要訪問的圖像,你需要通過命名空間

[ComImport] 
[Guid("5B0D3235-4DBA-4D44-865E-8F1D0E4FD04D")] 
[InterfaceType(ComInterfaceType.InterfaceIsIUnknown)] 
unsafe interface IMemoryBufferByteAccess 
{ 
    void GetBuffer(out byte* buffer, out uint capacity); 
} 

下一頁中添加以下代碼初始化IMemoryBufferByteAccess COM接口,你將需要設置字節不安全的編譯器標誌。右鍵單擊項目 - >屬性 - >生成 - >選中允許不安全的代碼。

現在您可以直接訪問/編輯像素,如下所示。

public unsafe void editSoftwarebitmap(SoftwareBitmap softwareBitmap) 
{ 
    //create buffer 
    using (BitmapBuffer buffer = softwareBitmap.LockBuffer(BitmapBufferAccessMode.Write)) 
    { 
     using (var reference = buffer.CreateReference()) 
     { 
      byte* dataInBytes; 
      uint capacity; 
      ((IMemoryBufferByteAccess)reference).GetBuffer(out dataInBytes, out capacity); 

      //fill-in the BGRA plane 
      BitmapPlaneDescription bufferLayout = buffer.GetPlaneDescription(0); 
      for (int i = 0; i < bufferLayout.Height; i++) 
      { 
       for (int j = 0; j < bufferLayout.Width; j++) 
       { 
        //get offset of the current pixel 
        var pixelStart = bufferLayout.StartIndex + bufferLayout.Stride * i + 4 * j; 

        //get gradient value to set for blue green and red 
        byte value = (byte)((float)j/bufferLayout.Width * 255); 
        dataInBytes[pixelStart + 0] = value; //Blue 
        dataInBytes[pixelStart + 1] = value; //Green 
        dataInBytes[pixelStart + 2] = value; //Red 
        dataInBytes[pixelStart + 3] = (byte)255; //Alpha 
       } 
      } 
     } 
    } 
} 

有關更多文檔,請參閱Imaging How-To

+0

對不起,但你能解釋一下這個:dataInBytes,我們可以得到該圖像的指針地址(該圖像的起始字節進行編輯) –