使用 OpenCV 搭配 MediaFrameReader

本文說明如何利用 OpenCV(Open Source 電腦視覺)函式庫搭配 MediaFrameReader,即時處理攝影機畫面。 此技術適用於 WinUI 3 桌面應用程式中的影像分析任務,如邊緣偵測、物件追蹤及背景減法。

先決條件

開始之前,請確定您擁有:

  • 一個 WinUI 3 桌面專案(打包或非打包)。
  • 連接到你的裝置的相容網路攝影機。
  • 安裝在你的專案中的 OpenCvSharp4 和 OpenCvSharp4.runtime.win NuGet 套件。
  • 您的應用程式已宣告攝影機存取權限,詳見 「宣告攝影機存取權限」。

要安裝 .NET 的 OpenCV:

dotnet add package OpenCvSharp4
dotnet add package OpenCvSharp4.runtime.win

宣告攝影機存取權

在你的應用程式可以使用 MediaFrameReader 從網路攝影機讀取影格之前,你必須宣告你的應用程式會使用攝影機。 你怎麼做這取決於你的應用程式是否有被打包。

  • 套裝應用程式:將裝置功能加入webcam:Package.appxmanifest

    <Capabilities>
        <DeviceCapability Name="webcam" />
    </Capabilities>
    
  • 未封裝應用程式:未封裝應用程式沒有套件清單,因此無法宣告。 未封裝應用程式的相機存取則是由使用者裝置上「讓>」設定中「隱私與安全>相機」的設定來控制。

在這兩種情況下,使用者仍可在作業系統層級拒絕攝影機存取。 在初始化攝影機前,請檢查存取權限,並優雅地處理被拒絕的案件,詳見「處理 Windows 攝影機隱私設定」的說明。

設定 MediaFrameReader

首先,建立一個 MediaCapture 實例並找到彩色影片畫面來源。 接著建立一個 MediaFrameReader 來接收影格:

using System.Linq;
using Windows.Media.Capture;
using Windows.Media.Capture.Frames;
using Windows.Graphics.Imaging;

private MediaCapture _mediaCapture;
private MediaFrameReader _frameReader;

private async Task InitializeFrameReaderAsync()
{
    // Find a color video source group
    var sourceGroups =
        await MediaFrameSourceGroup.FindAllAsync();

    var selectedGroup = sourceGroups.FirstOrDefault(group =>
        group.SourceInfos.Any(info =>
            info.MediaStreamType == MediaStreamType.VideoPreview &&
            info.SourceKind == MediaFrameSourceKind.Color));

    if (selectedGroup == null)
    {
        // No suitable camera found
        return;
    }

    _mediaCapture = new MediaCapture();
    var settings = new MediaCaptureInitializationSettings
    {
        SourceGroup = selectedGroup,
        MemoryPreference = MediaCaptureMemoryPreference.Cpu,
        StreamingCaptureMode = StreamingCaptureMode.Video,
    };

    await _mediaCapture.InitializeAsync(settings);

    // Find the color video source
    var colorSource = _mediaCapture.FrameSources
        .Values.FirstOrDefault(source =>
            source.Info.SourceKind == MediaFrameSourceKind.Color);

    if (colorSource == null)
    {
        return;
    }

    _frameReader =
        await _mediaCapture.CreateFrameReaderAsync(colorSource);
    _frameReader.FrameArrived += FrameReader_FrameArrived;

    await _frameReader.StartAsync();
}

Important

將 MemoryPreference 設為 Cpu,以便影格會以 SoftwareBitmap 物件的形式傳送,讓您可直接從受控程式碼存取。

OpenCV 的程序框架

在 FrameArrived 事件處理常式中,從影格取得 SoftwareBitmap,並將其轉換為 OpenCV Mat 以進行處理。 你需要 IMemoryBufferByteAccess COM 介面來存取原始像素資料。 將以下定義加入您的專案中:

using System.Runtime.InteropServices;

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

接著處理這些影格:

using OpenCvSharp;

private void FrameReader_FrameArrived(
    MediaFrameReader sender,
    MediaFrameArrivedEventArgs args)
{
    using var frameRef =
        sender.TryAcquireLatestFrame();
    if (frameRef == null) return;

    var bitmap = frameRef.VideoMediaFrame?.SoftwareBitmap;
    if (bitmap == null) return;

    // Convert to Bgra8 format if needed
    SoftwareBitmap convertedBitmap = null;
    if (bitmap.BitmapPixelFormat != BitmapPixelFormat.Bgra8)
    {
        convertedBitmap = SoftwareBitmap.Convert(
            bitmap, BitmapPixelFormat.Bgra8);
        bitmap = convertedBitmap;
    }

    // Access the pixel buffer
    using var buffer = bitmap.LockBuffer(
        BitmapBufferAccessMode.Read);
    using var reference =
        buffer.CreateReference();

    // Get the buffer as a byte array via
    // IMemoryBufferByteAccess
    unsafe
    {
        ((IMemoryBufferByteAccess)reference).GetBuffer(
            out byte* dataInBytes,
            out uint capacity);

        // Use stride from the buffer plane description
        // to avoid corrupted images from padding
        var desc = buffer.GetPlaneDescription(0);
        using var mat = Mat.FromPixelData(
            desc.Height, desc.Width,
            MatType.CV_8UC4,
            (IntPtr)dataInBytes,
            desc.Stride);

        // Process the frame with OpenCV
        ProcessFrame(mat);
    }

    // Dispose the converted bitmap if we created one
    convertedBitmap?.Dispose();
}

Note

不安全程式碼區塊使用 IMemoryBufferByteAccess 直接指向點陣資料。 你需要在專案設定中啟用不安全的程式碼,方法是將 <AllowUnsafeBlocks>true</AllowUnsafeBlocks> 新增至 .csproj 檔案中。

套用 OpenCV 運算

你可以將任何 OpenCV 影像處理操作套用到 Mat。 這裡有一個應用 Canny 邊緣偵測的範例:

private SoftwareBitmap _processedBitmap;

private void ProcessFrame(Mat inputMat)
{
    // Convert to grayscale for edge detection
    using var grayMat = new Mat();
    Cv2.CvtColor(inputMat, grayMat, ColorConversionCodes.BGRA2GRAY);

    // Apply Canny edge detection
    using var edges = new Mat();
    Cv2.Canny(grayMat, edges, 50, 200);

    // Convert back to BGRA for display
    using var outputMat = new Mat();
    Cv2.CvtColor(edges, outputMat, ColorConversionCodes.GRAY2BGRA);

    // Create a SoftwareBitmap from the processed Mat
    var processedBitmap = new SoftwareBitmap(
        BitmapPixelFormat.Bgra8,
        outputMat.Width,
        outputMat.Height,
        BitmapAlphaMode.Premultiplied);

    using var destBuffer = processedBitmap.LockBuffer(
        BitmapBufferAccessMode.Write);
    using var destRef = destBuffer.CreateReference();

    unsafe
    {
        ((IMemoryBufferByteAccess)destRef).GetBuffer(
            out byte* destBytes, out uint destCapacity);

        // Copy the processed data to the SoftwareBitmap row by row.
        // outputMat.Step() and desc.Stride can differ (for example,
        // because of OpenCV's own row alignment), so a single bulk
        // copy across the whole buffer can corrupt the image. Copying
        // one row at a time, using each buffer's own stride, avoids
        // that mismatch.
        var desc = destBuffer.GetPlaneDescription(0);
        int rowBytes = outputMat.Width * outputMat.ElemSize();
        byte* sourceRow = (byte*)outputMat.Data.ToPointer();
        byte* destRow = destBytes;

        for (int row = 0; row < outputMat.Height; row++)
        {
            System.Buffer.MemoryCopy(
                sourceRow,
                destRow,
                destCapacity - (uint)(row * desc.Stride),
                (uint)rowBytes);

            sourceRow += outputMat.Step();
            destRow += desc.Stride;
        }
    }

    // Update the UI with the processed frame
    DispatcherQueue.TryEnqueue(async () =>
    {
        var source =
            new Microsoft.UI.Xaml.Media.Imaging
                .SoftwareBitmapSource();
        await source.SetBitmapAsync(processedBitmap);
        ProcessedImage.Source = source;

        _processedBitmap?.Dispose();
        _processedBitmap = processedBitmap;
    });
}

在你的 XAML 中新增 Image 一個控制項來顯示已處理的幀:

<Image x:Name="ProcessedImage" Stretch="Uniform" />

清理資源

完成後停止幀讀取器並釋放資源:

private async Task CleanupAsync()
{
    if (_frameReader != null)
    {
        _frameReader.FrameArrived -= FrameReader_FrameArrived;
        await _frameReader.StopAsync();
        _frameReader.Dispose();
    }

    _mediaCapture?.Dispose();
    _processedBitmap?.Dispose();
}