UWP 使用Windows.Media.FaceAnalysis.FaceDetector檢測人臉


 

話說現在檢測人臉的技術有很多。有在線AI服務,比如Megvii Face++,Microsoft Cognitive Services,Tencent AI等等。還有本地的庫實現的,比如OpenCV。

但是這些這篇文章都不討論,微軟在 .NETCore里面也提供了一種本地檢測人臉的API,那就是Windows.Media.FaceAnalysis

 

.NetCore在你新建通用UWP應用的時候,Nuget自動添加了。

 

 

那么接下來,我們在設計Xaml代碼的時候,加兩個按鈕,一個是選擇圖片,一個是檢測人臉。

再建一個Canvas控件,用來顯示圖片。

之所以用Canvas畫布,不用Image,是因為我們還需要在圖片上畫出一個矩形框,框出識別的人臉位置和大小呢。

<Grid Background="{ThemeResource ApplicationPageBackgroundThemeBrush}">
        <Grid.RowDefinitions>
            <RowDefinition Height="30"/>
            <RowDefinition/>
        </Grid.RowDefinitions>
        <Grid.ColumnDefinitions>
            <ColumnDefinition/>
            <ColumnDefinition/>
        </Grid.ColumnDefinitions>

        <Button Content="Choose Picture" Click="ChoosePicture"/>
        <Button Grid.Column="1" Content="Detect Face" Click="DetectFace"/>

        <Canvas x:Name="canvasDetected" Grid.ColumnSpan="2" Grid.Row="1"  VerticalAlignment="Stretch" HorizontalAlignment="Stretch"/>
    </Grid>

 

然后開始寫代碼,選擇圖片的邏輯很簡單,只需要選擇一個圖片,顯示到Canvas中即可。

private async void ChoosePicture(object sender, RoutedEventArgs e)
        {
            FileOpenPicker openPicker = new FileOpenPicker();
            openPicker.ViewMode = PickerViewMode.Thumbnail;
            openPicker.SuggestedStartLocation = PickerLocationId.PicturesLibrary;
            openPicker.FileTypeFilter.Add(".bmp");
            openPicker.FileTypeFilter.Add(".png");
            openPicker.FileTypeFilter.Add(".jpeg");
            openPicker.FileTypeFilter.Add(".jpg");
            StorageFile file = await openPicker.PickSingleFileAsync();
            if (file != null)
            {
                using (IRandomAccessStream strm = await file.OpenAsync(Windows.Storage.FileAccessMode.Read))
                {
                    BitmapDecoder decoder = await BitmapDecoder.CreateAsync(strm);
                    BitmapTransform transform = new BitmapTransform();
                    source = await decoder.GetSoftwareBitmapAsync();

                    WriteableBitmap displaySource = new WriteableBitmap(source.PixelWidth, source.PixelHeight);
                    source.CopyToBuffer(displaySource.PixelBuffer);

                    ImageBrush brush = new ImageBrush();
                    brush.ImageSource = displaySource;
                    brush.Stretch = Stretch.Uniform;
                    canvasDetected.Background = brush;
                    canvasDetected.Children.Clear();
                }
            }
        }

 

遇到紅色波浪線提示的,用VS自動修復功能,自動添加引用即可。

還有一個source沒有定義,不慌,反正下一步就要檢測人臉了,我們來看一看FaceDetector的定義

namespace Windows.Media.FaceAnalysis
{
    //
    // 摘要:
    //     在 SoftwareBitmap 中檢測人臉。
    [ContractVersion(typeof(UniversalApiContract), 65536)]
    [MarshalingBehavior(MarshalingType.Agile)]
    [Static(typeof(IFaceDetectorStatics), 65536, "Windows.Foundation.UniversalApiContract")]
    [Threading(ThreadingModel.Both)]
    public sealed class FaceDetector : IFaceDetector
    {
        //
        // 摘要:
        //     異步檢測提供的 SoftwareBitmap 中的人臉。
        //
        // 參數:
        //   image:
        //     要進行人臉檢測處理的圖像數據。
        //
        // 返回結果:
        //     一個異步操作,在成功完成時返回 DetectedFace 對象的列表。
        [Overload("DetectFacesAsync")]
        [RemoteAsync]
        public IAsyncOperation<IList<DetectedFace>> DetectFacesAsync(SoftwareBitmap image);
     }
}

 

 

看到沒,使用FaceDetector需要一個SoftwareBitmap,那么好了,我們定義一個私有變量SoftwareBitmap source即可。

 

 然后寫檢測的代碼,

private async void DetectFace(object sender, RoutedEventArgs e)
        {
            const BitmapPixelFormat faceDetectionPixelFormat = BitmapPixelFormat.Gray8;
            SoftwareBitmap converted;
            if (source.BitmapPixelFormat != faceDetectionPixelFormat)
            {
                converted = SoftwareBitmap.Convert(source, faceDetectionPixelFormat);
            }
            else
            {
                converted = source;
            }

            FaceDetector faceDetector = await FaceDetector.CreateAsync();
            IList<DetectedFace> detectedFaces = await faceDetector.DetectFacesAsync(converted);
            DrawBoxes(detectedFaces);  //這個功能在實際場景中使用不多,在這可以寫你的實際業務場景
        }

 

 

 畫人臉矩形:

 
         
        //這個功能在實際場景中使用不多

private
void DrawBoxes(IList<DetectedFace> detectedFaces) { if (detectedFaces != null) { //get the scaling factor double scaleWidth = source.PixelWidth / this.canvasDetected.ActualWidth; double scaleHeight = source.PixelHeight / this.canvasDetected.ActualHeight; double scalingFactor = scaleHeight > scaleWidth ? scaleHeight : scaleWidth; //get the display width of the image. double displayWidth = source.PixelWidth / scalingFactor; double displayHeight = source.PixelHeight / scalingFactor; //get the delta width/height between canvas actual width and the image display width double deltaWidth = this.canvasDetected.ActualWidth - displayWidth; double deltaHeight = this.canvasDetected.ActualHeight - displayHeight; SolidColorBrush lineBrush = new SolidColorBrush(Windows.UI.Colors.White); double lineThickness = 2.0; SolidColorBrush fillBrush = new SolidColorBrush(Windows.UI.Colors.Transparent); foreach (DetectedFace face in detectedFaces) { Rectangle box = new Rectangle(); box.Tag = face.FaceBox; //scale the box with the scaling factor box.Width = face.FaceBox.Width / scalingFactor; box.Height = face.FaceBox.Height / scalingFactor; box.Fill = fillBrush; box.Stroke = lineBrush; box.StrokeThickness = lineThickness; //set coordinate of the box in the canvas box.Margin = new Thickness((uint)(face.FaceBox.X / scalingFactor + deltaWidth / 2), (uint)(face.FaceBox.Y / scalingFactor + deltaHeight / 2), 0, 0); this.canvasDetected.Children.Add(box); } } }

 

 

 其實,像上面的DrawBoxes注釋那樣,一般用的還不算多。

我的項目都是判斷如果detectedFaces不是null的話,接下來就可以調用雲API來實現人臉搜索了,畢竟這個本地微軟的api還做不到。

下面看一下效果

 

 

 

 總結

 

微軟提供的FaceDetector還是挺實用的,畢竟可以節約我們一遍一遍像服務器發送請求檢測人臉的開支了,雖然雲API檢測人臉並不貴,face++的10000次才一塊錢。畢竟你上傳圖片,還不要帶寬資源吧。萬一碰到個網絡不好,那不是還要再請求一次。。。哈哈,折騰點。

不過這個也隨便了,看自己喜好吧。


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM