Guest User

Untitled

a guest
Mar 23rd, 2018
90
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 8.70 KB | None | 0 0
  1. using System;
  2. using System.Collections.Generic;
  3. using System.IO;
  4. using System.Linq;
  5. using Windows.UI.Xaml;
  6. using Windows.UI.Xaml.Controls;
  7. using Windows.AI.MachineLearning.Preview;
  8. using Windows.Storage;
  9. using Windows.Media;
  10. using Windows.Graphics.Imaging;
  11. using System.Threading.Tasks;
  12. using Windows.Storage.Streams;
  13. using Windows.UI.Core;
  14. using Windows.Storage.Pickers;
  15. using Windows.UI.Xaml.Media.Imaging;
  16.  
  17. namespace SqueezeNetObjectDetection
  18. {
  19. /// <summary>
  20. /// An empty page that can be used on its own or navigated to within a Frame.
  21. /// </summary>
  22. public sealed partial class MainPage : Page
  23. {
  24. private const string _kModelFileName = "SqueezeNet.onnx";
  25. private const string _kLabelsFileName = "Labels.json";
  26. private ImageVariableDescriptorPreview _inputImageDescription;
  27. private TensorVariableDescriptorPreview _outputTensorDescription;
  28. private LearningModelPreview _model = null;
  29. private List<string> _labels = new List<string>();
  30. List<float> _outputVariableList = new List<float>();
  31.  
  32. public MainPage()
  33. {
  34. this.InitializeComponent();
  35. }
  36.  
  37. /// <summary>
  38. /// Load the label and model files
  39. /// </summary>
  40. /// <returns></returns>
  41. private async Task LoadModelAsync()
  42. {
  43. await Dispatcher.RunAsync(CoreDispatcherPriority.Normal, () => StatusBlock.Text = $"Loading {_kModelFileName} ... patience ");
  44.  
  45. try
  46. {
  47. // Parse labels from label file
  48. var file = await StorageFile.GetFileFromApplicationUriAsync(new Uri($"ms-appx:///Assets/{_kLabelsFileName}"));
  49. using (var inputStream = await file.OpenReadAsync())
  50. using (var classicStream = inputStream.AsStreamForRead())
  51. using (var streamReader = new StreamReader(classicStream))
  52. {
  53. string line = "";
  54. char[] charToTrim = { '\"', ' ' };
  55. while (streamReader.Peek() >= 0)
  56. {
  57. line = streamReader.ReadLine();
  58. line.Trim(charToTrim);
  59. var indexAndLabel = line.Split(':');
  60. if (indexAndLabel.Count() == 2)
  61. {
  62. _labels.Add(indexAndLabel[1]);
  63. }
  64. }
  65. }
  66.  
  67. // Load Model
  68. var modelFile = await StorageFile.GetFileFromApplicationUriAsync(new Uri($"ms-appx:///Assets/{_kModelFileName}"));
  69. _model = await LearningModelPreview.LoadModelFromStorageFileAsync(modelFile);
  70.  
  71. // Retrieve model input and output variable descriptions (we already know the model takes an image in and outputs a tensor)
  72. List<ILearningModelVariableDescriptorPreview> inputFeatures = _model.Description.InputFeatures.ToList();
  73. List<ILearningModelVariableDescriptorPreview> outputFeatures = _model.Description.OutputFeatures.ToList();
  74.  
  75. _inputImageDescription =
  76. inputFeatures.FirstOrDefault(feature => feature.ModelFeatureKind == LearningModelFeatureKindPreview.Image)
  77. as ImageVariableDescriptorPreview;
  78.  
  79. _outputTensorDescription =
  80. outputFeatures.FirstOrDefault(feature => feature.ModelFeatureKind == LearningModelFeatureKindPreview.Tensor)
  81. as TensorVariableDescriptorPreview;
  82. }
  83. catch (Exception ex)
  84. {
  85. await Dispatcher.RunAsync(CoreDispatcherPriority.Normal, () => StatusBlock.Text = $"error: {ex.Message}");
  86. _model = null;
  87. }
  88. }
  89.  
  90. /// <summary>
  91. /// Trigger file picker and image evaluation
  92. /// </summary>
  93. /// <param name="sender"></param>
  94. /// <param name="e"></param>
  95. private async void ButtonRun_Click(object sender, RoutedEventArgs e)
  96. {
  97. ButtonRun.IsEnabled = false;
  98. UIPreviewImage.Source = null;
  99. try
  100. {
  101. // Load the model
  102. await Task.Run(async () => await LoadModelAsync());
  103.  
  104. // Trigger file picker to select an image file
  105. FileOpenPicker fileOpenPicker = new FileOpenPicker();
  106. fileOpenPicker.SuggestedStartLocation = PickerLocationId.PicturesLibrary;
  107. fileOpenPicker.FileTypeFilter.Add(".jpg");
  108. fileOpenPicker.FileTypeFilter.Add(".png");
  109. fileOpenPicker.ViewMode = PickerViewMode.Thumbnail;
  110. StorageFile selectedStorageFile = await fileOpenPicker.PickSingleFileAsync();
  111.  
  112. SoftwareBitmap softwareBitmap;
  113. using (IRandomAccessStream stream = await selectedStorageFile.OpenAsync(FileAccessMode.Read))
  114. {
  115. // Create the decoder from the stream
  116. BitmapDecoder decoder = await BitmapDecoder.CreateAsync(stream);
  117.  
  118. // Get the SoftwareBitmap representation of the file in BGRA8 format
  119. softwareBitmap = await decoder.GetSoftwareBitmapAsync();
  120. softwareBitmap = SoftwareBitmap.Convert(softwareBitmap, BitmapPixelFormat.Bgra8, BitmapAlphaMode.Premultiplied);
  121. }
  122.  
  123. // Display the image
  124. SoftwareBitmapSource imageSource = new SoftwareBitmapSource();
  125. await imageSource.SetBitmapAsync(softwareBitmap);
  126. UIPreviewImage.Source = imageSource;
  127.  
  128. // Encapsulate the image within a VideoFrame to be bound and evaluated
  129. VideoFrame inputImage = VideoFrame.CreateWithSoftwareBitmap(softwareBitmap);
  130.  
  131. await Task.Run(async () =>
  132. {
  133. // Evaluate the image
  134. await EvaluateVideoFrameAsync(inputImage);
  135. });
  136. }
  137. catch (Exception ex)
  138. {
  139. await Dispatcher.RunAsync(CoreDispatcherPriority.Normal, () => StatusBlock.Text = $"error: {ex.Message}");
  140. ButtonRun.IsEnabled = true;
  141. }
  142. }
  143.  
  144. /// <summary>
  145. /// Evaluate the VideoFrame passed in as arg
  146. /// </summary>
  147. /// <param name="inputFrame"></param>
  148. /// <returns></returns>
  149. private async Task EvaluateVideoFrameAsync(VideoFrame inputFrame)
  150. {
  151. if (inputFrame != null)
  152. {
  153. try
  154. {
  155. // Create bindings for the input and output buffer
  156. LearningModelBindingPreview binding = new LearningModelBindingPreview(_model as LearningModelPreview);
  157. binding.Bind(_inputImageDescription.Name, inputFrame);
  158. binding.Bind(_outputTensorDescription.Name, _outputVariableList);
  159.  
  160. // Process the frame with the model
  161. LearningModelEvaluationResultPreview results = await _model.EvaluateAsync(binding, "test");
  162. List<float> resultProbabilities = results.Outputs[_outputTensorDescription.Name] as List<float>;
  163.  
  164. // Find the result of the evaluation in the bound output (the top classes detected with the max confidence)
  165. List<float> topProbabilities = new List<float>() { 0.0f, 0.0f, 0.0f };
  166. List<int> topProbabilityLabelIndexes = new List<int>() { 0, 0, 0 };
  167. for (int i = 0; i < resultProbabilities.Count(); i++)
  168. {
  169. for (int j = 0; j < 3; j++)
  170. {
  171. if (resultProbabilities[i] > topProbabilities[j])
  172. {
  173. topProbabilityLabelIndexes[j] = i;
  174. topProbabilities[j] = resultProbabilities[i];
  175. break;
  176. }
  177. }
  178. }
  179.  
  180. // Display the result
  181. string message = "Predominant objects detected are:";
  182. for (int i = 0; i < 3; i++)
  183. {
  184. message += $"\n{ _labels[topProbabilityLabelIndexes[i]]} with confidence of { topProbabilities[i]}";
  185. }
  186. await Dispatcher.RunAsync(CoreDispatcherPriority.Normal, () => StatusBlock.Text = message);
  187. }
  188. catch (Exception ex)
  189. {
  190. await Dispatcher.RunAsync(CoreDispatcherPriority.Normal, () => StatusBlock.Text = $"error: {ex.Message}");
  191. }
  192.  
  193. await Dispatcher.RunAsync(CoreDispatcherPriority.Normal, () => ButtonRun.IsEnabled = true);
  194. }
  195. }
  196. }
  197. }
Add Comment
Please, Sign In to add comment