There are a broad set of scenarios that are enabled by making calls into the intelligent cloud-services offered by Cognitive Services around vision, speech, knowledge, search and language.

I’ve written quite a lot about those services in the past on this blog and I showed them at events and in use on the Context show that I used to make for Channel 9 around ever more personal and contextual computing.

In the show, we often talked about what could be done in the cloud alongside what might be done locally on a device and specifically we looked at UWP (i.e. on device) support for speech and facial detection and we dug into using depth cameras and runtimes like the Intel RealSense cameras and Kinect sensors for face, hand and body tracking. Some of those ‘special camera’ capabilities have most recently been surfaced again by Project Gesture (formerly ‘Prague’) and I’ve written about some of that too.

I’m interested in these types of technologies and, against that backdrop, I was very excited to see the announcement of the;

which brings to the UWP the capability to run pre-trained learning models inside an app running on Windows devices including (as the blog post that I referenced says) on HoloLens and IoT where you can think of a tonne of potential scenarios. I’m particularly keen to think about this on HoloLens where the device is making decisions around the user’s context in near-real-time and so being able to make low-latency calls for intelligence is likely to be very powerful.

The announcement was also quite timely for me as recently I’d got a bit frustrated ( !) around the UWP’s lack of support for this type of workload – a little background …

Recent UK University Hacks on Cognitive Services

I took part in a couple of hack events at UK universities in the past couple of months that were themed around cognitive services and had a great time watching and helping students hack on the services and especially the vision services.

As part of preparing for those hacks, I made use of the “Custom Vision” service for image classification for the first time;

and I found it to be a really accessible service to make use of and I very quickly managed to build an image classification model which I trained over a number of iterations to differentiate between pictures which contained either dachshund dogs, ponies or some other type of dog although I didn’t train on too many non – dachshunds and so the model is a little weak in that area.

Here’s the portal where I have my dachshund recognition project going on;

and it works really well and I found it very easy to put together and you could put together your own classifier by following the tutorial here;

and as part of the hack I watched a lot of participating students make use of the custom vision service and then realise that they wanted this functionality available on their device rather than just in the cloud and they followed the guidance here;

to take the model that had been produced and export it so that they could make use of it locally inside apps running on Android or iOS via the export function;

and my frustration in looking at these pieces was that I had absolutely no idea how I would export one of these models and use it within an app running on the Universal Windows Platform.

Naturally, it’s easy to understand why iOS and Android support was added here but I was really pleased to see that announcement around Windows ML and I thought that I’d try it out by taking my existing dachshund classification model built and trained in the cloud and seeing if I could run it against a video stream inside of a Windows 10 UWP app.

Towards that end, I produced a new iteration of my model trained on the “General (compact) domain” so that it could be exported;

and then I used the “Export” menu to save it to my desktop in CoreML format named dachshund.mlmodel.

Checking out the Docs

I had a good look through the documentation around Windows Machine Learning here;

and set about trying to get the right bits of software together to see if I could make an app.

Getting the Right Bits

Operating System and SDK

At the time of writing, I’m running Windows 10 Fall Creators Update (16299) as my main operating system and support for these new Windows ML capabilities are coming in the next update which is in preview right now.

Consequently, I had some work to do to get the right OS and SDKs;

I moved a machine to the Windows Insider Preview 17115.1 via Windows Update

I grabbed the Windows 10 SDK 17110 Preview from the Insiders site.

Python and Machine Learning

I didn’t have an Python installation on the machine in question so I went and grabbed Python 2.7 from https://www.python.org/. I did initially try 3.6 but had some problems with scripts on that and, as a non-Python person, I came to the conclusion that the best plan might be to try 2.7 which did seem to work for me.

I knew that I need to convert my model from CoreML to ONNX and so I followed the document here;

to set about that process and that involved doing some pip installs and, specfically, for me I ended up running;

pip install coremltools pip install onnxmltools pip install winmltools

and that seemed to give me all that I needed to try and convert my model.

Converting the Model to ONNX

Just as the docs described, I ended up running these commands to do that conversion in a python environment;



from coremltools.models.utils import load_spec

from winmltools import convert_coreml from winmltools.utils import save_model model_coreml = load_spec(‘c:\users\mtaul\desktop\dachshunds.mlmodel’) model_onnx = convert_coreml(model_coreml) save_model (model_onnx, ‘c:\users\mtaul\desktop\dachshunds.onnx’)

and that all seemed to work quite nicely. I also took a look at my original model_coreml.description which gave me;

input {

name: “data”

type {

imageType {

width: 227

height: 227

colorSpace: BGR

}

}

}

output {

name: “loss”

type {

dictionaryType {

stringKeyType {

}

}

}

}

output {

name: “classLabel”

type {

stringType {

}

}

}

predictedFeatureName: “classLabel”

predictedProbabilitiesName: “loss”

which seemed reasonable but I’m not really qualified to know whether it was exactly right or not – the mechanics of these models are a bit beyond me at the time of writing

Having converted my model, though, I thought that I’d see if I could write some code against it.

Generating Code

I’d read about a code generation step in the document here;

and so I tried to use the mlgen tool on my .onnx model to generate some code. This was pretty easy and I just ran the command line;

“c:\Program Files (x86)\Windows Kits\10\bin\10.0.17110.0\x86\mlgen.exe” -i dachshunds.onnx -l CS -n “dachshunds.model” -o dachshunds.cs

and it spat out some C# code (it also does CPPCX) which is fairly short and which you could fairly easily construct yourself by looking at the types in the Windows.AI.MachineLearning.Preview namespace.

The C# code contained some machine generated names and so I replaced those and this is the code which I ended up with;

namespace daschunds.model { using System; using System.Collections.Generic; using System.Threading.Tasks; using Windows.AI.MachineLearning.Preview; using Windows.Media; using Windows.Storage; // MIKET: I renamed the auto generated long number class names to be 'Daschund' // to make it easier for me as a human to deal with them 🙂 public sealed class DacshundModelInput { public VideoFrame data { get; set; } } public sealed class DacshundModelOutput { public IList<string> classLabel { get; set; } public IDictionary<string, float> loss { get; set; } public DacshundModelOutput() { this.classLabel = new List<string>(); this.loss = new Dictionary<string, float>(); // MIKET: I added these 3 lines of code here after spending *quite some time* 🙂 // Trying to debug why I was getting a binding excption at the point in the // code below where the call to LearningModelBindingPreview.Bind is called // with the parameters ("loss", output.loss) where output.loss would be // an empty Dictionary<string,float>. // // The exception would be // "The binding is incomplete or does not match the input/output description. (Exception from HRESULT: 0x88900002)" // And I couldn't find symbols for Windows.AI.MachineLearning.Preview to debug it. // So...this could be wrong but it works for me and the 3 values here correspond // to the 3 classifications that my classifier produces. // this.loss.Add("daschund", float.NaN); this.loss.Add("dog", float.NaN); this.loss.Add("pony", float.NaN); } } public sealed class DacshundModel { private LearningModelPreview learningModel; public static async Task<DacshundModel> CreateDaschundModel(StorageFile file) { LearningModelPreview learningModel = await LearningModelPreview.LoadModelFromStorageFileAsync(file); DacshundModel model = new DacshundModel(); model.learningModel = learningModel; return model; } public async Task<DacshundModelOutput> EvaluateAsync(DacshundModelInput input) { DacshundModelOutput output = new DacshundModelOutput(); LearningModelBindingPreview binding = new LearningModelBindingPreview(learningModel); binding.Bind("data", input.data); binding.Bind("classLabel", output.classLabel); // MIKET: this generated line caused me trouble. See MIKET comment above. binding.Bind("loss", output.loss); LearningModelEvaluationResultPreview evalResult = await learningModel.EvaluateAsync(binding, string.Empty); return output; } } }

There’s a big comment in that code where I changed what had been generated for me. In short, I found that my model seems to take an input parameter here of type VideoFrame and it seems to produce output parameters of two ‘shapes’;

List<string> called “classLabel”

called Dictionary<string,float> called “loss”

I spent quite a bit of time debugging an exception that I got by passing an empty Dictionary<string,float> as the variable called “loss” as I would see an exception thrown from the call to LearningModelBindingPreview.Bind() saying that the “binding is incomplete”.

It took a while but I finally figured out that I was supposed to pass a Dictionary<string,float> with some entries already in it and you’ll notice in the code above that I pass in 3 floats which I think are related to the 3 tags that my model can categorise against – namely dachshunds, dogs and pony. I’m not at all sure that this is 100% right but it got me past that exception so I went with it

With that, I had some generated code that I thought I could build into an app.

Making a ‘Hello World’ App

I made a very simple UWP app targeting SDK 17110 and made a UI which had a few TextBlocks and a CaptureElement within it.

<Page x:Class="App1.MainPage" xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation" xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml" xmlns:local="using:App1" xmlns:d="http://schemas.microsoft.com/expression/blend/2008" xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006" mc:Ignorable="d"> <Grid Background="{ThemeResource ApplicationPageBackgroundThemeBrush}"> <CaptureElement x:Name="captureElement"/> <StackPanel HorizontalAlignment="Center" VerticalAlignment="Bottom"> <StackPanel.Resources> <Style TargetType="TextBlock"> <Setter Property="Foreground" Value="White"/> <Setter Property="FontSize" Value="18"/> <Setter Property="Margin" Value="5"/> </Style> </StackPanel.Resources> <TextBlock Text="Category " HorizontalTextAlignment="Center"><Run Text="{x:Bind Category,Mode=OneWay}"/></TextBlock> <StackPanel Orientation="Horizontal" HorizontalAlignment="Center"> <TextBlock Text="Dacshund "><Run Text="{x:Bind Dacshund,Mode=OneWay}"/></TextBlock> <TextBlock Text="Dog "><Run Text="{x:Bind Dog,Mode=OneWay}"/></TextBlock> <TextBlock Text="Pony "><Run Text="{x:Bind Pony,Mode=OneWay}"/></TextBlock> </StackPanel> </StackPanel> </Grid> </Page>

and then I wrote some code which would get hold of a camera on the device (I went for the back panel camera), wire it up to the CaptureElement in the UI and also to make use of a MediaFrameReader to get preview video frames off the camera which I’m hoping to run through the classification model.

That code is here – there’s some discussion to come in a moment about the RESIZE constant;

//#define RESIZE namespace App1 { using daschunds.model; using System; using System.Diagnostics; using System.IO; using System.Linq; using System.Runtime.InteropServices; using System.Threading; using System.Threading.Tasks; using Windows.Devices.Enumeration; using Windows.Graphics.Imaging; using Windows.Media.Capture; using Windows.Media.Capture.Frames; using Windows.Media.Devices; using Windows.Storage; using Windows.Storage.Streams; using Windows.UI.Xaml; using Windows.UI.Xaml.Controls; using Windows.UI.Xaml.Media.Imaging; using Windows.Media; using System.ComponentModel; using System.Runtime.CompilerServices; using Windows.UI.Core; using System.Runtime.InteropServices.WindowsRuntime; public sealed partial class MainPage : Page, INotifyPropertyChanged { public event PropertyChangedEventHandler PropertyChanged; public MainPage() { this.InitializeComponent(); this.inputData = new DacshundModelInput(); this.Loaded += OnLoaded; } public string Dog { get => this.dog; set => this.SetProperty(ref this.dog, value); } string dog; public string Pony { get => this.pony; set => this.SetProperty(ref this.pony, value); } string pony; public string Dacshund { get => this.daschund; set => this.SetProperty(ref this.daschund, value); } string daschund; public string Category { get => this.category; set => this.SetProperty(ref this.category, value); } string category; async Task LoadModelAsync() { var file = await StorageFile.GetFileFromApplicationUriAsync( new Uri("ms-appx:///Model/daschunds.onnx")); this.learningModel = await DacshundModel.CreateDaschundModel(file); } async Task<DeviceInformation> GetFirstBackPanelVideoCaptureAsync() { var devices = await DeviceInformation.FindAllAsync( DeviceClass.VideoCapture); var device = devices.FirstOrDefault( d => d.EnclosureLocation.Panel == Windows.Devices.Enumeration.Panel.Back); return (device); } async void OnLoaded(object sender, RoutedEventArgs e) { await this.LoadModelAsync(); var device = await this.GetFirstBackPanelVideoCaptureAsync(); if (device != null) { await this.CreateMediaCaptureAsync(device); await this.mediaCapture.StartPreviewAsync(); await this.CreateMediaFrameReaderAsync(); await this.frameReader.StartAsync(); } } async Task CreateMediaFrameReaderAsync() { var frameSource = this.mediaCapture.FrameSources.Where( source => source.Value.Info.SourceKind == MediaFrameSourceKind.Color).First(); this.frameReader = await this.mediaCapture.CreateFrameReaderAsync(frameSource.Value); this.frameReader.FrameArrived += OnFrameArrived; } async Task CreateMediaCaptureAsync(DeviceInformation device) { this.mediaCapture = new MediaCapture(); await this.mediaCapture.InitializeAsync( new MediaCaptureInitializationSettings() { VideoDeviceId = device.Id } ); // Try and set auto focus but on the Surface Pro 3 I'm running on, this // won't work. if (this.mediaCapture.VideoDeviceController.FocusControl.Supported) { await this.mediaCapture.VideoDeviceController.FocusControl.SetPresetAsync(FocusPreset.AutoNormal); } else { // Nor this. this.mediaCapture.VideoDeviceController.Focus.TrySetAuto(true); } this.captureElement.Source = this.mediaCapture; } async void OnFrameArrived(MediaFrameReader sender, MediaFrameArrivedEventArgs args) { if (Interlocked.CompareExchange(ref this.processingFlag, 1, 0) == 0) { try { using (var frame = sender.TryAcquireLatestFrame()) using (var videoFrame = frame.VideoMediaFrame?.GetVideoFrame()) { if (videoFrame != null) { // From the description (both visible in Python and through the // properties of the model that I can interrogate with code at // runtime here) my image seems to to be 227 by 227 which is an // odd size but I'm assuming that I should resize the frame here to // suit that. I'm also assuming that what I'm doing here is // expensive #if RESIZE using (var resizedBitmap = await ResizeVideoFrame(videoFrame, IMAGE_SIZE, IMAGE_SIZE)) using (var resizedFrame = VideoFrame.CreateWithSoftwareBitmap(resizedBitmap)) { this.inputData.data = resizedFrame; #else this.inputData.data = videoFrame; #endif // RESIZE var evalOutput = await this.learningModel.EvaluateAsync(this.inputData); await this.ProcessOutputAsync(evalOutput); #if RESIZE } #endif // RESIZE } } } finally { Interlocked.Exchange(ref this.processingFlag, 0); } } } string BuildOutputString(DacshundModelOutput evalOutput, string key) { var result = "no"; if (evalOutput.loss[key] > 0.25f) { result = $"{evalOutput.loss[key]:N2}"; } return (result); } async Task ProcessOutputAsync(DacshundModelOutput evalOutput) { string category = evalOutput.classLabel.FirstOrDefault() ?? "none"; string dog = $"{BuildOutputString(evalOutput, "dog")}"; string pony = $"{BuildOutputString(evalOutput, "pony")}"; string dacshund = $"{BuildOutputString(evalOutput, "daschund")}"; await this.Dispatcher.RunAsync(CoreDispatcherPriority.Normal, () => { this.Dog = dog; this.Pony = pony; this.Dacshund = dacshund; this.Category = category; } ); } /// <summary> /// This is horrible - I am trying to resize a VideoFrame and I haven't yet /// found a good way to do it so this function goes through a tonne of /// stuff to try and resize it but it's not pleasant at all. /// </summary> /// <param name="frame"></param> /// <param name="width"></param> /// <param name="height"></param> /// <returns></returns> async static Task<SoftwareBitmap> ResizeVideoFrame(VideoFrame frame, int width, int height) { SoftwareBitmap bitmapFromFrame = null; bool ownsFrame = false; if (frame.Direct3DSurface != null) { bitmapFromFrame = await SoftwareBitmap.CreateCopyFromSurfaceAsync( frame.Direct3DSurface, BitmapAlphaMode.Ignore); ownsFrame = true; } else if (frame.SoftwareBitmap != null) { bitmapFromFrame = frame.SoftwareBitmap; } // We now need it in a pixel format that an encoder is happy with var encoderBitmap = SoftwareBitmap.Convert( bitmapFromFrame, BitmapPixelFormat.Bgra8, BitmapAlphaMode.Premultiplied); if (ownsFrame) { bitmapFromFrame.Dispose(); } // We now need an encoder, should we keep creating it? var memoryStream = new MemoryStream(); var encoder = await BitmapEncoder.CreateAsync( BitmapEncoder.JpegEncoderId, memoryStream.AsRandomAccessStream()); encoder.SetSoftwareBitmap(encoderBitmap); encoder.BitmapTransform.ScaledWidth = (uint)width; encoder.BitmapTransform.ScaledHeight = (uint)height; await encoder.FlushAsync(); var decoder = await BitmapDecoder.CreateAsync(memoryStream.AsRandomAccessStream()); var resizedBitmap = await decoder.GetSoftwareBitmapAsync( BitmapPixelFormat.Bgra8, BitmapAlphaMode.Premultiplied); memoryStream.Dispose(); encoderBitmap.Dispose(); return (resizedBitmap); } void SetProperty<T>(ref T storage, T value, [CallerMemberName] string propertyName = null) { storage = value; this.PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(propertyName)); } DacshundModelInput inputData; int processingFlag; MediaFrameReader frameReader; MediaCapture mediaCapture; DacshundModel learningModel; static readonly int IMAGE_SIZE = 227; } }

In doing that, the main thing that I was unclear about was whether I need to resize the VideoFrames to fit with my model or whether I could leave them alone and have the code in between me and the model “do the right thing” with the VideoFrame?

Partly, that confusion comes from my model’s description seeming to be say that it was expecting frames at a resolution of 227 x 227 in BGR format and that feels like a very odd resolution to me.

Additionally, I found that trying to resize a VideoFrame seemed to be a bit of a painful task and I didn’t find a better way than going through a SoftwareBitmap with a BitmapEncoder, BitmapDecoder and a BitmapTransform.

The code that I ended up with got fairly ugly and I was never quite sure whether I needed it or not and so, for the moment, I conditionally compiled that code into my little test app so that I can switch between two modes of;

Pass the VideoFrame untouched to the underlying evaluation layer

untouched to the underlying evaluation layer Attempt to resize the VideoFrame to 227 x 227 before passing it to the underlying evaluation layer.

I’ve a feeling that it’s ok to leave the VideoFrame untouched but I’m about 20% sure on that at the time of writing and the follow on piece here assumes that I’m running with that version of the code.

Does It Work?

How does the app work out? I’m not yet sure and there’s a couple of things where I’m not certain.

I’m running on a Surface Pro 3 where the camera has a fixed focus and it doesn’t do a great job of focusing on my images (given that I’ve no UI to control the focus) and so it’s hard to tell at times how good an image the camera is getting. I’ve tried it with both the front and back cameras on that device but I don’t see too much difference.

I’m unsure of whether the way in which I’m passing the VideoFrame to the model is right or not.

But I did run the app and presented it with 3 pictures – one of a dachshund, one of an alsatian (which it should understand is a dog but not a dachshund) and one of a pony.

Here’s some examples showing the sort of output that the app displayed;

I’m not sure about the category of ‘dog’ here but the app seems fairly confident that this is both a dog and a dachshund so that seems good to me.

Here’s another (the model has been trained on alsatian images to some extent);

and so that seems like a good result and then I held up my phone to the video stream displaying an image of a pony;

and so that seems to work reasonably well and that’s the code which does not resize the image down to 227×227 and I found that the code that did resize didn’t seem to work the same way so maybe my notion of resizing (or the actual code which does the resizing) isn’t right.

Wrapping Up

First impressions here are very good in that I managed to get something working in very short time.

Naturally, it’d be interesting to try and build a better understanding around the binding of parameters and I’d also be interested to try this out with a camera that was doing a better job of focusing.

It’d also be interesting to point the camera at real world objects rather than 2D pictures of those objects and so perhaps I need to build a model that classifies something a little more ‘household’ than dogs and ponies to make it easier to test without going out into a field

I’d also like to try some of this out on other types of devices including HoloLens as/when that becomes possible.

Code

If you want the code that I put together here then it’s in this github repo;

Keep in mind that this is just my first experiment, I’m muddling my way through and it looks like the code conditionally compiled out with the RESIZE constant can be ignored unless I hear otherwise and I’ll update the post if I do.

Lastly, you’ve probably noticed many different spellings of the word dachshund in the code and in the blog post – I should have stuck with poodles