ImageSharp Sample
This commit is contained in:
Родитель
1020a0f612
Коммит
34316af986
|
@ -104,7 +104,10 @@ 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.
|
||||
|
||||
### Interop with other external Image Processing Libraries
|
||||
- **[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).
|
||||
- **[ImageSharp Interop](Samples/WinMLSamplesGallery/WinMLSamplesGallery/Samples/ImageSHarpInterop)**: This sample demonstrates how to interop between [Windows ML](https://docs.microsoft.com/en-us/windows/ai/windows-ml/) and [ImageSharp](https://github.com/SixLabors/ImageSharp).
|
||||
|
||||
## Developer Tools
|
||||
|
||||
|
|
|
@ -31,6 +31,9 @@ namespace WinMLSamplesGallery
|
|||
case "OpenCVInterop":
|
||||
SampleFrame.Navigate(typeof(Samples.OpenCVInterop));
|
||||
break;
|
||||
case "ImageSharpInterop":
|
||||
SampleFrame.Navigate(typeof(Samples.ImageSharpInterop));
|
||||
break;
|
||||
}
|
||||
if (sampleMetadata.Docs.Count > 0)
|
||||
DocsHeader.Visibility = Visibility.Visible;
|
||||
|
|
|
@ -36,14 +36,24 @@
|
|||
]
|
||||
},
|
||||
{
|
||||
"Title": "OpenCV Interop",
|
||||
"DescriptionShort": "The sample uses Windows ML to classify images that have been denoised using OpenCV.",
|
||||
"Title": "OpenCV",
|
||||
"DescriptionShort": "The sample uses Windows ML to classify images that have been denoised natively 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": []
|
||||
},
|
||||
{
|
||||
"Title": "ImageSharp",
|
||||
"DescriptionShort": "The sample uses Windows ML to classify images that have been loaded by the managed ImageSharp library.",
|
||||
"Description": "The sample uses Windows ML to classify images that have been rotated by the managed ImageSharp library. Choose an image to get started.",
|
||||
"Icon": "\uE155",
|
||||
"Tag": "ImageSharpInterop",
|
||||
"XAMLGithubLink": "https://github.com/microsoft/Windows-Machine-Learning/blob/master/Samples/WinMLSamplesGallery/WinMLSamplesGallery/Samples/ImageSharpInterop/ImageSharpInterop.xaml",
|
||||
"CSharpGithubLink": "https://github.com/microsoft/Windows-Machine-Learning/blob/master/Samples/WinMLSamplesGallery/WinMLSamplesGallery/Samples/ImageSharpInterop/ImageSharpInterop.xaml.cs",
|
||||
"Docs": []
|
||||
}
|
||||
]
|
||||
}
|
|
@ -0,0 +1,49 @@
|
|||
using System;
|
||||
using System.Linq;
|
||||
using System.Runtime.InteropServices.WindowsRuntime;
|
||||
|
||||
using SixLabors.ImageSharp;
|
||||
using SixLabors.ImageSharp.Processing;
|
||||
using SixLabors.ImageSharp.PixelFormats;
|
||||
using SixLabors.ImageSharp.Advanced;
|
||||
using SixLabors.ImageSharp.Memory;
|
||||
|
||||
using Microsoft.AI.MachineLearning;
|
||||
using Windows.Graphics.Imaging;
|
||||
|
||||
namespace ImageSharpExtensrions
|
||||
{
|
||||
public static class ImageExtensions
|
||||
{
|
||||
public static Windows.Storage.Streams.IBuffer AsBuffer<TPixel>(this Image<TPixel> img) where TPixel : unmanaged, IPixel<TPixel>
|
||||
{
|
||||
var memoryGroup = img.GetPixelMemoryGroup();
|
||||
var memory = memoryGroup.ToArray()[0];
|
||||
var pixelData = System.Runtime.InteropServices.MemoryMarshal.AsBytes(memory.Span).ToArray(); // Can we get rid of this?
|
||||
var buffer = pixelData.AsBuffer();
|
||||
return buffer;
|
||||
}
|
||||
|
||||
public static ITensor AsTensor<TPixel>(this Image<TPixel> img) where TPixel : unmanaged, IPixel<TPixel>
|
||||
{
|
||||
var buffer = img.AsBuffer();
|
||||
var shape = new long[] { 1, buffer.Length };
|
||||
var tensor = TensorUInt8Bit.CreateFromBuffer(shape, buffer);
|
||||
return tensor;
|
||||
}
|
||||
|
||||
|
||||
public static SoftwareBitmap AsSoftwareBitmap<TPixel>(this Image<TPixel> img) where TPixel : unmanaged, IPixel<TPixel>
|
||||
{
|
||||
var buffer = img.AsBuffer();
|
||||
var format = BitmapPixelFormat.Unknown;
|
||||
if (typeof(TPixel) == typeof(Bgra32))
|
||||
{
|
||||
format = BitmapPixelFormat.Bgra8;
|
||||
}
|
||||
|
||||
var softwareBitmap = SoftwareBitmap.CreateCopyFromBuffer(buffer, BitmapPixelFormat.Bgra8, img.Width, img.Height);
|
||||
return softwareBitmap;
|
||||
}
|
||||
}
|
||||
}
|
|
@ -0,0 +1,136 @@
|
|||
<Page
|
||||
x:Class="WinMLSamplesGallery.Samples.ImageSharpInterop"
|
||||
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">
|
||||
<Grid Width="200" Height="204">
|
||||
<Image Stretch="UniformToFill" Source="{x:Bind ImageUri}" HorizontalAlignment="Center" VerticalAlignment="Center" Height="204"/>
|
||||
</Grid>
|
||||
</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/kitten.png" />
|
||||
</GridView.Items>
|
||||
</GridView>
|
||||
</StackPanel>
|
||||
|
||||
<Slider x:Name="RotationSlider" IsEnabled="False" ValueChanged="RotationSlider_ValueChanged" Orientation="Vertical" TickFrequency="60" TickPlacement="Outside" Maximum="360" Minimum="0"/>
|
||||
<Border BorderBrush="LightGray" Padding="5,0,0,0">
|
||||
<Image x:Name="InputImage" Stretch="UniformToFill" Height="260" HorizontalAlignment="Center"/>
|
||||
</Border>
|
||||
</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,259 @@
|
|||
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;
|
||||
using SixLabors.ImageSharp;
|
||||
using SixLabors.ImageSharp.PixelFormats;
|
||||
using ImageSharpExtensrions;
|
||||
using SixLabors.ImageSharp.Processing;
|
||||
|
||||
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 ImageSharpInterop : Page
|
||||
{
|
||||
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 Image<Bgra32> CurrentImage { 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 ImageSharpInterop()
|
||||
{
|
||||
this.InitializeComponent();
|
||||
|
||||
_imagenetLabels = LoadLabels("ms-appx:///InputData/sysnet.txt");
|
||||
var tensorizationModel = TensorizationModels.BasicTensorization(Height, Width, BatchSize, Channels, Height, Width, "nearest");
|
||||
_tensorizationSession = CreateLearningModelSession(tensorizationModel, SelectedDeviceKind);
|
||||
_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(Image<Bgra32> image, float angle)
|
||||
{
|
||||
long start, stop;
|
||||
PerformanceMetricsMonitor.ClearLog();
|
||||
|
||||
// Tensorize
|
||||
start = HighResolutionClock.UtcNow();
|
||||
image.Mutate(ctx => ctx.Rotate(angle));
|
||||
var resizeOptions = new ResizeOptions()
|
||||
{
|
||||
Mode = ResizeMode.Crop,
|
||||
Size = new SixLabors.ImageSharp.Size((int)Width, (int)Height)
|
||||
};
|
||||
image.Mutate(ctx => ctx.Resize(resizeOptions));
|
||||
object input = image.AsTensor();
|
||||
var tensorizationResults = Evaluate(_tensorizationSession, input);
|
||||
object 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("Tensorize", tensorizeDuration);
|
||||
PerformanceMetricsMonitor.Log("Pre-process", 0);
|
||||
PerformanceMetricsMonitor.Log("Inference", inferenceDuration);
|
||||
PerformanceMetricsMonitor.Log("Post-process", postProcessDuration);
|
||||
|
||||
RenderingHelpers.BindSoftwareBitmapToImageControl(InputImage, image.AsSoftwareBitmap());
|
||||
image.Dispose();
|
||||
|
||||
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 (CurrentImage != null)
|
||||
{
|
||||
// Classify
|
||||
var angle = (float)RotationSlider.Value;
|
||||
var (labels, probabilities) = Classify(CurrentImage.Clone(), angle);
|
||||
|
||||
// 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;
|
||||
SetCurrentImage(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();
|
||||
SetCurrentImage(file.Path);
|
||||
TryPerformInference();
|
||||
}
|
||||
}
|
||||
|
||||
private void SetCurrentImage(string path)
|
||||
{
|
||||
if (CurrentImage != null) CurrentImage.Dispose();
|
||||
|
||||
RotationSlider.IsEnabled = true;
|
||||
|
||||
CurrentImage = SixLabors.ImageSharp.Image.Load<Bgra32>(path);
|
||||
RenderingHelpers.BindSoftwareBitmapToImageControl(InputImage, CurrentImage.AsSoftwareBitmap());
|
||||
}
|
||||
|
||||
private void DeviceComboBox_SelectionChanged(object sender, SelectionChangedEventArgs e)
|
||||
{
|
||||
TryPerformInference();
|
||||
}
|
||||
|
||||
private void RotationSlider_ValueChanged(object sender, Microsoft.UI.Xaml.Controls.Primitives.RangeBaseValueChangedEventArgs e)
|
||||
{
|
||||
TryPerformInference();
|
||||
}
|
||||
}
|
||||
}
|
|
@ -0,0 +1,34 @@
|
|||
# WinML Samples Gallery: ImageSharp Interop
|
||||
This sample demonstrates how to interop between [Windows ML](https://docs.microsoft.com/en-us/windows/ai/windows-ml/) and [ImageSharp](https://docs.sixlabors.com/articles/imagesharp/index.html).
|
||||
|
||||
ImageSharp is a new, fully featured, fully managed, cross-platform, 2D graphics library.
|
||||
|
||||
The demo will run [SqueezeNet](https://github.com/onnx/models/tree/master/vision/classification/squeezenet) image classification in WindowsML and consume images arbitrarily rotated using ImageSharp.
|
||||
|
||||
ImageSharp will be used to load, rotate, resize and crop images.
|
||||
Windows ML will be used to tensorize the image into NCHW format and 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
|
||||
You can check out the source [here](https://github.com/microsoft/Windows-Machine-Learning/blob/master/Samples/WinMLSamplesGallery/WinMLSamplesGallery/Samples/ImageSharpInterop/ImageSharpInterop.xaml.cs).
|
||||
|
||||
## 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/ImageSharpInterop/docs/screenshot.png
Normal file
Двоичные данные
Samples/WinMLSamplesGallery/WinMLSamplesGallery/Samples/ImageSharpInterop/docs/screenshot.png
Normal file
Двоичный файл не отображается.
После Ширина: | Высота: | Размер: 368 KiB |
|
@ -36,7 +36,7 @@ In order to build this sample, OpenCV will need to be built and linked into the
|
|||
- 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).
|
||||
You can check out the source [here](https://github.com/microsoft/Windows-Machine-Learning/blob/6840e7bd312b09ecd9f51127758f5168e4f844b9/Samples/WinMLSamplesGallery/WinMLSamplesGalleryNative/OpenCVImage.cpp#L19).
|
||||
|
||||
## Feedback
|
||||
Please file an issue [here](https://github.com/microsoft/Windows-Machine-Learning/issues/new) if you encounter any issues with this sample.
|
||||
|
|
|
@ -32,6 +32,7 @@
|
|||
<None Remove="Samples\ImageEffects.xaml" />
|
||||
<None Remove="Samples\ObjectDetector\ObjectDetector.xaml" />
|
||||
<None Remove="Samples\OpenCVInterop\OpenCVInterop.xaml" />
|
||||
<None Remove="Samples\ImageSharpInterop\ImageSharpInterop.xaml" />
|
||||
<None Remove="Video.xaml" />
|
||||
</ItemGroup>
|
||||
<ItemGroup>
|
||||
|
@ -73,6 +74,7 @@
|
|||
<PackageReference Include="Microsoft.AI.MachineLearning" Version="1.9.1" />
|
||||
<PackageReference Include="Microsoft.ProjectReunion" Version="0.8.4" />
|
||||
<PackageReference Include="Microsoft.Windows.CsWinRT" Version="1.3.5" />
|
||||
<PackageReference Include="SixLabors.ImageSharp" Version="1.0.4" />
|
||||
<Manifest Include="$(ApplicationManifest)" />
|
||||
</ItemGroup>
|
||||
|
||||
|
@ -80,6 +82,7 @@
|
|||
<None Include="Samples\ImageEffects\ImageEffects.xaml.cs" />
|
||||
<None Include="Samples\ImageClassifier\ImageClassifier.xaml.cs" />
|
||||
<None Include="Samples\OpenCVInterop\OpenCVInterop.xaml.cs" />
|
||||
<None Include="Samples\ImageSharpInterop\ImageSharpInterop.xaml.cs" />
|
||||
</ItemGroup>
|
||||
|
||||
<ItemGroup>
|
||||
|
@ -142,6 +145,9 @@
|
|||
<Page Update="Samples\OpenCVInterop\OpenCVInterop.xaml">
|
||||
<Generator>MSBuild:Compile</Generator>
|
||||
</Page>
|
||||
<Page Update="Samples\ImageSharpInterop\ImageSharpInterop.xaml">
|
||||
<Generator>MSBuild:Compile</Generator>
|
||||
</Page>
|
||||
</ItemGroup>
|
||||
|
||||
<ItemGroup>
|
||||
|
|
|
@ -4,7 +4,7 @@ Do Not Translate or Localize
|
|||
This software incorporates third party material from the projects listed below.
|
||||
|
||||
- opencv : https://github.com/opencv/opencv
|
||||
|
||||
- ImageSharp : https://github.com/SixLabors/ImageSharp
|
||||
-------------------------------------------------------------------------------
|
||||
opencv
|
||||
-------------------------------------------------------------------------------
|
||||
|
@ -210,3 +210,208 @@ opencv
|
|||
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.
|
||||
|
||||
-------------------------------------------------------------------------------
|
||||
ImageSharp
|
||||
-------------------------------------------------------------------------------
|
||||
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 (c) Six Labors
|
||||
|
||||
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.
|
Загрузка…
Ссылка в новой задаче