Merge pull request #429 from microsoft/user/sheilk/opencv-test
Add OpenCV Interop sample to the gallery
This commit is contained in:
Коммит
1020a0f612
|
@ -13,12 +13,14 @@
|
|||
*.userprefs
|
||||
|
||||
# Build results
|
||||
[Bb]uild/
|
||||
[Dd]ebug/
|
||||
[Dd]ebugPublic/
|
||||
[Rr]elease/
|
||||
[Rr]eleases/
|
||||
x64/
|
||||
x86/
|
||||
[Ii]nt/
|
||||
bld/
|
||||
[Bb]in/
|
||||
[Oo]bj/
|
||||
|
|
|
@ -4,3 +4,6 @@
|
|||
[submodule "Samples/RustSqueezenet/winrt-rs"]
|
||||
path = Samples/RustSqueezenet/winrt-rs
|
||||
url = https://github.com/microsoft/winrt-rs.git
|
||||
[submodule "external/opencv"]
|
||||
path = external/opencv
|
||||
url = https://github.com/opencv/opencv.git
|
||||
|
|
37
README.md
37
README.md
|
@ -54,24 +54,24 @@ A subdomain of computer vision in which an algorithm looks at an image and assig
|
|||
|
||||
| Windows App Type <br/>Distribution | UWP<br/>In-Box | UWP<br/>NuGet | Desktop<br/>In-Box | Desktop<br/>NuGet |
|
||||
|------------|------------------------------------|--------------------------------------|------------------------------------|--------------------------------------|
|
||||
| [AlexNet](https://github.com/onnx/models/tree/master/vision/classification/alexnet) | | ||[✔️C# .NET5 - Samples Gallery](https://github.com/microsoft/Windows-Machine-Learning/tree/master/Samples/WinMLSamplesGallery)<br/>|
|
||||
| [CaffeNet](https://github.com/onnx/models/tree/master/vision/classification/caffenet) | | ||[✔️C# .NET5 - Samples Gallery](https://github.com/microsoft/Windows-Machine-Learning/tree/master/Samples/WinMLSamplesGallery)<br/>|
|
||||
| [DenseNet](https://github.com/onnx/models/tree/master/vision/classification/densenet-121) | | ||[✔️C# .NET5 - Samples Gallery](https://github.com/microsoft/Windows-Machine-Learning/tree/master/Samples/WinMLSamplesGallery)<br/>|
|
||||
| [EfficientNet](https://github.com/onnx/models/tree/master/vision/classification/efficientnet-lite4) | | ||[✔️C# .NET5 - Samples Gallery](https://github.com/microsoft/Windows-Machine-Learning/tree/master/Samples/WinMLSamplesGallery)<br/>|
|
||||
| [AlexNet](https://github.com/onnx/models/tree/master/vision/classification/alexnet) | | ||[✔️C# .NET5 - Samples Gallery](Samples/WinMLSamplesGallery)<br/>|
|
||||
| [CaffeNet](https://github.com/onnx/models/tree/master/vision/classification/caffenet) | | ||[✔️C# .NET5 - Samples Gallery](Samples/WinMLSamplesGallery)<br/>|
|
||||
| [DenseNet](https://github.com/onnx/models/tree/master/vision/classification/densenet-121) | | ||[✔️C# .NET5 - Samples Gallery](Samples/WinMLSamplesGallery)<br/>|
|
||||
| [EfficientNet](https://github.com/onnx/models/tree/master/vision/classification/efficientnet-lite4) | | ||[✔️C# .NET5 - Samples Gallery](Samples/WinMLSamplesGallery)<br/>|
|
||||
| [Emoji8](https://blogs.windows.com/windowsdeveloper/2018/11/16/introducing-emoji8/) | [✔️C#](https://github.com/microsoft/Windows-Machine-Learning/tree/master/Samples/Emoji8/UWP/cs) | |
|
||||
| [GoogleNet](https://github.com/onnx/models/tree/master/vision/classification/inception_and_googlenet/googlenet) | | ||[✔️C# .NET5 - Samples Gallery](https://github.com/microsoft/Windows-Machine-Learning/tree/master/Samples/WinMLSamplesGallery)<br/>|
|
||||
| [InceptionV1](https://github.com/onnx/models/tree/master/vision/classification/inception_and_googlenet/inception_v1) | | ||[✔️C# .NET5 - Samples Gallery](https://github.com/microsoft/Windows-Machine-Learning/tree/master/Samples/WinMLSamplesGallery)<br/>|
|
||||
| [InceptionV2](https://github.com/onnx/models/tree/master/vision/classification/inception_and_googlenet/inception_v2) | | ||[✔️C# .NET5 - Samples Gallery](https://github.com/microsoft/Windows-Machine-Learning/tree/master/Samples/WinMLSamplesGallery)<br/>|
|
||||
| [GoogleNet](https://github.com/onnx/models/tree/master/vision/classification/inception_and_googlenet/googlenet) | | ||[✔️C# .NET5 - Samples Gallery](Samples/WinMLSamplesGallery)<br/>|
|
||||
| [InceptionV1](https://github.com/onnx/models/tree/master/vision/classification/inception_and_googlenet/inception_v1) | | ||[✔️C# .NET5 - Samples Gallery](Samples/WinMLSamplesGallery)<br/>|
|
||||
| [InceptionV2](https://github.com/onnx/models/tree/master/vision/classification/inception_and_googlenet/inception_v2) | | ||[✔️C# .NET5 - Samples Gallery](Samples/WinMLSamplesGallery)<br/>|
|
||||
| [MNIST](https://github.com/onnx/models/tree/master/vision/classification/mnist) | [✔️C++/CX](https://github.com/Microsoft/Windows-Machine-Learning/tree/master/Samples/MNIST/UWP)<br/>[✔️C#](https://github.com/Microsoft/Windows-Machine-Learning/tree/master/Samples/MNIST/Tutorial/cs)<br/> | |
|
||||
| [MobileNetV2](https://github.com/onnx/models/tree/master/vision/classification/mobilenet) | | ||[✔️C# .NET5 - Samples Gallery](https://github.com/microsoft/Windows-Machine-Learning/tree/master/Samples/WinMLSamplesGallery)<br/>|
|
||||
| [RCNN](https://github.com/onnx/models/tree/master/vision/classification/rcnn_ilsvrc13) | | ||[✔️C# .NET5 - Samples Gallery](https://github.com/microsoft/Windows-Machine-Learning/tree/master/Samples/WinMLSamplesGallery)<br/>|
|
||||
| [ResNet50](https://github.com/onnx/models/tree/master/vision/classification/resnet) | | ||[✔️C# .NET5 - Samples Gallery](https://github.com/microsoft/Windows-Machine-Learning/tree/master/Samples/WinMLSamplesGallery)<br/>|
|
||||
| [ShuffleNetV1](https://github.com/onnx/models/tree/master/vision/classification/shufflenet) | | ||[✔️C# .NET5 - Samples Gallery](https://github.com/microsoft/Windows-Machine-Learning/tree/master/Samples/WinMLSamplesGallery)<br/>|
|
||||
| [ShuffleNetV2](https://github.com/onnx/models/tree/master/vision/classification/shufflenet) | | ||[✔️C# .NET5 - Samples Gallery](https://github.com/microsoft/Windows-Machine-Learning/tree/master/Samples/WinMLSamplesGallery)<br/>|
|
||||
| [SqueezeNet](https://github.com/onnx/models/tree/master/vision/classification/squeezenet) | [✔️C#](https://github.com/Microsoft/Windows-Machine-Learning/tree/master/Samples/SqueezeNetObjectDetection/UWP/cs)<br/>[✔️JavaScript](https://github.com/Microsoft/Windows-Machine-Learning/tree/master/Samples/SqueezeNetObjectDetection/UWP/cs)<br/> | |[✔️C++/WinRT](https://github.com/Microsoft/Windows-Machine-Learning/tree/master/Samples/SqueezeNetObjectDetection/Desktop/cpp)<br/> [✔️C# .NET5](https://github.com/Microsoft/Windows-Machine-Learning/tree/master/Samples/SqueezeNetObjectDetection/NET5)<br/>[✔️C# .NET Core 2](https://github.com/microsoft/Windows-Machine-Learning/tree/master/Samples/SqueezeNetObjectDetection/NETCore/cs)<br/>|[✔️C++/WinRT](https://github.com/Microsoft/Windows-Machine-Learning/tree/master/Samples/SqueezeNetObjectDetection/Desktop/cpp)<br/>[✔️C# .NET5 - Samples Gallery](https://github.com/microsoft/Windows-Machine-Learning/tree/master/Samples/WinMLSamplesGallery)<br/>[✔️Rust](https://github.com/microsoft/Windows-Machine-Learning/tree/master/Samples/RustSqueezenet)<br/>|
|
||||
| [VGG19](https://github.com/onnx/models/tree/master/vision/classification/vgg) | | ||[✔️C# .NET5 - Samples Gallery](https://github.com/microsoft/Windows-Machine-Learning/tree/master/Samples/WinMLSamplesGallery)<br/>|
|
||||
| [VGG19bn](https://github.com/onnx/models/tree/master/vision/classification/vgg) | | ||[✔️C# .NET5 - Samples Gallery](https://github.com/microsoft/Windows-Machine-Learning/tree/master/Samples/WinMLSamplesGallery)<br/>|
|
||||
| [ZFNet512](https://github.com/onnx/models/tree/master/vision/classification/zfnet-512) | | ||[✔️C# .NET5 - Samples Gallery](https://github.com/microsoft/Windows-Machine-Learning/tree/master/Samples/WinMLSamplesGallery)<br/>|
|
||||
| [MobileNetV2](https://github.com/onnx/models/tree/master/vision/classification/mobilenet) | | ||[✔️C# .NET5 - Samples Gallery](Samples/WinMLSamplesGallery)<br/>|
|
||||
| [RCNN](https://github.com/onnx/models/tree/master/vision/classification/rcnn_ilsvrc13) | | ||[✔️C# .NET5 - Samples Gallery](Samples/WinMLSamplesGallery)<br/>|
|
||||
| [ResNet50](https://github.com/onnx/models/tree/master/vision/classification/resnet) | | ||[✔️C# .NET5 - Samples Gallery](Samples/WinMLSamplesGallery)<br/>|
|
||||
| [ShuffleNetV1](https://github.com/onnx/models/tree/master/vision/classification/shufflenet) | | ||[✔️C# .NET5 - Samples Gallery](Samples/WinMLSamplesGallery)<br/>|
|
||||
| [ShuffleNetV2](https://github.com/onnx/models/tree/master/vision/classification/shufflenet) | | ||[✔️C# .NET5 - Samples Gallery](Samples/WinMLSamplesGallery)<br/>|
|
||||
| [SqueezeNet](https://github.com/onnx/models/tree/master/vision/classification/squeezenet) | [✔️C#](https://github.com/Microsoft/Windows-Machine-Learning/tree/master/Samples/SqueezeNetObjectDetection/UWP/cs)<br/>[✔️JavaScript](https://github.com/Microsoft/Windows-Machine-Learning/tree/master/Samples/SqueezeNetObjectDetection/UWP/cs)<br/> | |[✔️C++/WinRT](https://github.com/Microsoft/Windows-Machine-Learning/tree/master/Samples/SqueezeNetObjectDetection/Desktop/cpp)<br/> [✔️C# .NET5](https://github.com/Microsoft/Windows-Machine-Learning/tree/master/Samples/SqueezeNetObjectDetection/NET5)<br/>[✔️C# .NET Core 2](https://github.com/microsoft/Windows-Machine-Learning/tree/master/Samples/SqueezeNetObjectDetection/NETCore/cs)<br/>|[✔️C++/WinRT](https://github.com/Microsoft/Windows-Machine-Learning/tree/master/Samples/SqueezeNetObjectDetection/Desktop/cpp)<br/>[✔️C# .NET5 - Samples Gallery](Samples/WinMLSamplesGallery)<br/>[✔️Rust](https://github.com/microsoft/Windows-Machine-Learning/tree/master/Samples/RustSqueezenet)<br/>|
|
||||
| [VGG19](https://github.com/onnx/models/tree/master/vision/classification/vgg) | | ||[✔️C# .NET5 - Samples Gallery](Samples/WinMLSamplesGallery)<br/>|
|
||||
| [VGG19bn](https://github.com/onnx/models/tree/master/vision/classification/vgg) | | ||[✔️C# .NET5 - Samples Gallery](Samples/WinMLSamplesGallery)<br/>|
|
||||
| [ZFNet512](https://github.com/onnx/models/tree/master/vision/classification/zfnet-512) | | ||[✔️C# .NET5 - Samples Gallery](Samples/WinMLSamplesGallery)<br/>|
|
||||
|
||||
**Style Transfer**
|
||||
|
||||
|
@ -87,7 +87,7 @@ A computer vision technique that allows us to recompose the content of an image
|
|||
|
||||
| | Store App<br/>Inbox API | Store App<br/>NuGet API | Desktop App<br/>Inbox API | Desktop App<br/>NuGet API |
|
||||
|------------|------------------------------------|--------------------------------------|------------------------------------|--------------------------------------|
|
||||
| [YoloV4](https://github.com/onnx/models/raw/master/vision/object_detection_segmentation/yolov4/model/yolov4.onnx) | | ||[✔️C# .NET5 - Samples Gallery](https://github.com/microsoft/Windows-Machine-Learning/tree/master/Samples/WinMLSamplesGallery)<br/>|
|
||||
| [YoloV4](https://github.com/onnx/models/raw/master/vision/object_detection_segmentation/yolov4/model/yolov4.onnx) | | ||[✔️C# .NET5 - Samples Gallery](Samples/WinMLSamplesGallery)<br/>|
|
||||
|
||||
-->
|
||||
|
||||
|
@ -104,6 +104,7 @@ These advanced samples show how to use various binding and evaluation features i
|
|||
- **[PyTorch Data Analysis](https://github.com/Microsoft/Windows-AppConsult-Samples-UWP/tree/master/PlaneIdentifier)**: The tutorial shows how to solve a classification task with a neural network using the PyTorch library, export the model to ONNX format and deploy the model with the Windows Machine Learning application that can run on any Windows device.
|
||||
- **[PyTorch Image Classification](https://github.com/Microsoft/Windows-AppConsult-Samples-UWP/tree/master/PlaneIdentifier)**: The tutorial shows how to train an image classification neural network model using PyTorch, export the model to the ONNX format, and deploy it in a Windows Machine Learning application running locally on your Windows device.
|
||||
- **[YoloV4 Object Detection](https://github.com/Microsoft/Windows-AppConsult-Samples-UWP/tree/master/PlaneIdentifier)**: This tutorial shows how to build a UWP C# app that uses the YOLOv4 model to detect objects in video streams.
|
||||
- **[OpenCV Interop](Samples/WinMLSamplesGallery/WinMLSamplesGallery/Samples/OpenCVInterop)**: This sample demonstrates how to interop between [Windows ML](https://docs.microsoft.com/en-us/windows/ai/windows-ml/) and [OpenCV](https://github.com/opencv/opencv).
|
||||
|
||||
## Developer Tools
|
||||
|
||||
|
@ -135,7 +136,7 @@ These advanced samples show how to use various binding and evaluation features i
|
|||
|
||||
Download for [VS 2017](https://marketplace.visualstudio.com/items?itemName=WinML.mlgen), [VS 2019](https://marketplace.visualstudio.com/items?itemName=WinML.MLGenV2)
|
||||
|
||||
- **[WinML Samples Gallery](https://github.com/microsoft/Windows-Machine-Learning/tree/master/Samples/WinMLSamplesGallery):** explore a variety of ML integration scenarios and models.
|
||||
- **[WinML Samples Gallery](Samples/WinMLSamplesGallery):** explore a variety of ML integration scenarios and models.
|
||||
|
||||
- Check out the [Model Samples](#model-samples) and [Advanced Scenario Samples](#advanced-scenarios) to learn how to use Windows ML in your application.
|
||||
|
||||
|
|
|
@ -36,6 +36,8 @@ To learn how to implement these features in your application, or unlock addition
|
|||
|
||||
- [Batched Inputs](./WinMLSamplesGallery/Samples/Batching): WinML enables batched inputs that allow callers to perform inference over multiple inputs at once in order to increase performance. Use this sample to compare inference runtime performace with and without batching.
|
||||
|
||||
- [OpenCV Interop](./WinMLSamplesGallery/Samples/OpenCVInterop): This sample demonstrates how to interop between [Windows ML](https://docs.microsoft.com/en-us/windows/ai/windows-ml/) and [OpenCV](https://github.com/opencv/opencv). The demo will run [SqueezeNet](https://github.com/onnx/models/tree/master/vision/classification/squeezenet) image classification in WindowsML and consume images loaded and preprocessed using OpenCV.
|
||||
|
||||
## Feedback
|
||||
Please file an issue [here](https://github.com/microsoft/Windows-Machine-Learning/issues/new) if you encounter any issues with the WinML Samples Gallery or wish to request a new sample.
|
||||
|
||||
|
|
|
@ -128,6 +128,7 @@
|
|||
</ItemGroup>
|
||||
<ItemGroup>
|
||||
<None Include="$(SolutionDir)$(Platform)\$(Configuration)\WinMLSamplesGalleryNative\*.dll" Link="%(RecursiveDir)%(Filename)%(Extension)" CopyToOutputDirectory="PreserveNewest" />
|
||||
<None Include="$(SolutionDir)..\..\build\external\opencv\cmake_config\$(Platform)\bin\$(Configuration)\*.dll" Link="%(RecursiveDir)%(Filename)%(Extension)" CopyToOutputDirectory="PreserveNewest" />
|
||||
</ItemGroup>
|
||||
<Import Project="$(WapProjPath)\Microsoft.DesktopBridge.targets" />
|
||||
<ItemGroup>
|
||||
|
|
|
@ -28,6 +28,9 @@ namespace WinMLSamplesGallery
|
|||
case "ImageEffects":
|
||||
SampleFrame.Navigate(typeof(Samples.ImageEffects));
|
||||
break;
|
||||
case "OpenCVInterop":
|
||||
SampleFrame.Navigate(typeof(Samples.OpenCVInterop));
|
||||
break;
|
||||
}
|
||||
if (sampleMetadata.Docs.Count > 0)
|
||||
DocsHeader.Visibility = Visibility.Visible;
|
||||
|
|
|
@ -39,6 +39,17 @@ namespace WinMLSamplesGallery
|
|||
for (int i = 0; i < metadataJsonArray.Count; i++)
|
||||
{
|
||||
JsonObject currentSampleMetadata = metadataJsonArray[i].GetObject();
|
||||
|
||||
bool shouldHideSample = false;
|
||||
#if !USE_OPENCV
|
||||
shouldHideSample |= currentSampleMetadata["Tag"].GetString() == "OpenCVInterop";
|
||||
#endif
|
||||
|
||||
if (shouldHideSample)
|
||||
{
|
||||
continue;
|
||||
}
|
||||
|
||||
allSampleMetadata.Add(new SampleMetadata
|
||||
{
|
||||
Title = currentSampleMetadata["Title"].GetString(),
|
||||
|
|
|
@ -34,6 +34,16 @@
|
|||
"link": "https://docs.microsoft.com/en-us/uwp/api/windows.ai.machinelearning.learningmodelsessionoptions.batchsizeoverride?view=winrt-20348"
|
||||
}
|
||||
]
|
||||
},
|
||||
{
|
||||
"Title": "OpenCV Interop",
|
||||
"DescriptionShort": "The sample uses Windows ML to classify images that have been denoised using OpenCV.",
|
||||
"Description": "This sample demonstrates interop between Windows ML and OpenCV. The sample classifes images that have been denoised using OpenCV's medianBlur using the SqueezeNet model on Windows ML. Choose an image to get started.",
|
||||
"Icon": "\uE155",
|
||||
"Tag": "OpenCVInterop",
|
||||
"XAMLGithubLink": "https://github.com/microsoft/Windows-Machine-Learning/blob/master/Samples/WinMLSamplesGallery/WinMLSamplesGallery/Samples/OpenCVInterop/OpenCVInterop.xaml",
|
||||
"CSharpGithubLink": "https://github.com/microsoft/Windows-Machine-Learning/blob/master/Samples/WinMLSamplesGallery/WinMLSamplesGallery/Samples/OpenCVInterop/OpenCVInterop.xaml.cs",
|
||||
"Docs": []
|
||||
}
|
||||
]
|
||||
}
|
|
@ -233,9 +233,7 @@ namespace WinMLSamplesGallery.Samples
|
|||
|
||||
private void InitializeWindowsMachineLearning()
|
||||
{
|
||||
_tensorizationSession =
|
||||
CreateLearningModelSession(
|
||||
TensorizationModels.BasicTensorization(
|
||||
_tensorizationSession = CreateLearningModelSession(TensorizationModels.BasicTensorization(
|
||||
Height, Width,
|
||||
BatchSize, Channels, CurrentImageDecoder.PixelHeight, CurrentImageDecoder.PixelWidth,
|
||||
"nearest"),
|
||||
|
@ -287,7 +285,7 @@ namespace WinMLSamplesGallery.Samples
|
|||
{
|
||||
var pixelDataProvider = decoder.GetPixelDataAsync().GetAwaiter().GetResult();
|
||||
var bytes = pixelDataProvider.DetachPixelData();
|
||||
var buffer = bytes.AsBuffer(); // Need to make this 0 copy...
|
||||
var buffer = bytes.AsBuffer();
|
||||
input = TensorUInt8Bit.CreateFromBuffer(new long[] { 1, buffer.Length }, buffer);
|
||||
|
||||
tensorizationSession = _tensorizationSession;
|
||||
|
@ -303,6 +301,7 @@ namespace WinMLSamplesGallery.Samples
|
|||
var tensorizationResults = Evaluate(tensorizationSession, input);
|
||||
tensorizedOutput = tensorizationResults.Outputs.First().Value;
|
||||
}
|
||||
|
||||
stop = HighResolutionClock.UtcNow();
|
||||
var tensorizeDuration = HighResolutionClock.DurationInMs(start, stop);
|
||||
|
||||
|
|
|
@ -0,0 +1,173 @@
|
|||
<Page
|
||||
x:Class="WinMLSamplesGallery.Samples.OpenCVInterop"
|
||||
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
|
||||
xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
|
||||
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
|
||||
xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
|
||||
xmlns:local_controls="using:WinMLSamplesGallery.Controls"
|
||||
xmlns:local_samples="using:WinMLSamplesGallery.Samples"
|
||||
mc:Ignorable="d"
|
||||
|
||||
Background="{ThemeResource ApplicationPageBackgroundThemeBrush}">
|
||||
|
||||
<Page.Resources>
|
||||
<DataTemplate x:Key="ImageTemplate" x:DataType="local_controls:Thumbnail">
|
||||
<Image Stretch="UniformToFill" Source="{x:Bind ImageUri}" Width="200" Height="204" />
|
||||
</DataTemplate>
|
||||
|
||||
<DataTemplate x:Name="InferenceResultsTemplate" x:DataType="local_controls:Prediction">
|
||||
<StackPanel Orientation="Horizontal">
|
||||
<TextBlock Width="414"
|
||||
FontSize="14"
|
||||
Foreground="Black"
|
||||
Padding="0,1,1,1"
|
||||
Typography.Capitals="AllSmallCaps"
|
||||
Typography.StylisticSet4="True"
|
||||
TextTrimming="CharacterEllipsis">
|
||||
<Run Text="[" />
|
||||
<Run Text="{Binding Index}" />
|
||||
<Run Text="] " />
|
||||
<Run Text="{Binding Name}" />
|
||||
</TextBlock>
|
||||
<TextBlock Width="120"
|
||||
FontSize="14"
|
||||
Foreground="Black"
|
||||
Padding="0,1,1,1"
|
||||
Typography.Capitals="AllSmallCaps"
|
||||
Typography.StylisticSet4="True">
|
||||
<Run Text="p =" />
|
||||
<Run Text="{Binding Probability}" />
|
||||
</TextBlock>
|
||||
</StackPanel>
|
||||
</DataTemplate>
|
||||
|
||||
<DataTemplate x:Name="AllModelsTemplate" x:DataType="local_samples:ClassifierViewModel">
|
||||
<Grid Background="#e6e6e6" BorderBrush="#12bef6" BorderThickness="1">
|
||||
<TextBlock FontSize="14" Text="{x:Bind Title}"
|
||||
Typography.Capitals="AllSmallCaps"
|
||||
Typography.StylisticSet4="True"
|
||||
VerticalAlignment="Top"
|
||||
Padding="10,2,10,2"
|
||||
MinWidth="136"
|
||||
/>
|
||||
</Grid>
|
||||
</DataTemplate>
|
||||
</Page.Resources>
|
||||
|
||||
<Grid>
|
||||
<ScrollViewer
|
||||
ZoomMode="Disabled"
|
||||
IsVerticalScrollChainingEnabled="True"
|
||||
HorizontalScrollMode="Enabled" HorizontalScrollBarVisibility="Disabled"
|
||||
VerticalScrollMode="Enabled" VerticalScrollBarVisibility="Visible">
|
||||
<Grid>
|
||||
<Grid.RowDefinitions>
|
||||
<RowDefinition Height="*" />
|
||||
<RowDefinition Height="Auto" />
|
||||
<RowDefinition Height="*" />
|
||||
</Grid.RowDefinitions>
|
||||
|
||||
<StackPanel Grid.Row="0" Orientation="Horizontal" Padding="0,10,0,0">
|
||||
<StackPanel Orientation="Vertical">
|
||||
<StackPanel Orientation="Horizontal" HorizontalAlignment="Left">
|
||||
<Button FontFamily="Segoe MDL2 Assets" Content="" Width="97" Height="50" HorizontalAlignment="Left" Click="OpenButton_Clicked" />
|
||||
<Grid Padding="5,0,0,0">
|
||||
<ComboBox x:Name="DeviceComboBox" SelectedIndex="0" Background="LightGray" PlaceholderText="Device" Height="50" Width="97"
|
||||
SelectionChanged="DeviceComboBox_SelectionChanged">
|
||||
<TextBlock Text="CPU" FontSize="18" Typography.Capitals="AllSmallCaps" Typography.StylisticSet4="True"/>
|
||||
<TextBlock Text="DML" FontSize="18" Typography.Capitals="AllSmallCaps" Typography.StylisticSet4="True"/>
|
||||
</ComboBox>
|
||||
</Grid>
|
||||
</StackPanel>
|
||||
<GridView
|
||||
x:Name="BasicGridView"
|
||||
ItemTemplate="{StaticResource ImageTemplate}"
|
||||
IsItemClickEnabled="True"
|
||||
SelectionChanged="SampleInputsGridView_SelectionChanged"
|
||||
SelectionMode="Single"
|
||||
Padding="0,6,0,0"
|
||||
HorizontalAlignment="Center">
|
||||
<GridView.ItemsPanel>
|
||||
<ItemsPanelTemplate>
|
||||
<StackPanel Orientation="Vertical" />
|
||||
</ItemsPanelTemplate>
|
||||
</GridView.ItemsPanel>
|
||||
<GridView.Items>
|
||||
<local_controls:Thumbnail ImageUri="ms-appx:///InputData/hummingbird.jpg" />
|
||||
</GridView.Items>
|
||||
</GridView>
|
||||
</StackPanel>
|
||||
|
||||
<StackPanel Orientation="Horizontal">
|
||||
<StackPanel Orientation="Vertical" Margin="11,0,0,0">
|
||||
<Border x:Name="OriginalBorder" Background="LightGray" BorderBrush="LightGray" CornerRadius="5,5,0,0" Padding="0,5,0,5">
|
||||
<Grid Width="200">
|
||||
<TextBlock Text="Original" FontSize="18" Typography.Capitals="AllSmallCaps" Typography.StylisticSet4="True" HorizontalAlignment="Center"/>
|
||||
</Grid>
|
||||
</Border>
|
||||
<Grid Background="LightGray" HorizontalAlignment="Center" Height="200" Width="200" VerticalAlignment="Top">
|
||||
<Image x:Name="InputImage" Stretch="UniformToFill" Height="200" HorizontalAlignment="Center"/>
|
||||
</Grid>
|
||||
<Button Content="Classify" x:Name="InferOriginal" IsEnabled="false" FontFamily="Segoe UI Light" Typography.Capitals="AllSmallCaps" Typography.StylisticSet4="True"
|
||||
Style="{StaticResource AccentButtonStyle}" Width="200"
|
||||
Click="InferOriginal_Click"/>
|
||||
</StackPanel>
|
||||
|
||||
<StackPanel Orientation="Vertical" Margin="11,0,0,0">
|
||||
<Border x:Name="NoisyBorder" Background="LightGray" BorderBrush="LightGray" CornerRadius="5,5,0,0" Padding="0,5,0,5">
|
||||
<Grid Width="200">
|
||||
<TextBlock Text="Noisy" FontSize="18" Typography.Capitals="AllSmallCaps" Typography.StylisticSet4="True" HorizontalAlignment="Center"/>
|
||||
</Grid>
|
||||
</Border>
|
||||
<Grid Background="LightGray" HorizontalAlignment="Center" Height="200" Width="200" VerticalAlignment="Top">
|
||||
<Image x:Name="NoisyImage" Stretch="UniformToFill" Height="200" HorizontalAlignment="Center"/>
|
||||
</Grid>
|
||||
<Button Content="Classify" x:Name="InferNoisy" IsEnabled="false" FontFamily="Segoe UI Light" Typography.Capitals="AllSmallCaps" Typography.StylisticSet4="True"
|
||||
Style="{StaticResource AccentButtonStyle}" Width="200"
|
||||
Click="InferNoisy_Click"/>
|
||||
</StackPanel>
|
||||
|
||||
<StackPanel Orientation="Vertical" Margin="11,0,0,0">
|
||||
<Border x:Name="DenoisedBorder" Background="LightGray" BorderBrush="LightGray" CornerRadius="5,5,0,0" Padding="0,5,0,5">
|
||||
<Grid Width="200">
|
||||
<TextBlock Text="Denoised" FontSize="18" Typography.Capitals="AllSmallCaps" Typography.StylisticSet4="True" HorizontalAlignment="Center"/>
|
||||
</Grid>
|
||||
</Border>
|
||||
<Grid Background="LightGray" HorizontalAlignment="Center" Height="200" Width="200" VerticalAlignment="Top">
|
||||
<Image x:Name="DenoisedImage" Stretch="UniformToFill" Height="200" HorizontalAlignment="Center"/>
|
||||
</Grid>
|
||||
<Button Content="Classify" x:Name="InferDenoised" IsEnabled="false" FontFamily="Segoe UI Light" Typography.Capitals="AllSmallCaps" Typography.StylisticSet4="True"
|
||||
Style="{StaticResource AccentButtonStyle}" Width="200"
|
||||
Click="InferDenoised_Click"/>
|
||||
</StackPanel>
|
||||
</StackPanel>
|
||||
</StackPanel>
|
||||
|
||||
<StackPanel Orientation="Horizontal" Grid.Row="2"
|
||||
Padding="0,7,0,0">
|
||||
<ListView
|
||||
x:Name="InferenceResults"
|
||||
HorizontalAlignment="Stretch"
|
||||
Padding="0,2,0,0"
|
||||
ItemTemplate="{StaticResource InferenceResultsTemplate}"
|
||||
IsItemClickEnabled="False"
|
||||
SingleSelectionFollowsFocus="False">
|
||||
<ListView.ItemContainerStyle>
|
||||
<Style TargetType="ListViewItem">
|
||||
<Setter Property="Margin" Value="1,1,1,1"/>
|
||||
<Setter Property="MinHeight" Value="0"/>
|
||||
</Style>
|
||||
</ListView.ItemContainerStyle>
|
||||
|
||||
<ListView.ItemsPanel>
|
||||
<ItemsPanelTemplate>
|
||||
<ItemsWrapGrid x:Name="MaxItemsWrapGrid" Orientation="Vertical" HorizontalAlignment="Stretch"/>
|
||||
</ItemsPanelTemplate>
|
||||
</ListView.ItemsPanel>
|
||||
</ListView>
|
||||
<local_controls:PerformanceMonitor x:Name="PerformanceMetricsMonitor"/>
|
||||
</StackPanel>
|
||||
</Grid>
|
||||
</ScrollViewer>
|
||||
</Grid>
|
||||
</Page>
|
|
@ -0,0 +1,343 @@
|
|||
using Microsoft.AI.MachineLearning;
|
||||
using Microsoft.UI.Xaml;
|
||||
using Microsoft.UI.Xaml.Controls;
|
||||
using Microsoft.UI.Xaml.Data;
|
||||
using Microsoft.UI.Xaml.Media;
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
using System.Linq;
|
||||
using System.Runtime.InteropServices.WindowsRuntime;
|
||||
using Windows.Foundation;
|
||||
using Windows.Foundation.Collections;
|
||||
using Windows.Foundation.Metadata;
|
||||
using Windows.Graphics.Imaging;
|
||||
using Windows.Media;
|
||||
using Windows.Storage;
|
||||
using Windows.UI;
|
||||
using WinMLSamplesGallery.Common;
|
||||
using WinMLSamplesGallery.Controls;
|
||||
|
||||
namespace WinMLSamplesGallery.Samples
|
||||
{
|
||||
/// <summary>
|
||||
/// An empty page that can be used on its own or navigated to within a Frame.
|
||||
/// </summary>
|
||||
public sealed partial class OpenCVInterop : Page
|
||||
{
|
||||
enum ClassifyChoice {
|
||||
Original,
|
||||
Noisy,
|
||||
Denoised
|
||||
}
|
||||
|
||||
|
||||
const long BatchSize = 1;
|
||||
const long TopK = 10;
|
||||
const long Height = 224;
|
||||
const long Width = 224;
|
||||
const long Channels = 4;
|
||||
|
||||
private LearningModelSession _inferenceSession;
|
||||
private LearningModelSession _tensorizationSession;
|
||||
private LearningModelSession _postProcessingSession;
|
||||
|
||||
private static Dictionary<long, string> _imagenetLabels;
|
||||
|
||||
private WinMLSamplesGalleryNative.OpenCVImage Original { get; set; }
|
||||
private WinMLSamplesGalleryNative.OpenCVImage Noisy { get; set; }
|
||||
private WinMLSamplesGalleryNative.OpenCVImage Denoised { get; set; }
|
||||
|
||||
private string _currentImagePath = null;
|
||||
private string CurrentImagePath {
|
||||
get {
|
||||
return _currentImagePath;
|
||||
}
|
||||
set
|
||||
{
|
||||
_currentImagePath = value;
|
||||
UpdateSelected();
|
||||
}
|
||||
}
|
||||
|
||||
private void UpdateSelected()
|
||||
{
|
||||
if (_currentImagePath == null)
|
||||
{
|
||||
OriginalBorder.Background = new SolidColorBrush(Microsoft.UI.Colors.LightGray);
|
||||
NoisyBorder.Background = new SolidColorBrush(Microsoft.UI.Colors.LightGray);
|
||||
DenoisedBorder.Background = new SolidColorBrush(Microsoft.UI.Colors.LightGray);
|
||||
InferOriginal.IsEnabled = false;
|
||||
InferNoisy.IsEnabled = false;
|
||||
InferDenoised.IsEnabled = false;
|
||||
}
|
||||
else
|
||||
{
|
||||
InferOriginal.IsEnabled = true;
|
||||
InferNoisy.IsEnabled = true;
|
||||
InferDenoised.IsEnabled = true;
|
||||
switch (InferenceChoice)
|
||||
{
|
||||
case ClassifyChoice.Original:
|
||||
OriginalBorder.Background = new SolidColorBrush(Microsoft.UI.Colors.LightGreen);
|
||||
NoisyBorder.Background = new SolidColorBrush(Microsoft.UI.Colors.LightGray);
|
||||
DenoisedBorder.Background = new SolidColorBrush(Microsoft.UI.Colors.LightGray);
|
||||
break;
|
||||
case ClassifyChoice.Noisy:
|
||||
OriginalBorder.Background = new SolidColorBrush(Microsoft.UI.Colors.LightGray);
|
||||
NoisyBorder.Background = new SolidColorBrush(Microsoft.UI.Colors.LightGreen);
|
||||
DenoisedBorder.Background = new SolidColorBrush(Microsoft.UI.Colors.LightGray);
|
||||
break;
|
||||
case ClassifyChoice.Denoised:
|
||||
OriginalBorder.Background = new SolidColorBrush(Microsoft.UI.Colors.LightGray);
|
||||
NoisyBorder.Background = new SolidColorBrush(Microsoft.UI.Colors.LightGray);
|
||||
DenoisedBorder.Background = new SolidColorBrush(Microsoft.UI.Colors.LightGreen);
|
||||
break;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
private ClassifyChoice InferenceChoice { get; set; }
|
||||
|
||||
#pragma warning disable CA1416 // Validate platform compatibility
|
||||
private LearningModelDeviceKind SelectedDeviceKind
|
||||
{
|
||||
get
|
||||
{
|
||||
return (DeviceComboBox.SelectedIndex == 0) ?
|
||||
LearningModelDeviceKind.Cpu :
|
||||
LearningModelDeviceKind.DirectXHighPerformance;
|
||||
}
|
||||
}
|
||||
#pragma warning restore CA1416 // Validate platform compatibility
|
||||
|
||||
public OpenCVInterop()
|
||||
{
|
||||
this.InitializeComponent();
|
||||
CurrentImagePath = null;
|
||||
InferenceChoice = ClassifyChoice.Denoised;
|
||||
_imagenetLabels = LoadLabels("ms-appx:///InputData/sysnet.txt");
|
||||
_inferenceSession = CreateLearningModelSession("ms-appx:///Models/squeezenet1.1-7.onnx");
|
||||
_postProcessingSession = CreateLearningModelSession(TensorizationModels.SoftMaxThenTopK(TopK));
|
||||
}
|
||||
|
||||
#pragma warning disable CA1416 // Validate platform compatibility
|
||||
private (IEnumerable<string>, IReadOnlyList<float>) Classify(WinMLSamplesGalleryNative.OpenCVImage image)
|
||||
{
|
||||
long start, stop;
|
||||
PerformanceMetricsMonitor.ClearLog();
|
||||
|
||||
start = HighResolutionClock.UtcNow();
|
||||
object input = image.AsTensor();
|
||||
stop = HighResolutionClock.UtcNow();
|
||||
var pixelAccessDuration = HighResolutionClock.DurationInMs(start, stop);
|
||||
|
||||
// Tensorize
|
||||
start = HighResolutionClock.UtcNow();
|
||||
object tensorizedOutput = input;
|
||||
var tensorizationResults = Evaluate(_tensorizationSession, input);
|
||||
tensorizedOutput = tensorizationResults.Outputs.First().Value;
|
||||
stop = HighResolutionClock.UtcNow();
|
||||
var tensorizeDuration = HighResolutionClock.DurationInMs(start, stop);
|
||||
|
||||
// Inference
|
||||
start = HighResolutionClock.UtcNow();
|
||||
var inferenceResults = Evaluate(_inferenceSession, tensorizedOutput);
|
||||
var inferenceOutput = inferenceResults.Outputs.First().Value;
|
||||
stop = HighResolutionClock.UtcNow();
|
||||
var inferenceDuration = HighResolutionClock.DurationInMs(start, stop);
|
||||
|
||||
// PostProcess
|
||||
start = HighResolutionClock.UtcNow();
|
||||
var postProcessedOutputs = Evaluate(_postProcessingSession, inferenceOutput);
|
||||
var topKValues = (TensorFloat)postProcessedOutputs.Outputs["TopKValues"];
|
||||
var topKIndices = (TensorInt64Bit)postProcessedOutputs.Outputs["TopKIndices"];
|
||||
|
||||
// Return results
|
||||
var probabilities = topKValues.GetAsVectorView();
|
||||
var indices = topKIndices.GetAsVectorView();
|
||||
var labels = indices.Select((index) => _imagenetLabels[index]);
|
||||
stop = HighResolutionClock.UtcNow();
|
||||
var postProcessDuration = HighResolutionClock.DurationInMs(start, stop);
|
||||
|
||||
PerformanceMetricsMonitor.Log("Pixel Access (CPU)", pixelAccessDuration);
|
||||
PerformanceMetricsMonitor.Log("Tensorize", tensorizeDuration);
|
||||
PerformanceMetricsMonitor.Log("Pre-process", 0);
|
||||
PerformanceMetricsMonitor.Log("Inference", inferenceDuration);
|
||||
PerformanceMetricsMonitor.Log("Post-process", postProcessDuration);
|
||||
|
||||
return (labels, probabilities);
|
||||
}
|
||||
|
||||
private static LearningModelEvaluationResult Evaluate(LearningModelSession session, object input)
|
||||
{
|
||||
// Create the binding
|
||||
var binding = new LearningModelBinding(session);
|
||||
|
||||
// Create an emoty output, that will keep the output resources on the GPU
|
||||
// It will be chained into a the post processing on the GPU as well
|
||||
var output = TensorFloat.Create();
|
||||
|
||||
// Bind inputs and outputs
|
||||
// For squeezenet these evaluate to "data", and "squeezenet0_flatten0_reshape0"
|
||||
string inputName = session.Model.InputFeatures[0].Name;
|
||||
string outputName = session.Model.OutputFeatures[0].Name;
|
||||
binding.Bind(inputName, input);
|
||||
|
||||
var outputBindProperties = new PropertySet();
|
||||
outputBindProperties.Add("DisableTensorCpuSync", PropertyValue.CreateBoolean(true));
|
||||
binding.Bind(outputName, output, outputBindProperties);
|
||||
|
||||
// Evaluate
|
||||
return session.Evaluate(binding, "");
|
||||
}
|
||||
|
||||
private LearningModelSession CreateLearningModelSession(string modelPath)
|
||||
{
|
||||
var model = CreateLearningModel(modelPath);
|
||||
var session = CreateLearningModelSession(model);
|
||||
return session;
|
||||
}
|
||||
|
||||
private LearningModelSession CreateLearningModelSession(LearningModel model, Nullable<LearningModelDeviceKind> kind = null)
|
||||
{
|
||||
var device = new LearningModelDevice(kind ?? SelectedDeviceKind);
|
||||
var options = new LearningModelSessionOptions()
|
||||
{
|
||||
CloseModelOnSessionCreation = true // Close the model to prevent extra memory usage
|
||||
};
|
||||
var session = new LearningModelSession(model, device, options);
|
||||
return session;
|
||||
}
|
||||
|
||||
private static LearningModel CreateLearningModel(string modelPath)
|
||||
{
|
||||
var uri = new Uri(modelPath);
|
||||
var file = StorageFile.GetFileFromApplicationUriAsync(uri).GetAwaiter().GetResult();
|
||||
return LearningModel.LoadFromStorageFileAsync(file).GetAwaiter().GetResult();
|
||||
}
|
||||
#pragma warning restore CA1416 // Validate platform compatibility
|
||||
|
||||
private static Dictionary<long, string> LoadLabels(string csvFile)
|
||||
{
|
||||
var file = StorageFile.GetFileFromApplicationUriAsync(new Uri(csvFile)).GetAwaiter().GetResult();
|
||||
var text = Windows.Storage.FileIO.ReadTextAsync(file).GetAwaiter().GetResult();
|
||||
var labels = new Dictionary<long, string>();
|
||||
var records = text.Split(Environment.NewLine);
|
||||
foreach (var record in records)
|
||||
{
|
||||
var fields = record.Split(",", 2);
|
||||
if (fields.Length == 2)
|
||||
{
|
||||
var index = long.Parse(fields[0]);
|
||||
labels[index] = fields[1];
|
||||
}
|
||||
}
|
||||
return labels;
|
||||
}
|
||||
|
||||
private void TryPerformInference(bool reloadImages = true)
|
||||
{
|
||||
if (CurrentImagePath != null)
|
||||
{
|
||||
if (reloadImages)
|
||||
{
|
||||
Original = WinMLSamplesGalleryNative.OpenCVImage.CreateFromPath(CurrentImagePath);
|
||||
Noisy = WinMLSamplesGalleryNative.OpenCVImage.AddSaltAndPepperNoise(Original);
|
||||
Denoised = WinMLSamplesGalleryNative.OpenCVImage.DenoiseMedianBlur(Noisy);
|
||||
|
||||
var baseImageBitmap = Original.AsSoftwareBitmap();
|
||||
RenderingHelpers.BindSoftwareBitmapToImageControl(InputImage, baseImageBitmap);
|
||||
RenderingHelpers.BindSoftwareBitmapToImageControl(NoisyImage, Noisy.AsSoftwareBitmap());
|
||||
RenderingHelpers.BindSoftwareBitmapToImageControl(DenoisedImage, Denoised.AsSoftwareBitmap());
|
||||
|
||||
var tensorizationModel = TensorizationModels.CastResizeAndTranspose11(Height, Width, 1, 3, baseImageBitmap.PixelHeight, baseImageBitmap.PixelWidth, "nearest");
|
||||
_tensorizationSession = CreateLearningModelSession(tensorizationModel, SelectedDeviceKind);
|
||||
}
|
||||
|
||||
WinMLSamplesGalleryNative.OpenCVImage classificationImage = null;
|
||||
switch (InferenceChoice)
|
||||
{
|
||||
case ClassifyChoice.Original:
|
||||
classificationImage = Original;
|
||||
break;
|
||||
case ClassifyChoice.Noisy:
|
||||
classificationImage = Noisy;
|
||||
break;
|
||||
case ClassifyChoice.Denoised:
|
||||
classificationImage = Denoised;
|
||||
break;
|
||||
}
|
||||
|
||||
// Classify
|
||||
var (labels, probabilities) = Classify(classificationImage);
|
||||
|
||||
// Render the classification and probabilities
|
||||
RenderInferenceResults(labels, probabilities);
|
||||
}
|
||||
}
|
||||
|
||||
private void RenderInferenceResults(IEnumerable<string> labels, IReadOnlyList<float> probabilities)
|
||||
{
|
||||
var indices = Enumerable.Range(1, probabilities.Count);
|
||||
var zippedResults = indices.Zip(labels.Zip(probabilities));
|
||||
var results = zippedResults.Select(
|
||||
(zippedResult) =>
|
||||
new Controls.Prediction {
|
||||
Index = zippedResult.First,
|
||||
Name = zippedResult.Second.First.Trim(new char[] { ',' }),
|
||||
Probability = zippedResult.Second.Second.ToString("E4")
|
||||
});
|
||||
InferenceResults.ItemsSource = results;
|
||||
InferenceResults.SelectedIndex = 0;
|
||||
}
|
||||
|
||||
private void OpenButton_Clicked(object sender, RoutedEventArgs e)
|
||||
{
|
||||
var storageFile = ImageHelper.PickImageFiles();
|
||||
if (storageFile != null)
|
||||
{
|
||||
BasicGridView.SelectedItem = null;
|
||||
CurrentImagePath = storageFile.Path;
|
||||
TryPerformInference();
|
||||
}
|
||||
}
|
||||
|
||||
private void SampleInputsGridView_SelectionChanged(object sender, SelectionChangedEventArgs e)
|
||||
{
|
||||
var gridView = (GridView)sender;
|
||||
var thumbnail = (Thumbnail)gridView.SelectedItem;
|
||||
if (thumbnail != null)
|
||||
{
|
||||
var file = StorageFile.GetFileFromApplicationUriAsync(new Uri(thumbnail.ImageUri)).GetAwaiter().GetResult();
|
||||
CurrentImagePath = file.Path;
|
||||
TryPerformInference();
|
||||
}
|
||||
}
|
||||
|
||||
private void DeviceComboBox_SelectionChanged(object sender, SelectionChangedEventArgs e)
|
||||
{
|
||||
TryPerformInference();
|
||||
}
|
||||
|
||||
private void InferOriginal_Click(object sender, RoutedEventArgs e)
|
||||
{
|
||||
InferenceChoice = ClassifyChoice.Original;
|
||||
UpdateSelected();
|
||||
TryPerformInference(false);
|
||||
}
|
||||
|
||||
private void InferNoisy_Click(object sender, RoutedEventArgs e)
|
||||
{
|
||||
InferenceChoice = ClassifyChoice.Noisy;
|
||||
UpdateSelected();
|
||||
TryPerformInference(false);
|
||||
}
|
||||
|
||||
private void InferDenoised_Click(object sender, RoutedEventArgs e)
|
||||
{
|
||||
InferenceChoice = ClassifyChoice.Denoised;
|
||||
UpdateSelected();
|
||||
TryPerformInference(false);
|
||||
}
|
||||
}
|
||||
}
|
|
@ -0,0 +1,49 @@
|
|||
# WinML Samples Gallery: OpenCV Interop
|
||||
This sample demonstrates how to interop between [Windows ML](https://docs.microsoft.com/en-us/windows/ai/windows-ml/) and [OpenCV](https://github.com/opencv/opencv).
|
||||
|
||||
OpenCV (Open Source Computer Vision Library) is an open source computer vision and machine learning software library. OpenCV was built to provide a common infrastructure for computer vision applications and to accelerate the use of machine perception in the commercial products.
|
||||
|
||||
The demo will run [SqueezeNet](https://github.com/onnx/models/tree/master/vision/classification/squeezenet) image classification in WindowsML and consume images loaded and preprocessed using OpenCV.
|
||||
|
||||
OpenCV will be used to load images, add salt and pepper noise to the base image, and denoise the image using media blur.
|
||||
Windows ML will be used to resize and tensorize the image into NCHW format, as well as perform image classification.
|
||||
|
||||
|
||||
<img src="docs/screenshot.png" width="650"/>
|
||||
|
||||
- [Licenses](#licenses)
|
||||
- [Getting Started](#getting-started)
|
||||
- [Feedback]($feedback)
|
||||
- [External Links](#links)
|
||||
|
||||
|
||||
## Licenses
|
||||
See [ThirdPartyNotices.txt](../../../../../ThirdPartyNotices.txt) for relevant license info.
|
||||
|
||||
## Getting Started
|
||||
In order to build this sample, OpenCV will need to be built and linked into the WinML Samples Gallery. The OpenCV project is included as a submodule, and will need to be synced and built for your Platform Architecture and Configuration before it will appear in the Windows ML Samples Gallery. To do so follow these instructions:
|
||||
- Launch a Visual Studio Developer Command Prompt.
|
||||
- Navigate to the `repository root` directory.
|
||||
- Sync submodules with `git submodule update --init --recursive`
|
||||
- Launch Powershell with `powershell`
|
||||
- Build the OpenCV project with
|
||||
|
||||
`.\external\tools\BuildOpenCV.ps1 -Architecture <ARCH> -Configuration <CONFIGURATION> -SetupDevEnv`
|
||||
|
||||
For example:
|
||||
|
||||
`.\external\tools\BuildOpenCV.ps1 -Architecture x64 -Configuration Debug`
|
||||
- Launch the `WinMLSamplesGallery.sln` and build with the same **Architecture** and **Configuration** to see the sample appear.
|
||||
|
||||
|
||||
You can check out the source [here](https://github.com/microsoft/Windows-Machine-Learning/blob/91e493d699df80a633654929418f41bab136ae1d/Samples/WinMLSamplesGallery/WinMLSamplesGalleryNative/OpenCVImage.cpp#L21).
|
||||
|
||||
## Feedback
|
||||
Please file an issue [here](https://github.com/microsoft/Windows-Machine-Learning/issues/new) if you encounter any issues with this sample.
|
||||
|
||||
## External Links
|
||||
|
||||
- [Windows ML Library (WinML)](https://docs.microsoft.com/en-us/windows/ai/windows-ml/)
|
||||
- [DirectML](https://github.com/microsoft/directml)
|
||||
- [ONNX Model Zoo](https://github.com/onnx/models)
|
||||
- [Windows UI Library (WinUI)](https://docs.microsoft.com/en-us/windows/apps/winui/)
|
Двоичные данные
Samples/WinMLSamplesGallery/WinMLSamplesGallery/Samples/OpenCVInterop/docs/screenshot.png
Normal file
Двоичные данные
Samples/WinMLSamplesGallery/WinMLSamplesGallery/Samples/OpenCVInterop/docs/screenshot.png
Normal file
Двоичный файл не отображается.
После Ширина: | Высота: | Размер: 368 KiB |
|
@ -401,6 +401,60 @@ namespace WinMLSamplesGallery.Samples
|
|||
|
||||
return builder.CreateModel();
|
||||
}
|
||||
|
||||
public static LearningModel CastResizeAndTranspose(long newH, long newW, string interpolationMode)
|
||||
{
|
||||
|
||||
var builder = LearningModelBuilder.Create(13)
|
||||
.Inputs.Add(LearningModelBuilder.CreateTensorFeatureDescriptor("Input", TensorKind.UInt8, new long[] { -1, -1, -1, 3 }))
|
||||
.Outputs.Add(LearningModelBuilder.CreateTensorFeatureDescriptor("Output", TensorKind.Float, new long[] { 1, 3, newH, newW }))
|
||||
.Operators.Add(new LearningModelOperator("Cast")
|
||||
.SetInput("input", "Input")
|
||||
.SetAttribute("to", TensorInt64Bit.CreateFromIterable(new long[] { }, new long[] { (long)OnnxDataType.FLOAT }))
|
||||
.SetOutput("output", "CastOutput"))
|
||||
.Operators.Add(new LearningModelOperator("Resize")
|
||||
.SetInput("X", "CastOutput")
|
||||
.SetConstant("sizes", TensorInt64Bit.CreateFromIterable(new long[] { 4 }, new long[] { 1, newH, newW, 3 }))
|
||||
.SetAttribute("mode", TensorString.CreateFromArray(new long[] { }, new string[] { interpolationMode }))
|
||||
.SetOutput("Y", "ResizeOutput"))
|
||||
.Operators.Add(new LearningModelOperator("Transpose")
|
||||
.SetInput("data", "ResizeOutput")
|
||||
.SetAttribute("perm", TensorInt64Bit.CreateFromArray(new long[] { 4 }, new long[] { 0, 3, 1, 2 }))
|
||||
.SetOutput("transposed", "Output"));
|
||||
|
||||
return builder.CreateModel();
|
||||
}
|
||||
public static LearningModel CastResizeAndTranspose11(long newH, long newW, long n, long c, long h, long w, string interpolationMode)
|
||||
{
|
||||
long resizedW, resizedH, top, bottom, left, right;
|
||||
CalculateCenterFillDimensions(h, w, newH, newW, out resizedW, out resizedH, out top, out bottom, out left, out right);
|
||||
var builder = LearningModelBuilder.Create(13)
|
||||
.Inputs.Add(LearningModelBuilder.CreateTensorFeatureDescriptor("Input", TensorKind.UInt8, new long[] { -1, -1, -1, 3 }))
|
||||
.Outputs.Add(LearningModelBuilder.CreateTensorFeatureDescriptor("Output", TensorKind.Float, new long[] { 1, 3, newH, newW }))
|
||||
.Operators.Add(new LearningModelOperator("Cast")
|
||||
.SetInput("input", "Input")
|
||||
.SetAttribute("to", TensorInt64Bit.CreateFromIterable(new long[] { }, new long[] { (long)OnnxDataType.FLOAT }))
|
||||
.SetOutput("output", "CastOutput"))
|
||||
.Operators.Add(new LearningModelOperator("Resize")
|
||||
.SetInput("X", "CastOutput")
|
||||
.SetConstant("roi", TensorFloat.CreateFromIterable(new long[] { 8 }, new float[] { 0, 0, 0, 0, 1, 1, 1, 1 }))
|
||||
.SetConstant("scales", TensorFloat.CreateFromIterable(new long[] { 4 }, new float[] { 1, (float)(1 + resizedH) / (float)h, (float)(1 + resizedH) / (float)h, 1 }))
|
||||
//.SetConstant("sizes", TensorInt64Bit.CreateFromIterable(new long[] { 4 }, new long[] { 1, 3, resizedH, resizedW }))
|
||||
.SetAttribute("mode", TensorString.CreateFromArray(new long[] { }, new string[] { interpolationMode }))
|
||||
.SetOutput("Y", "ResizeOutput"))
|
||||
.Operators.Add(new LearningModelOperator("Slice")
|
||||
.SetInput("data", "ResizeOutput")
|
||||
.SetConstant("starts", TensorInt64Bit.CreateFromIterable(new long[] { 4 }, new long[] { 0, top, left, 0 }))
|
||||
.SetConstant("ends", TensorInt64Bit.CreateFromIterable(new long[] { 4 }, new long[] { long.MaxValue, bottom, right, c }))
|
||||
.SetOutput("output", "SliceOutput"))
|
||||
.Operators.Add(new LearningModelOperator("Transpose")
|
||||
.SetInput("data", "SliceOutput")
|
||||
.SetAttribute("perm", TensorInt64Bit.CreateFromArray(new long[] { 4 }, new long[] { 0, 3, 1, 2 }))
|
||||
.SetOutput("transposed", "Output"));
|
||||
|
||||
return builder.CreateModel();
|
||||
}
|
||||
|
||||
public static LearningModel BasicTensorization(long newH, long newW, long n, long c, long h, long w, string interpolationMode, bool castFirst = false)
|
||||
{
|
||||
long resizedW, resizedH, top, bottom, left, right;
|
||||
|
@ -424,7 +478,6 @@ namespace WinMLSamplesGallery.Samples
|
|||
.SetConstant("roi", TensorFloat.CreateFromIterable(new long[] { 8 }, new float[] { 0, 0, 0, 0, 1, 1, 1, 1 }))
|
||||
.SetConstant("scales", TensorFloat.CreateFromIterable(new long[] { 4 }, new float[] { 1, (float)(1 + resizedH) / (float)h, (float)(1 + resizedH) / (float)h, 1 }))
|
||||
//.SetConstant("sizes", TensorInt64Bit.CreateFromIterable(new long[] { 4 }, new long[] { 1, 3, resizedH, resizedW }))
|
||||
// Experimental Model Building API does not support inputs of string type, so cubic interpolation cant be set...
|
||||
.SetAttribute("mode", TensorString.CreateFromArray(new long[] { }, new string[] { interpolationMode }))
|
||||
.SetOutput("Y", "ResizeOutput"))
|
||||
.Operators.Add(new LearningModelOperator("Slice")
|
||||
|
|
|
@ -8,8 +8,14 @@
|
|||
<Platforms>x86;x64;arm64</Platforms>
|
||||
<RuntimeIdentifiers>win10-x86;win10-x64;win10-arm64</RuntimeIdentifiers>
|
||||
<UseWinUI>true</UseWinUI>
|
||||
<UseLargeModels Condition="$(UseLargeModels) == ''">false</UseLargeModels>
|
||||
<UseLargeModels Condition="$(UseLargeModels) == ''">False</UseLargeModels>
|
||||
<OpenCVLib Condition="'$(Configuration)'=='Debug'">opencv_world454d.lib</OpenCVLib>
|
||||
<OpenCVLib Condition="'$(Configuration)'=='Release'">opencv_world454.lib</OpenCVLib>
|
||||
<OpenCVLibFullPath>$(SolutionDir)..\..\build\external\opencv\cmake_config\$(Platform)\lib\$(Configuration)\$(OpenCVLib)</OpenCVLibFullPath>
|
||||
<UseOpenCV>False</UseOpenCV>
|
||||
<UseOpenCV Condition="Exists('$(OpenCVLibFullPath)')">True</UseOpenCV>
|
||||
<DefineConstants Condition="$(UseLargeModels)">$(DefineConstants);USE_LARGE_MODELS</DefineConstants>
|
||||
<DefineConstants Condition="$(UseOpenCV)">$(DefineConstants);USE_OPENCV</DefineConstants>
|
||||
<AllowUnsafeBlocks>true</AllowUnsafeBlocks>
|
||||
</PropertyGroup>
|
||||
<ItemGroup>
|
||||
|
@ -25,6 +31,7 @@
|
|||
<None Remove="Samples\ImageClassifier.xaml" />
|
||||
<None Remove="Samples\ImageEffects.xaml" />
|
||||
<None Remove="Samples\ObjectDetector\ObjectDetector.xaml" />
|
||||
<None Remove="Samples\OpenCVInterop\OpenCVInterop.xaml" />
|
||||
<None Remove="Video.xaml" />
|
||||
</ItemGroup>
|
||||
<ItemGroup>
|
||||
|
@ -72,6 +79,7 @@
|
|||
<ItemGroup>
|
||||
<None Include="Samples\ImageEffects\ImageEffects.xaml.cs" />
|
||||
<None Include="Samples\ImageClassifier\ImageClassifier.xaml.cs" />
|
||||
<None Include="Samples\OpenCVInterop\OpenCVInterop.xaml.cs" />
|
||||
</ItemGroup>
|
||||
|
||||
<ItemGroup>
|
||||
|
@ -131,10 +139,7 @@
|
|||
<Page Update="Samples\ImageClassifier\ImageClassifier.xaml">
|
||||
<Generator>MSBuild:Compile</Generator>
|
||||
</Page>
|
||||
</ItemGroup>
|
||||
|
||||
<ItemGroup>
|
||||
<Page Update="Samples\ImageClassifier.xaml">
|
||||
<Page Update="Samples\OpenCVInterop\OpenCVInterop.xaml">
|
||||
<Generator>MSBuild:Compile</Generator>
|
||||
</Page>
|
||||
</ItemGroup>
|
||||
|
|
|
@ -9,6 +9,7 @@
|
|||
</PropertyGroup>
|
||||
|
||||
<ItemGroup>
|
||||
<PackageReference Include="Microsoft.AI.MachineLearning" Version="1.9.1" />
|
||||
<PackageReference Include="Microsoft.Windows.CsWinRT" Version="1.3.5" />
|
||||
</ItemGroup>
|
||||
|
||||
|
@ -19,6 +20,7 @@
|
|||
<Target Name="GenerateProjection" BeforeTargets="DispatchToInnerBuilds;Build;CoreCompile">
|
||||
<ItemGroup>
|
||||
<WinMLSamplesGalleryNativeWinMDs Include="$(SolutionDir)WinMLSamplesGalleryNative\bin\neutral\WinMLSamplesGalleryNative.winmd" />
|
||||
<WinMLSamplesGalleryNativeWinMDs Include="$(SolutionDir)packages\Microsoft.AI.MachineLearning.1.9.1\winmds\Microsoft.AI.MachineLearning.winmd" />
|
||||
</ItemGroup>
|
||||
|
||||
<PropertyGroup>
|
||||
|
|
|
@ -1,29 +0,0 @@
|
|||
#include "pch.h"
|
||||
#include "Class.h"
|
||||
#include "Class.g.cpp"
|
||||
|
||||
#include <Windows.h>
|
||||
|
||||
namespace winrt::WinMLSamplesGalleryNative::implementation
|
||||
{
|
||||
int32_t Class::MyProperty()
|
||||
{
|
||||
throw hresult_not_implemented();
|
||||
}
|
||||
|
||||
void Class::MyProperty(int32_t /* value */)
|
||||
{
|
||||
throw hresult_not_implemented();
|
||||
}
|
||||
|
||||
void Class::MessageBoxFromWin32()
|
||||
{
|
||||
MessageBox(
|
||||
NULL,
|
||||
(LPCWSTR)L"Resource not available\nDo you want to try again?",
|
||||
(LPCWSTR)L"Account Details",
|
||||
MB_ICONWARNING | MB_CANCELTRYCONTINUE | MB_DEFBUTTON2
|
||||
);
|
||||
|
||||
}
|
||||
}
|
|
@ -0,0 +1,114 @@
|
|||
#include "pch.h"
|
||||
#include "OpenCVImage.h"
|
||||
#include "OpenCVImage.g.cpp"
|
||||
|
||||
#include "winrt/Windows.Graphics.Imaging.h"
|
||||
#include "winrt/Windows.Storage.Streams.h"
|
||||
#include "winrt/Microsoft.AI.MachineLearning.h"
|
||||
|
||||
#include "WeakBuffer.h"
|
||||
#include <wrl.h>
|
||||
#include <sstream>
|
||||
|
||||
namespace wrl = ::Microsoft::WRL;
|
||||
namespace details = ::Microsoft::AI::MachineLearning::Details;
|
||||
namespace abi_wss = ABI::Windows::Storage::Streams;
|
||||
|
||||
namespace winrt::WinMLSamplesGalleryNative::implementation
|
||||
{
|
||||
OpenCVImage::OpenCVImage(winrt::hstring path)
|
||||
{
|
||||
#ifdef USE_OPENCV
|
||||
image_ = cv::imread(winrt::to_string(path), cv::IMREAD_COLOR);
|
||||
#endif
|
||||
}
|
||||
|
||||
#ifdef USE_OPENCV
|
||||
OpenCVImage::OpenCVImage(cv::Mat&& image) : image_(std::move(image)) {
|
||||
}
|
||||
#endif
|
||||
|
||||
winrt::Windows::Storage::Streams::IBuffer OpenCVImage::AsWeakBuffer()
|
||||
{
|
||||
#ifdef USE_OPENCV
|
||||
auto cz_buffer = image_.ptr();
|
||||
auto size = image_.total()* image_.elemSize();
|
||||
winrt::com_ptr<abi_wss::IBuffer> ptr;
|
||||
wrl::MakeAndInitialize<details::WeakBuffer<uint8_t>>(ptr.put(), cz_buffer, cz_buffer + size);
|
||||
return ptr.as<winrt::Windows::Storage::Streams::IBuffer>();
|
||||
#else
|
||||
return nullptr;
|
||||
#endif
|
||||
}
|
||||
|
||||
winrt::Microsoft::AI::MachineLearning::ITensor OpenCVImage::AsTensor()
|
||||
{
|
||||
#ifdef USE_OPENCV
|
||||
auto buffer = AsWeakBuffer();
|
||||
return winrt::Microsoft::AI::MachineLearning::TensorUInt8Bit::CreateFromBuffer(
|
||||
std::vector<int64_t>{ 1, image_.rows, image_.cols, 3 }, buffer);
|
||||
#else
|
||||
return nullptr;
|
||||
#endif
|
||||
}
|
||||
|
||||
|
||||
winrt::Windows::Graphics::Imaging::SoftwareBitmap OpenCVImage::AsSoftwareBitmap()
|
||||
{
|
||||
#ifdef USE_OPENCV
|
||||
cv::Mat bgra_image;
|
||||
cv::cvtColor(image_, bgra_image, cv::COLOR_RGB2RGBA);
|
||||
|
||||
auto bgra_opencv_image = winrt::make<OpenCVImage>(std::move(bgra_image));
|
||||
auto bgra_opencv_image_impl = bgra_opencv_image.as<implementation::OpenCVImage>();
|
||||
auto bgra_buffer = bgra_opencv_image_impl->AsWeakBuffer();
|
||||
auto software_bitmap =
|
||||
winrt::Windows::Graphics::Imaging::SoftwareBitmap::CreateCopyFromBuffer(
|
||||
bgra_buffer, winrt::Windows::Graphics::Imaging::BitmapPixelFormat::Bgra8, image_.cols, image_.rows);
|
||||
return software_bitmap;
|
||||
#else
|
||||
return nullptr;
|
||||
#endif
|
||||
}
|
||||
|
||||
void OpenCVImage::Close()
|
||||
{
|
||||
#ifdef USE_OPENCV
|
||||
image_.deallocate();
|
||||
#endif
|
||||
}
|
||||
|
||||
winrt::WinMLSamplesGalleryNative::OpenCVImage OpenCVImage::CreateFromPath(hstring const& path) {
|
||||
return winrt::make<OpenCVImage>(path);
|
||||
}
|
||||
|
||||
winrt::WinMLSamplesGalleryNative::OpenCVImage OpenCVImage::AddSaltAndPepperNoise(winrt::WinMLSamplesGalleryNative::OpenCVImage image) {
|
||||
#ifdef USE_OPENCV
|
||||
auto& image_mat = image.as<implementation::OpenCVImage>().get()->image_;
|
||||
cv::Mat saltpepper_noise = cv::Mat::zeros(image_mat.rows, image_mat.cols, CV_8U);
|
||||
randu(saltpepper_noise, 0, 255);
|
||||
|
||||
cv::Mat black = saltpepper_noise < 30;
|
||||
cv::Mat white = saltpepper_noise > 225;
|
||||
|
||||
cv::Mat saltpepper_img = image_mat.clone();
|
||||
saltpepper_img.setTo(255, white);
|
||||
saltpepper_img.setTo(0, black);
|
||||
|
||||
return winrt::make<OpenCVImage>(std::move(saltpepper_img));
|
||||
#else
|
||||
return nullptr;
|
||||
#endif
|
||||
}
|
||||
|
||||
winrt::WinMLSamplesGalleryNative::OpenCVImage OpenCVImage::DenoiseMedianBlur(winrt::WinMLSamplesGalleryNative::OpenCVImage image) {
|
||||
#ifdef USE_OPENCV
|
||||
auto& image_mat = image.as<implementation::OpenCVImage>().get()->image_;
|
||||
cv::Mat denoised;
|
||||
cv::medianBlur(image_mat, denoised, 5);
|
||||
return winrt::make<OpenCVImage>(std::move(denoised));
|
||||
#else
|
||||
return nullptr;
|
||||
#endif
|
||||
}
|
||||
}
|
|
@ -0,0 +1,38 @@
|
|||
#pragma once
|
||||
#include "OpenCVImage.g.h"
|
||||
|
||||
#ifdef USE_OPENCV
|
||||
#include <opencv2/opencv.hpp>
|
||||
#endif
|
||||
|
||||
|
||||
namespace winrt::WinMLSamplesGalleryNative::implementation
|
||||
{
|
||||
struct OpenCVImage : OpenCVImageT<OpenCVImage>
|
||||
{
|
||||
OpenCVImage(winrt::hstring path);
|
||||
#ifdef USE_OPENCV
|
||||
OpenCVImage(cv::Mat&& image);
|
||||
#endif
|
||||
|
||||
static winrt::WinMLSamplesGalleryNative::OpenCVImage CreateFromPath(hstring const& path);
|
||||
static winrt::WinMLSamplesGalleryNative::OpenCVImage AddSaltAndPepperNoise(winrt::WinMLSamplesGalleryNative::OpenCVImage image);
|
||||
static winrt::WinMLSamplesGalleryNative::OpenCVImage DenoiseMedianBlur(winrt::WinMLSamplesGalleryNative::OpenCVImage image);
|
||||
winrt::Microsoft::AI::MachineLearning::ITensor AsTensor();
|
||||
winrt::Windows::Graphics::Imaging::SoftwareBitmap AsSoftwareBitmap();
|
||||
|
||||
winrt::Windows::Storage::Streams::IBuffer AsWeakBuffer();
|
||||
void Close();
|
||||
|
||||
private:
|
||||
#ifdef USE_OPENCV
|
||||
cv::Mat image_;
|
||||
#endif
|
||||
};
|
||||
}
|
||||
namespace winrt::WinMLSamplesGalleryNative::factory_implementation
|
||||
{
|
||||
struct OpenCVImage : OpenCVImageT<OpenCVImage, implementation::OpenCVImage>
|
||||
{
|
||||
};
|
||||
}
|
|
@ -0,0 +1,75 @@
|
|||
// Copyright 2019 Microsoft Corporation. All rights reserved.
|
||||
// Use of this source code is governed by a BSD-style license that can be
|
||||
// found in the LICENSE file.
|
||||
#ifndef WEAK_BUFFER_H
|
||||
#define WEAK_BUFFER_H
|
||||
|
||||
#include <wrl.h>
|
||||
#include <wrl/client.h>
|
||||
|
||||
#include <windows.storage.streams.h>
|
||||
#include <robuffer.h>
|
||||
|
||||
namespace Microsoft { namespace AI { namespace MachineLearning { namespace Details {
|
||||
|
||||
template <typename T>
|
||||
struct WeakBuffer
|
||||
: public Microsoft::WRL::RuntimeClass<
|
||||
Microsoft::WRL::RuntimeClassFlags<Microsoft::WRL::WinRtClassicComMix | Microsoft::WRL::InhibitRoOriginateError>,
|
||||
ABI::Windows::Storage::Streams::IBuffer,
|
||||
Windows::Storage::Streams::IBufferByteAccess> {
|
||||
InspectableClass(L"Microsoft.AI.MachineLearning.Details.WeakBuffer", BaseTrust)
|
||||
|
||||
private:
|
||||
const T* m_p_begin;
|
||||
const T* m_p_end;
|
||||
|
||||
public:
|
||||
HRESULT RuntimeClassInitialize(_In_ const T* p_begin, _In_ const T* p_end) {
|
||||
m_p_begin = p_begin;
|
||||
m_p_end = p_end;
|
||||
|
||||
return S_OK;
|
||||
}
|
||||
|
||||
virtual HRESULT STDMETHODCALLTYPE get_Capacity(
|
||||
UINT32 * value)
|
||||
{
|
||||
if (value == nullptr) {
|
||||
return E_POINTER;
|
||||
}
|
||||
|
||||
*value = static_cast<uint32_t>(m_p_end - m_p_begin) * sizeof(T);
|
||||
return S_OK;
|
||||
}
|
||||
|
||||
virtual HRESULT STDMETHODCALLTYPE get_Length(
|
||||
UINT32 * value)
|
||||
{
|
||||
if (value == nullptr) {
|
||||
return E_POINTER;
|
||||
}
|
||||
*value = static_cast<uint32_t>(m_p_end - m_p_begin) * sizeof(T);
|
||||
return S_OK;
|
||||
}
|
||||
|
||||
virtual HRESULT STDMETHODCALLTYPE put_Length(
|
||||
UINT32 /*value*/)
|
||||
{
|
||||
return E_NOTIMPL;
|
||||
}
|
||||
|
||||
STDMETHOD(Buffer)(uint8_t** value)
|
||||
{
|
||||
if (value == nullptr) {
|
||||
return E_POINTER;
|
||||
}
|
||||
|
||||
*value = reinterpret_cast<uint8_t*>(const_cast<T*>(m_p_begin));
|
||||
return S_OK;
|
||||
}
|
||||
};
|
||||
|
||||
}}}} // namespace Microsoft::AI::MachineLearning::Details
|
||||
|
||||
#endif // WEAK_BUFFER_H
|
|
@ -1,10 +1,13 @@
|
|||
namespace WinMLSamplesGalleryNative
|
||||
{
|
||||
[default_interface]
|
||||
runtimeclass Class
|
||||
runtimeclass OpenCVImage : Windows.Foundation.IClosable
|
||||
{
|
||||
Class();
|
||||
Microsoft.AI.MachineLearning.ITensor AsTensor();
|
||||
Windows.Graphics.Imaging.SoftwareBitmap AsSoftwareBitmap();
|
||||
|
||||
static void MessageBoxFromWin32();
|
||||
static OpenCVImage CreateFromPath(String path);
|
||||
static OpenCVImage AddSaltAndPepperNoise(OpenCVImage image);
|
||||
static OpenCVImage DenoiseMedianBlur(OpenCVImage image);
|
||||
}
|
||||
}
|
||||
|
|
|
@ -1,5 +1,7 @@
|
|||
<?xml version="1.0" encoding="utf-8"?>
|
||||
<Project DefaultTargets="Build" ToolsVersion="15.0" xmlns="http://schemas.microsoft.com/developer/msbuild/2003">
|
||||
<Import Project="..\packages\Microsoft.AI.MachineLearning.1.9.1\build\native\Microsoft.AI.MachineLearning.props" Condition="Exists('..\packages\Microsoft.AI.MachineLearning.1.9.1\build\native\Microsoft.AI.MachineLearning.props')" />
|
||||
<Import Project="..\packages\Microsoft.AI.DirectML.1.5.1\build\Microsoft.AI.DirectML.props" Condition="Exists('..\packages\Microsoft.AI.DirectML.1.5.1\build\Microsoft.AI.DirectML.props')" />
|
||||
<Import Project="..\packages\Microsoft.Windows.CppWinRT.2.0.210930.14\build\native\Microsoft.Windows.CppWinRT.props" Condition="Exists('..\packages\Microsoft.Windows.CppWinRT.2.0.210930.14\build\native\Microsoft.Windows.CppWinRT.props')" />
|
||||
<PropertyGroup Label="Globals">
|
||||
<CppWinRTOptimized>true</CppWinRTOptimized>
|
||||
|
@ -96,6 +98,32 @@
|
|||
<ModuleDefinitionFile>WinMLSamplesGalleryNative.def</ModuleDefinitionFile>
|
||||
</Link>
|
||||
</ItemDefinitionGroup>
|
||||
|
||||
<ItemDefinitionGroup>
|
||||
<ClCompile>
|
||||
<AdditionalIncludeDirectories>$(MSBuildThisFileDirectory)../../build/native/include/;%(AdditionalIncludeDirectories)</AdditionalIncludeDirectories>
|
||||
</ClCompile>
|
||||
</ItemDefinitionGroup>
|
||||
|
||||
<!-- OpenCV -->
|
||||
<PropertyGroup>
|
||||
<OpenCVLib Condition="'$(Configuration)'=='Debug'">opencv_world454d.lib</OpenCVLib>
|
||||
<OpenCVLib Condition="'$(Configuration)'=='Release'">opencv_world454.lib</OpenCVLib>
|
||||
<OpenCVLibFullPath>$(SolutionDir)..\..\build\external\opencv\cmake_config\$(PlatformString)\lib\$(Configuration)\$(OpenCVLib)</OpenCVLibFullPath>
|
||||
<UseOpenCV>False</UseOpenCV>
|
||||
<UseOpenCV Condition="Exists('$(OpenCVLibFullPath)')">True</UseOpenCV>
|
||||
</PropertyGroup>
|
||||
<ItemDefinitionGroup Condition="$(UseOpenCV)">
|
||||
<ClCompile>
|
||||
<AdditionalIncludeDirectories>$(SolutionDir)..\..\build\external\opencv\cmake_config\$(PlatformString)\install\include;%(AdditionalIncludeDirectories)</AdditionalIncludeDirectories>
|
||||
<AdditionalOptions>%(AdditionalOptions) /DUSE_OPENCV=1</AdditionalOptions>
|
||||
</ClCompile>
|
||||
<Link>
|
||||
<AdditionalLibraryDirectories>$(SolutionDir)..\..\build\external\opencv\cmake_config\$(PlatformString)\lib\$(Configuration)</AdditionalLibraryDirectories>
|
||||
<AdditionalDependencies>$(OpenCVLib);%(AdditionalDependencies)</AdditionalDependencies>
|
||||
</Link>
|
||||
</ItemDefinitionGroup>
|
||||
|
||||
<ItemDefinitionGroup Condition="'$(Configuration)'=='Debug'">
|
||||
<ClCompile>
|
||||
<PreprocessorDefinitions>_DEBUG;%(PreprocessorDefinitions)</PreprocessorDefinitions>
|
||||
|
@ -111,11 +139,12 @@
|
|||
</Link>
|
||||
</ItemDefinitionGroup>
|
||||
<ItemGroup>
|
||||
<ClInclude Include="Class.h" />
|
||||
<ClInclude Include="OpenCVImage.h" />
|
||||
<ClInclude Include="pch.h" />
|
||||
<ClInclude Include="WeakBuffer.h" />
|
||||
</ItemGroup>
|
||||
<ItemGroup>
|
||||
<ClCompile Include="Class.cpp" />
|
||||
<ClCompile Include="OpenCVImage.cpp" />
|
||||
<ClCompile Include="pch.cpp">
|
||||
<PrecompiledHeader>Create</PrecompiledHeader>
|
||||
</ClCompile>
|
||||
|
@ -137,6 +166,8 @@
|
|||
<Import Project="$(VCTargetsPath)\Microsoft.Cpp.targets" />
|
||||
<ImportGroup Label="ExtensionTargets">
|
||||
<Import Project="..\packages\Microsoft.Windows.CppWinRT.2.0.210930.14\build\native\Microsoft.Windows.CppWinRT.targets" Condition="Exists('..\packages\Microsoft.Windows.CppWinRT.2.0.210930.14\build\native\Microsoft.Windows.CppWinRT.targets')" />
|
||||
<Import Project="..\packages\Microsoft.AI.DirectML.1.5.1\build\Microsoft.AI.DirectML.targets" Condition="Exists('..\packages\Microsoft.AI.DirectML.1.5.1\build\Microsoft.AI.DirectML.targets')" />
|
||||
<Import Project="..\packages\Microsoft.AI.MachineLearning.1.9.1\build\native\Microsoft.AI.MachineLearning.targets" Condition="Exists('..\packages\Microsoft.AI.MachineLearning.1.9.1\build\native\Microsoft.AI.MachineLearning.targets')" />
|
||||
</ImportGroup>
|
||||
<Target Name="EnsureNuGetPackageBuildImports" BeforeTargets="PrepareForBuild">
|
||||
<PropertyGroup>
|
||||
|
@ -144,6 +175,10 @@
|
|||
</PropertyGroup>
|
||||
<Error Condition="!Exists('..\packages\Microsoft.Windows.CppWinRT.2.0.210930.14\build\native\Microsoft.Windows.CppWinRT.props')" Text="$([System.String]::Format('$(ErrorText)', '..\packages\Microsoft.Windows.CppWinRT.2.0.210930.14\build\native\Microsoft.Windows.CppWinRT.props'))" />
|
||||
<Error Condition="!Exists('..\packages\Microsoft.Windows.CppWinRT.2.0.210930.14\build\native\Microsoft.Windows.CppWinRT.targets')" Text="$([System.String]::Format('$(ErrorText)', '..\packages\Microsoft.Windows.CppWinRT.2.0.210930.14\build\native\Microsoft.Windows.CppWinRT.targets'))" />
|
||||
<Error Condition="!Exists('..\packages\Microsoft.AI.DirectML.1.5.1\build\Microsoft.AI.DirectML.props')" Text="$([System.String]::Format('$(ErrorText)', '..\packages\Microsoft.AI.DirectML.1.5.1\build\Microsoft.AI.DirectML.props'))" />
|
||||
<Error Condition="!Exists('..\packages\Microsoft.AI.DirectML.1.5.1\build\Microsoft.AI.DirectML.targets')" Text="$([System.String]::Format('$(ErrorText)', '..\packages\Microsoft.AI.DirectML.1.5.1\build\Microsoft.AI.DirectML.targets'))" />
|
||||
<Error Condition="!Exists('..\packages\Microsoft.AI.MachineLearning.1.9.1\build\native\Microsoft.AI.MachineLearning.props')" Text="$([System.String]::Format('$(ErrorText)', '..\packages\Microsoft.AI.MachineLearning.1.9.1\build\native\Microsoft.AI.MachineLearning.props'))" />
|
||||
<Error Condition="!Exists('..\packages\Microsoft.AI.MachineLearning.1.9.1\build\native\Microsoft.AI.MachineLearning.targets')" Text="$([System.String]::Format('$(ErrorText)', '..\packages\Microsoft.AI.MachineLearning.1.9.1\build\native\Microsoft.AI.MachineLearning.targets'))" />
|
||||
</Target>
|
||||
<Target Name="CopyNeutral" AfterTargets="Build">
|
||||
<Copy SourceFiles="$(OutDir)\WinMLSamplesGalleryNative.winmd" DestinationFolder="$(SolutionDir)$(MSBuildProjectName)\bin\neutral\WinMLSamplesGalleryNative.winmd" />
|
||||
|
|
|
@ -1,4 +1,6 @@
|
|||
<?xml version="1.0" encoding="utf-8"?>
|
||||
<packages>
|
||||
<package id="Microsoft.AI.DirectML" version="1.5.1" targetFramework="native" />
|
||||
<package id="Microsoft.AI.MachineLearning" version="1.9.1" targetFramework="native" />
|
||||
<package id="Microsoft.Windows.CppWinRT" version="2.0.210930.14" targetFramework="native" />
|
||||
</packages>
|
|
@ -0,0 +1,212 @@
|
|||
THIRD-PARTY SOFTWARE NOTICES AND INFORMATION
|
||||
Do Not Translate or Localize
|
||||
|
||||
This software incorporates third party material from the projects listed below.
|
||||
|
||||
- opencv : https://github.com/opencv/opencv
|
||||
|
||||
-------------------------------------------------------------------------------
|
||||
opencv
|
||||
-------------------------------------------------------------------------------
|
||||
|
||||
Apache License
|
||||
Version 2.0, January 2004
|
||||
http://www.apache.org/licenses/
|
||||
|
||||
TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
|
||||
|
||||
1. Definitions.
|
||||
|
||||
"License" shall mean the terms and conditions for use, reproduction,
|
||||
and distribution as defined by Sections 1 through 9 of this document.
|
||||
|
||||
"Licensor" shall mean the copyright owner or entity authorized by
|
||||
the copyright owner that is granting the License.
|
||||
|
||||
"Legal Entity" shall mean the union of the acting entity and all
|
||||
other entities that control, are controlled by, or are under common
|
||||
control with that entity. For the purposes of this definition,
|
||||
"control" means (i) the power, direct or indirect, to cause the
|
||||
direction or management of such entity, whether by contract or
|
||||
otherwise, or (ii) ownership of fifty percent (50%) or more of the
|
||||
outstanding shares, or (iii) beneficial ownership of such entity.
|
||||
|
||||
"You" (or "Your") shall mean an individual or Legal Entity
|
||||
exercising permissions granted by this License.
|
||||
|
||||
"Source" form shall mean the preferred form for making modifications,
|
||||
including but not limited to software source code, documentation
|
||||
source, and configuration files.
|
||||
|
||||
"Object" form shall mean any form resulting from mechanical
|
||||
transformation or translation of a Source form, including but
|
||||
not limited to compiled object code, generated documentation,
|
||||
and conversions to other media types.
|
||||
|
||||
"Work" shall mean the work of authorship, whether in Source or
|
||||
Object form, made available under the License, as indicated by a
|
||||
copyright notice that is included in or attached to the work
|
||||
(an example is provided in the Appendix below).
|
||||
|
||||
"Derivative Works" shall mean any work, whether in Source or Object
|
||||
form, that is based on (or derived from) the Work and for which the
|
||||
editorial revisions, annotations, elaborations, or other modifications
|
||||
represent, as a whole, an original work of authorship. For the purposes
|
||||
of this License, Derivative Works shall not include works that remain
|
||||
separable from, or merely link (or bind by name) to the interfaces of,
|
||||
the Work and Derivative Works thereof.
|
||||
|
||||
"Contribution" shall mean any work of authorship, including
|
||||
the original version of the Work and any modifications or additions
|
||||
to that Work or Derivative Works thereof, that is intentionally
|
||||
submitted to Licensor for inclusion in the Work by the copyright owner
|
||||
or by an individual or Legal Entity authorized to submit on behalf of
|
||||
the copyright owner. For the purposes of this definition, "submitted"
|
||||
means any form of electronic, verbal, or written communication sent
|
||||
to the Licensor or its representatives, including but not limited to
|
||||
communication on electronic mailing lists, source code control systems,
|
||||
and issue tracking systems that are managed by, or on behalf of, the
|
||||
Licensor for the purpose of discussing and improving the Work, but
|
||||
excluding communication that is conspicuously marked or otherwise
|
||||
designated in writing by the copyright owner as "Not a Contribution."
|
||||
|
||||
"Contributor" shall mean Licensor and any individual or Legal Entity
|
||||
on behalf of whom a Contribution has been received by Licensor and
|
||||
subsequently incorporated within the Work.
|
||||
|
||||
2. Grant of Copyright License. Subject to the terms and conditions of
|
||||
this License, each Contributor hereby grants to You a perpetual,
|
||||
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
|
||||
copyright license to reproduce, prepare Derivative Works of,
|
||||
publicly display, publicly perform, sublicense, and distribute the
|
||||
Work and such Derivative Works in Source or Object form.
|
||||
|
||||
3. Grant of Patent License. Subject to the terms and conditions of
|
||||
this License, each Contributor hereby grants to You a perpetual,
|
||||
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
|
||||
(except as stated in this section) patent license to make, have made,
|
||||
use, offer to sell, sell, import, and otherwise transfer the Work,
|
||||
where such license applies only to those patent claims licensable
|
||||
by such Contributor that are necessarily infringed by their
|
||||
Contribution(s) alone or by combination of their Contribution(s)
|
||||
with the Work to which such Contribution(s) was submitted. If You
|
||||
institute patent litigation against any entity (including a
|
||||
cross-claim or counterclaim in a lawsuit) alleging that the Work
|
||||
or a Contribution incorporated within the Work constitutes direct
|
||||
or contributory patent infringement, then any patent licenses
|
||||
granted to You under this License for that Work shall terminate
|
||||
as of the date such litigation is filed.
|
||||
|
||||
4. Redistribution. You may reproduce and distribute copies of the
|
||||
Work or Derivative Works thereof in any medium, with or without
|
||||
modifications, and in Source or Object form, provided that You
|
||||
meet the following conditions:
|
||||
|
||||
(a) You must give any other recipients of the Work or
|
||||
Derivative Works a copy of this License; and
|
||||
|
||||
(b) You must cause any modified files to carry prominent notices
|
||||
stating that You changed the files; and
|
||||
|
||||
(c) You must retain, in the Source form of any Derivative Works
|
||||
that You distribute, all copyright, patent, trademark, and
|
||||
attribution notices from the Source form of the Work,
|
||||
excluding those notices that do not pertain to any part of
|
||||
the Derivative Works; and
|
||||
|
||||
(d) If the Work includes a "NOTICE" text file as part of its
|
||||
distribution, then any Derivative Works that You distribute must
|
||||
include a readable copy of the attribution notices contained
|
||||
within such NOTICE file, excluding those notices that do not
|
||||
pertain to any part of the Derivative Works, in at least one
|
||||
of the following places: within a NOTICE text file distributed
|
||||
as part of the Derivative Works; within the Source form or
|
||||
documentation, if provided along with the Derivative Works; or,
|
||||
within a display generated by the Derivative Works, if and
|
||||
wherever such third-party notices normally appear. The contents
|
||||
of the NOTICE file are for informational purposes only and
|
||||
do not modify the License. You may add Your own attribution
|
||||
notices within Derivative Works that You distribute, alongside
|
||||
or as an addendum to the NOTICE text from the Work, provided
|
||||
that such additional attribution notices cannot be construed
|
||||
as modifying the License.
|
||||
|
||||
You may add Your own copyright statement to Your modifications and
|
||||
may provide additional or different license terms and conditions
|
||||
for use, reproduction, or distribution of Your modifications, or
|
||||
for any such Derivative Works as a whole, provided Your use,
|
||||
reproduction, and distribution of the Work otherwise complies with
|
||||
the conditions stated in this License.
|
||||
|
||||
5. Submission of Contributions. Unless You explicitly state otherwise,
|
||||
any Contribution intentionally submitted for inclusion in the Work
|
||||
by You to the Licensor shall be under the terms and conditions of
|
||||
this License, without any additional terms or conditions.
|
||||
Notwithstanding the above, nothing herein shall supersede or modify
|
||||
the terms of any separate license agreement you may have executed
|
||||
with Licensor regarding such Contributions.
|
||||
|
||||
6. Trademarks. This License does not grant permission to use the trade
|
||||
names, trademarks, service marks, or product names of the Licensor,
|
||||
except as required for reasonable and customary use in describing the
|
||||
origin of the Work and reproducing the content of the NOTICE file.
|
||||
|
||||
7. Disclaimer of Warranty. Unless required by applicable law or
|
||||
agreed to in writing, Licensor provides the Work (and each
|
||||
Contributor provides its Contributions) on an "AS IS" BASIS,
|
||||
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
|
||||
implied, including, without limitation, any warranties or conditions
|
||||
of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
|
||||
PARTICULAR PURPOSE. You are solely responsible for determining the
|
||||
appropriateness of using or redistributing the Work and assume any
|
||||
risks associated with Your exercise of permissions under this License.
|
||||
|
||||
8. Limitation of Liability. In no event and under no legal theory,
|
||||
whether in tort (including negligence), contract, or otherwise,
|
||||
unless required by applicable law (such as deliberate and grossly
|
||||
negligent acts) or agreed to in writing, shall any Contributor be
|
||||
liable to You for damages, including any direct, indirect, special,
|
||||
incidental, or consequential damages of any character arising as a
|
||||
result of this License or out of the use or inability to use the
|
||||
Work (including but not limited to damages for loss of goodwill,
|
||||
work stoppage, computer failure or malfunction, or any and all
|
||||
other commercial damages or losses), even if such Contributor
|
||||
has been advised of the possibility of such damages.
|
||||
|
||||
9. Accepting Warranty or Additional Liability. While redistributing
|
||||
the Work or Derivative Works thereof, You may choose to offer,
|
||||
and charge a fee for, acceptance of support, warranty, indemnity,
|
||||
or other liability obligations and/or rights consistent with this
|
||||
License. However, in accepting such obligations, You may act only
|
||||
on Your own behalf and on Your sole responsibility, not on behalf
|
||||
of any other Contributor, and only if You agree to indemnify,
|
||||
defend, and hold each Contributor harmless for any liability
|
||||
incurred by, or claims asserted against, such Contributor by reason
|
||||
of your accepting any such warranty or additional liability.
|
||||
|
||||
END OF TERMS AND CONDITIONS
|
||||
|
||||
APPENDIX: How to apply the Apache License to your work.
|
||||
|
||||
To apply the Apache License to your work, attach the following
|
||||
boilerplate notice, with the fields enclosed by brackets "[]"
|
||||
replaced with your own identifying information. (Don't include
|
||||
the brackets!) The text should be enclosed in the appropriate
|
||||
comment syntax for the file format. We also recommend that a
|
||||
file or class name and description of purpose be included on the
|
||||
same "printed page" as the copyright notice for easier
|
||||
identification within third-party archives.
|
||||
|
||||
Copyright [yyyy] [name of copyright owner]
|
||||
|
||||
Licensed under the Apache License, Version 2.0 (the "License");
|
||||
you may not use this file except in compliance with the License.
|
||||
You may obtain a copy of the License at
|
||||
|
||||
http://www.apache.org/licenses/LICENSE-2.0
|
||||
|
||||
Unless required by applicable law or agreed to in writing, software
|
||||
distributed under the License is distributed on an "AS IS" BASIS,
|
||||
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
||||
See the License for the specific language governing permissions and
|
||||
limitations under the License.
|
|
@ -25,7 +25,9 @@ strategy:
|
|||
BuildConfiguration: Debug
|
||||
|
||||
pool:
|
||||
name: DirectML_BuildPool
|
||||
vmImage: 'windows-latest'
|
||||
# pool:
|
||||
# name: DirectML_BuildPool
|
||||
# demands: agent.osversion -equals 10.0.17763
|
||||
|
||||
# CI trigger
|
||||
|
@ -47,6 +49,12 @@ pr:
|
|||
- Tools
|
||||
|
||||
steps:
|
||||
- task: PowerShell@2
|
||||
displayName: 'Clone Git Submodules'
|
||||
inputs:
|
||||
targetType: inline
|
||||
script: git submodule update --init --recursive
|
||||
|
||||
- task: NuGetToolInstaller@1
|
||||
displayName: 'Install NuGet 5.11.0'
|
||||
inputs:
|
||||
|
@ -58,6 +66,35 @@ steps:
|
|||
targetType: inline
|
||||
script: if (-not (Test-Path "${ENV:programfiles(x86)}\windows Kits\10\include\10.0.18362.0\")) { choco install windows-sdk-10-version-1903-all -y }
|
||||
|
||||
- task: PowerShell@1
|
||||
displayName: OpenCV - Configure CMake
|
||||
inputs:
|
||||
scriptName: external/tools/CMakeConfigureOpenCV.ps1
|
||||
workingDirectory: $(System.ArtifactsDirectory)
|
||||
arguments: >
|
||||
-Architecture $(BuildPlatform)
|
||||
|
||||
- task: VSBuild@1
|
||||
displayName: 'OpenCV - Build'
|
||||
inputs:
|
||||
solution: 'build/external/opencv/cmake_config/$(BuildPlatform)/OpenCV.sln"'
|
||||
vsVersion: "16.0"
|
||||
msbuildArgs: '/p:Configuration=$(BuildConfiguration) /t:Build /p:LinkIncremental=false /p:DebugSymbols=false /p:DebugType=None'
|
||||
configuration: '$(BuildConfiguration)'
|
||||
msbuildArchitecture: x64
|
||||
createLogFile: true
|
||||
condition: succeededOrFailed()
|
||||
|
||||
- task: VSBuild@1
|
||||
displayName: 'OpenCV - Install'
|
||||
inputs:
|
||||
solution: 'build/external/opencv/cmake_config/$(BuildPlatform)/INSTALL.vcxproj'
|
||||
vsVersion: "16.0"
|
||||
msbuildArgs: '/p:Configuration=$(BuildConfiguration) /p:LinkIncremental=false /p:DebugSymbols=false /p:DebugType=None'
|
||||
configuration: '$(BuildConfiguration)'
|
||||
msbuildArchitecture: x64
|
||||
createLogFile: true
|
||||
condition: succeededOrFailed()
|
||||
|
||||
- task: PowerShell@2
|
||||
displayName: 'Restore WinMLSamplesGalleryNative Nuget Packages'
|
||||
|
@ -74,19 +111,7 @@ steps:
|
|||
inputs:
|
||||
solution: 'Samples/WinMLSamplesGallery/WinMLSamplesGallery.sln'
|
||||
vsVersion: "16.0"
|
||||
msbuildArgs: '-v:diag /p:OutDir=$(System.DefaultWorkingDirectory)\bin\$(BuildPlatform)\$(BuildConfiguration)\WinMLSamplesGallery\ /p:WindowsTargetPlatformVersion=$(WindowsTargetPlatformVersion) /p:UseLargeModels=true /t:Restore,Clean,Build'
|
||||
platform: '$(BuildPlatform)'
|
||||
configuration: '$(BuildConfiguration)'
|
||||
msbuildArchitecture: x64
|
||||
createLogFile: true
|
||||
condition: succeededOrFailed()
|
||||
|
||||
- task: VSBuild@1
|
||||
displayName: 'Build WinMLSamplesGallery with Large Models'
|
||||
inputs:
|
||||
solution: 'Samples/WinMLSamplesGallery/WinMLSamplesGallery.sln'
|
||||
vsVersion: "16.0"
|
||||
msbuildArgs: '-v:diag /p:OutDir=$(System.DefaultWorkingDirectory)\bin\$(BuildPlatform)\$(BuildConfiguration)\WinMLSamplesGallery\ /p:UseLargeModels=true /p:WindowsTargetPlatformVersion=$(WindowsTargetPlatformVersion) /t:Restore,Clean,Build'
|
||||
msbuildArgs: '/p:OutDir=$(System.DefaultWorkingDirectory)\bin\$(BuildPlatform)\$(BuildConfiguration)\WinMLSamplesGallery\ /p:WindowsTargetPlatformVersion=$(WindowsTargetPlatformVersion) /t:Restore,Clean,Build'
|
||||
platform: '$(BuildPlatform)'
|
||||
configuration: '$(BuildConfiguration)'
|
||||
msbuildArchitecture: x64
|
||||
|
|
|
@ -0,0 +1 @@
|
|||
Subproject commit 4223495e6cd67011f86b8ecd9be1fa105018f3b1
|
|
@ -0,0 +1,47 @@
|
|||
Param
|
||||
(
|
||||
# Build architecture.
|
||||
[ValidateSet(
|
||||
'x64',
|
||||
'x86',
|
||||
'ARM64')]
|
||||
[string]$Architecture = 'x64',
|
||||
|
||||
# Build configuration.
|
||||
[ValidateSet('Debug', 'Release')][string]$Configuration = 'Debug',
|
||||
|
||||
# Location to generate build files.
|
||||
[string]$CMakeBuildDirectory = "$PSScriptRoot\..\..\build\external\opencv\cmake_config\$Architecture\",
|
||||
|
||||
# Cleans build files before proceeding.
|
||||
[switch]$Clean,
|
||||
|
||||
[switch]$SetupDevEnv = $False
|
||||
)
|
||||
|
||||
if ($Clean) {
|
||||
Remove-Item -Recurse -Force $CMakeBuildDirectory
|
||||
}
|
||||
|
||||
& $PSScriptRoot\CMakeConfigureOpenCV.ps1 -Architecture $Architecture
|
||||
|
||||
$msbuild = "msbuild"
|
||||
|
||||
if ($SetupDevEnv)
|
||||
{
|
||||
Install-Module VSSetup -Scope CurrentUser -Force
|
||||
$latestVS = Get-VSSetupInstance -All -Prerelease | Sort-Object -Property InstallationVersion -Descending | Select-Object -First 1
|
||||
if ($latestVS.InstallationVersion -like "15.*") {
|
||||
$msbuild = "$($latestVS.InstallationPath)\MSBuild\15.0\Bin\msbuild.exe"
|
||||
} else {
|
||||
$msbuild = "$($latestVS.InstallationPath)\MSBuild\Current\Bin\msbuild.exe"
|
||||
}
|
||||
}
|
||||
|
||||
# Build OpenCV
|
||||
$solution = $CMakeBuildDirectory + "OpenCV.sln"
|
||||
& $msbuild /p:Configuration=$Configuration /t:Build /p:LinkIncremental=false /p:DebugSymbols=false /p:DebugType=None $solution
|
||||
|
||||
# Install
|
||||
$installProject = $CMakeBuildDirectory + "INSTALL.vcxproj"
|
||||
& $msbuild /p:Configuration=$Configuration /p:LinkIncremental=false /p:DebugSymbols=false /p:DebugType=None $installProject
|
|
@ -0,0 +1,58 @@
|
|||
Param
|
||||
(
|
||||
# Build architecture.
|
||||
[ValidateSet(
|
||||
'x64',
|
||||
'x86',
|
||||
'ARM64')]
|
||||
[string]$Architecture = 'x64',
|
||||
|
||||
# CMake generator.
|
||||
[ValidateSet(
|
||||
'Visual Studio 15 2017',
|
||||
'Visual Studio 16 2019')]
|
||||
[string]$Generator='Visual Studio 16 2019',
|
||||
|
||||
# Location to generate build files.
|
||||
[string]$BuildDirectory = "$PSScriptRoot\..\..\build\external\opencv\cmake_config\$Architecture",
|
||||
|
||||
# Cleans build files before proceeding.
|
||||
[switch]$Clean
|
||||
)
|
||||
|
||||
|
||||
$Args = New-Object Collections.Generic.List[String]
|
||||
|
||||
if ($Architecture -eq 'x86') {
|
||||
$Args.Add("-A Win32")
|
||||
}
|
||||
else {
|
||||
$Args.Add("-A " + $Architecture)
|
||||
}
|
||||
|
||||
$Args.Add("-G " + $Generator)
|
||||
$Args.Add("-DCMAKE_SYSTEM_NAME=Windows")
|
||||
$Args.Add("-DCMAKE_SYSTEM_VERSION=10.0")
|
||||
$Args.Add("-DWITH_OPENCL=OFF")
|
||||
$Args.Add("-DWITH_FFMPEG=OFF")
|
||||
$Args.Add("-DWITH_CUDA=OFF")
|
||||
$Args.Add("-DBUILD_EXAMPLES=OFF")
|
||||
$Args.Add("-DBUILD_TESTS=OFF")
|
||||
$Args.Add("-DBUILD_opencv_apps=OFF")
|
||||
$Args.Add("-DBUILD_DOCS=OFF")
|
||||
$Args.Add("-DBUILD_PERF_TESTS=OFF")
|
||||
$Args.Add("-DBUILD_opencv_world=ON")
|
||||
|
||||
if ($Architecture -eq 'x64') {
|
||||
$Args.Add("-DCMAKE_SYSTEM_PROCESSOR=AMD64")
|
||||
}
|
||||
else {
|
||||
$Args.Add("-DCMAKE_SYSTEM_PROCESSOR=" + $Architecture)
|
||||
}
|
||||
|
||||
if ($Clean) {
|
||||
$Args.Add("--clean")
|
||||
}
|
||||
|
||||
$Args.Add("-B " + $BuildDirectory)
|
||||
cmake $Args "$PSScriptRoot\..\opencv"
|
Загрузка…
Ссылка в новой задаче