UWP通過機器學習載入ONNX進行表情識別

来源:https://www.cnblogs.com/GreenShade/archive/2020/02/07/12275048.html
-Advertisement-
Play Games

首先我們先來說說這個ONNX ONNX是一種針對機器學習所設計的開放式的文件格式,用於存儲訓練好的模型。它使得不同的人工智慧框架(如Pytorch, MXNet)可以採用相同格式存儲模型數據並交互。 ONNX的規範及代碼主要由微軟,亞馬遜 ,Facebook 和 IBM 等公司共同開發,以開放源代碼 ...


首先我們先來說說這個ONNX

ONNX是一種針對機器學習所設計的開放式的文件格式,用於存儲訓練好的模型。它使得不同的人工智慧框架(如Pytorch, MXNet)可以採用相同格式存儲模型數據並交互。 ONNX的規範及代碼主要由微軟,亞馬遜 ,Facebook 和 IBM 等公司共同開發,以開放源代碼的方式托管在Github上。目前官方支持載入ONNX模型併進行推理的深度學習框架有: Caffe2, PyTorch, MXNet,ML.NET,TensorRT 和 Microsoft CNTK,並且 TensorFlow 也非官方的支持ONNX。---維基百科

看了上面的引用 大家應該知道了 這個其實是個文件格式用來存儲訓練好的模型,所以我這篇帖子既然是做表情識別那肯定是需要有個能識別表情的模型。有了這個模型我們就可以根據圖片上的人物,進行表情的識別判斷了。

剛好微軟對機器學習這塊也挺上心的,所以我也趁著疫情比較閑,就來學習學習了。UWP的機器學習的api微軟已經切成正式了,所以大家可以放心使用。

這就是uwp api文檔 開頭就是AI的

我其實是個小白 所以我就直接拿官方的一個demo的簡化版來進行講解了,官方的demo演示如下。

這個app就是通過攝像頭讀取每一幀 進行和模型匹配得出結果的

下麵是機器學習的微軟的github地址

Emoji8的git地址

我今天要說的就是這個demo的簡化代碼大致運行流程

下麵是項目結構圖

我把官方項目簡化了 所以只留下了識別後的文本移除了一些依賴的庫

核心代碼在IntelligenceService類里的Current_SoftwareBitmapFrameCaptured方法里

 private async void Current_SoftwareBitmapFrameCaptured(object sender, SoftwareBitmapEventArgs e)
        {
            Debug.WriteLine("FrameCaptured");
            Debug.WriteLine($"Frame evaluation started {DateTime.Now}" );
            if (e.SoftwareBitmap != null)
            {
                BitmapPixelFormat bpf = e.SoftwareBitmap.BitmapPixelFormat;

                var uncroppedBitmap = SoftwareBitmap.Convert(e.SoftwareBitmap, BitmapPixelFormat.Nv12);
                var faces = await _faceDetector.DetectFacesAsync(uncroppedBitmap);
                if (faces.Count > 0)
                {
                    //crop image to focus on face portion
                    var faceBox = faces[0].FaceBox;
                    VideoFrame inputFrame = VideoFrame.CreateWithSoftwareBitmap(e.SoftwareBitmap);
                    VideoFrame tmp = null;
                    tmp = new VideoFrame(e.SoftwareBitmap.BitmapPixelFormat, (int)(faceBox.Width + faceBox.Width % 2) - 2, (int)(faceBox.Height + faceBox.Height % 2) - 2);
                    await inputFrame.CopyToAsync(tmp, faceBox, null);

                    //crop image to fit model input requirements
                    VideoFrame croppedInputImage = new VideoFrame(BitmapPixelFormat.Gray8, (int)_inputImageDescriptor.Shape[3], (int)_inputImageDescriptor.Shape[2]);
                    var srcBounds = GetCropBounds(
                        tmp.SoftwareBitmap.PixelWidth,
                        tmp.SoftwareBitmap.PixelHeight,
                        croppedInputImage.SoftwareBitmap.PixelWidth,
                        croppedInputImage.SoftwareBitmap.PixelHeight);
                    await tmp.CopyToAsync(croppedInputImage, srcBounds, null);

                    ImageFeatureValue imageTensor = ImageFeatureValue.CreateFromVideoFrame(croppedInputImage);

                    _binding = new LearningModelBinding(_session);

                    TensorFloat outputTensor = TensorFloat.Create(_outputTensorDescriptor.Shape);
                    List<float> _outputVariableList = new List<float>();

                    // Bind inputs + outputs
                    _binding.Bind(_inputImageDescriptor.Name, imageTensor);
                    _binding.Bind(_outputTensorDescriptor.Name, outputTensor);

                    // Evaluate results
                    var results = await _session.EvaluateAsync(_binding, new Guid().ToString());

                    Debug.WriteLine("ResultsEvaluated: " + results.ToString());

                    var outputTensorList = outputTensor.GetAsVectorView();
                    var resultsList = new List<float>(outputTensorList.Count);
                    for (int i = 0; i < outputTensorList.Count; i++)
                    {
                        resultsList.Add(outputTensorList[i]);
                    }

                    var softMaxexOutputs = SoftMax(resultsList);

                    double maxProb = 0;
                    int maxIndex = 0;

                    // Comb through the evaluation results
                    for (int i = 0; i < Constants.POTENTIAL_EMOJI_NAME_LIST.Count(); i++)
                    {
                        // Record the dominant emotion probability & its location
                        if (softMaxexOutputs[i] > maxProb)
                        {
                            maxIndex = i;
                            maxProb = softMaxexOutputs[i];
                        }                      
                    }

                    Debug.WriteLine($"Probability = {maxProb}, Threshold set to = {Constants.CLASSIFICATION_CERTAINTY_THRESHOLD}, Emotion = {Constants.POTENTIAL_EMOJI_NAME_LIST[maxIndex]}");

                    // For evaluations run on the MainPage, update the emoji carousel
                    if (maxProb >= Constants.CLASSIFICATION_CERTAINTY_THRESHOLD)
                    {
                        Debug.WriteLine("first page emoji should start to update");
                        IntelligenceServiceEmotionClassified?.Invoke(this, new ClassifiedEmojiEventArgs(CurrentEmojis._emojis.Emojis[maxIndex]));
                    }

                    // Dispose of resources
                    if (e.SoftwareBitmap != null)
                    {
                        e.SoftwareBitmap.Dispose();
                        e.SoftwareBitmap = null;
                    }
                }
            }
            IntelligenceServiceProcessingCompleted?.Invoke(this, null);
            Debug.WriteLine($"Frame evaluation finished {DateTime.Now}");
        }

        //WinML team function
        private List<float> SoftMax(List<float> inputs)
        {
            List<float> inputsExp = new List<float>();
            float inputsExpSum = 0;
            for (int i = 0; i < inputs.Count; i++)
            {
                var input = inputs[i];
                inputsExp.Add((float)Math.Exp(input));
                inputsExpSum += inputsExp[i];
            }
            inputsExpSum = inputsExpSum == 0 ? 1 : inputsExpSum;
            for (int i = 0; i < inputs.Count; i++)
            {
                inputsExp[i] /= inputsExpSum;
            }
            return inputsExp;
        }

        public static BitmapBounds GetCropBounds(int srcWidth, int srcHeight, int targetWidth, int targetHeight)
        {
            var modelHeight = targetHeight;
            var modelWidth = targetWidth;
            BitmapBounds bounds = new BitmapBounds();
            // we need to recalculate the crop bounds in order to correctly center-crop the input image
            float flRequiredAspectRatio = (float)modelWidth / modelHeight;

            if (flRequiredAspectRatio * srcHeight > (float)srcWidth)
            {
                // clip on the y axis
                bounds.Height = (uint)Math.Min((srcWidth / flRequiredAspectRatio + 0.5f), srcHeight);
                bounds.Width = (uint)srcWidth;
                bounds.X = 0;
                bounds.Y = (uint)(srcHeight - bounds.Height) / 2;
            }
            else // clip on the x axis
            {
                bounds.Width = (uint)Math.Min((flRequiredAspectRatio * srcHeight + 0.5f), srcWidth);
                bounds.Height = (uint)srcHeight;
                bounds.X = (uint)(srcWidth - bounds.Width) / 2; ;
                bounds.Y = 0;
            }
            return bounds;
        }

感興趣的朋友可以把官方的代碼和我的代碼都克隆下來看一看,玩一玩。

我的簡化版的代碼 地址如下

簡化版表情識別代碼地址

特別感謝 Windows Community Toolkit Sample App提供的攝像頭輔助類

商店搜索 Windows Community Toolkit Sample App就能下載

講的不好的地方 希望大家給與批評


您的分享是我們最大的動力!

-Advertisement-
Play Games
更多相關文章
  • notepad中運行python cmd /k python "$(FULL_CURRENT_PATH)" & ECHO. & PAUSE & EXIT notepad中運行python kALI 用: sudo apt get install ttf wqy zenhei kali安裝後出現亂碼 ...
  • 在MainModule里 Design 模式 1]RecallLastTheme 設為True 2]Theme選一個皮膚 總共有 classicgraycrispneptunetritontriton.modifiedariagraphite 8個預設皮膚 uses uniStrUtils, pro ...
  • SpringBoot官方不推薦使用jsp,因為jsp不好發揮SpringBoot的特性。官方推薦使用模板引擎代替jsp,現在很多公司都使用FreeMarker來作為SpringBoot的視圖。 SpringBoot對動態頁面的支持很好,為多種模板引擎提供了預設配置,常用的有: Thymeleaf F ...
  • Lamda表達式學習筆記一 一、Lamda語法詮釋 三傻大鬧寶萊塢的主人公蘭徹說的一句話讓我映像深刻:用簡單的語言來表達同樣的意 我並不是說書上的定義怎麼怎麼不對,而是應該理解書本上的定義,並用簡單的話語描述! 那麼正題來了,lamda表達式是什麼? 定義:lamda表達式是一個可傳遞的代碼塊,可以 ...
  • 1.單調隊列簡介: 單調隊列是一種數據結構,類似如單調棧,但裡面的元素必須在一個區間內,如果“過時”就要出隊。所以,單調隊列可以在兩端進行出隊,但只能再隊尾入隊。按此性質,傳統的隊列已無法滿足需求,需要使用雙端隊列,再C++的STL里,雙端隊列定義在deque里: #include <deque> ...
  • 效果圖: 左邊的樹 的樹結點 ,通過 結點名 與 右 側TabSheet名 一致時,顯示 相關頁面。 這是相關 源代碼 procedure TMainForm.UniFormCreate(Sender: TObject); var I: Integer; begin for I := UniPage ...
  • 壁紙的選擇其實很大程度上能看出電腦主人的內心世界,有的人喜歡風景,有的人喜歡星空,有的人喜歡美女,有的人喜歡動物。 ...
  • 前言 之前終於在Linux上部署好了.NetCore站點,但是這個站點非常“脆弱”。當我的ssh連接關閉或者我想在當前連接執行其他命令時候就必須關閉dotnet站點的執行程式。這顯然不是我想要達到的效果,還好知道有所謂的守護進程這個東西,大多數人都是推薦採取Supervisor來進行Linux上的應 ...
一周排行
    -Advertisement-
    Play Games
  • 前言 在我們開發過程中基本上不可或缺的用到一些敏感機密數據,比如SQL伺服器的連接串或者是OAuth2的Secret等,這些敏感數據在代碼中是不太安全的,我們不應該在源代碼中存儲密碼和其他的敏感數據,一種推薦的方式是通過Asp.Net Core的機密管理器。 機密管理器 在 ASP.NET Core ...
  • 新改進提供的Taurus Rpc 功能,可以簡化微服務間的調用,同時可以不用再手動輸出模塊名稱,或調用路徑,包括負載均衡,這一切,由框架實現並提供了。新的Taurus Rpc 功能,將使得服務間的調用,更加輕鬆、簡約、高效。 ...
  • 順序棧的介面程式 目錄順序棧的介面程式頭文件創建順序棧入棧出棧利用棧將10進位轉16進位數驗證 頭文件 #include <stdio.h> #include <stdbool.h> #include <stdlib.h> 創建順序棧 // 指的是順序棧中的元素的數據類型,用戶可以根據需要進行修改 ...
  • 前言 整理這個官方翻譯的系列,原因是網上大部分的 tomcat 版本比較舊,此版本為 v11 最新的版本。 開源項目 從零手寫實現 tomcat minicat 別稱【嗅虎】心有猛虎,輕嗅薔薇。 系列文章 web server apache tomcat11-01-官方文檔入門介紹 web serv ...
  • C總結與剖析:關鍵字篇 -- <<C語言深度解剖>> 目錄C總結與剖析:關鍵字篇 -- <<C語言深度解剖>>程式的本質:二進位文件變數1.變數:記憶體上的某個位置開闢的空間2.變數的初始化3.為什麼要有變數4.局部變數與全局變數5.變數的大小由類型決定6.任何一個變數,記憶體賦值都是從低地址開始往高地 ...
  • 如果讓你來做一個有狀態流式應用的故障恢復,你會如何來做呢? 單機和多機會遇到什麼不同的問題? Flink Checkpoint 是做什麼用的?原理是什麼? ...
  • C++ 多級繼承 多級繼承是一種面向對象編程(OOP)特性,允許一個類從多個基類繼承屬性和方法。它使代碼更易於組織和維護,並促進代碼重用。 多級繼承的語法 在 C++ 中,使用 : 符號來指定繼承關係。多級繼承的語法如下: class DerivedClass : public BaseClass1 ...
  • 前言 什麼是SpringCloud? Spring Cloud 是一系列框架的有序集合,它利用 Spring Boot 的開發便利性簡化了分散式系統的開發,比如服務註冊、服務發現、網關、路由、鏈路追蹤等。Spring Cloud 並不是重覆造輪子,而是將市面上開發得比較好的模塊集成進去,進行封裝,從 ...
  • class_template 類模板和函數模板的定義和使用類似,我們已經進行了介紹。有時,有兩個或多個類,其功能是相同的,僅僅是數據類型不同。類模板用於實現類所需數據的類型參數化 template<class NameType, class AgeType> class Person { publi ...
  • 目錄system v IPC簡介共用記憶體需要用到的函數介面shmget函數--獲取對象IDshmat函數--獲得映射空間shmctl函數--釋放資源共用記憶體實現思路註意 system v IPC簡介 消息隊列、共用記憶體和信號量統稱為system v IPC(進程間通信機制),V是羅馬數字5,是UNI ...