You can not select more than 25 topics Topics must start with a chinese character,a letter or number, can include dashes ('-') and can be up to 35 characters long.

ImageRecognitionInception.cs 4.5 kB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114
  1. using NumSharp;
  2. using System;
  3. using System.Collections.Generic;
  4. using System.Diagnostics;
  5. using System.IO;
  6. using Console = Colorful.Console;
  7. using System.Linq;
  8. using System.Net;
  9. using System.Text;
  10. using Tensorflow;
  11. using System.Drawing;
  12. namespace TensorFlowNET.Examples
  13. {
  14. /// <summary>
  15. /// Inception v3 is a widely-used image recognition model
  16. /// that has been shown to attain greater than 78.1% accuracy on the ImageNet dataset.
  17. /// The model is the culmination of many ideas developed by multiple researchers over the years.
  18. /// </summary>
  19. public class ImageRecognitionInception : Python, IExample
  20. {
  21. public int Priority => 7;
  22. public bool Enabled { get; set; } = true;
  23. public string Name => "Image Recognition Inception";
  24. public bool ImportGraph { get; set; } = false;
  25. string dir = "ImageRecognitionInception";
  26. string pbFile = "tensorflow_inception_graph.pb";
  27. string labelFile = "imagenet_comp_graph_label_strings.txt";
  28. public bool Run()
  29. {
  30. PrepareData();
  31. var labels = File.ReadAllLines(Path.Join(dir, labelFile));
  32. var files = Directory.GetFiles(Path.Join(dir, "img"));
  33. var graph = new Graph().as_default();
  34. //import GraphDef from pb file
  35. graph.Import(Path.Join(dir, pbFile));
  36. var input_name = "input";
  37. var output_name = "output";
  38. var input_operation = graph.OperationByName(input_name);
  39. var output_operation = graph.OperationByName(output_name);
  40. var result_labels = new List<string>();
  41. var sw = new Stopwatch();
  42. with(tf.Session(graph), sess =>
  43. {
  44. foreach (var file in files)
  45. {
  46. sw.Restart();
  47. // load image file
  48. var tensor = ReadTensorFromImageFile(file);
  49. var results = sess.run(output_operation.outputs[0], new FeedItem(input_operation.outputs[0], tensor));
  50. results = np.squeeze(results);
  51. int idx = np.argmax(results);
  52. Console.WriteLine($"{file.Split(Path.DirectorySeparatorChar).Last()}: {labels[idx]} {results[idx]} in {sw.ElapsedMilliseconds}ms", Color.Tan);
  53. result_labels.Add(labels[idx]);
  54. }
  55. });
  56. return result_labels.Contains("military uniform");
  57. }
  58. private NDArray ReadTensorFromImageFile(string file_name,
  59. int input_height = 224,
  60. int input_width = 224,
  61. int input_mean = 117,
  62. int input_std = 1)
  63. {
  64. return with(tf.Graph(), graph =>
  65. {
  66. var file_reader = tf.read_file(file_name, "file_reader");
  67. var decodeJpeg = tf.image.decode_jpeg(file_reader, channels: 3, name: "DecodeJpeg");
  68. var cast = tf.cast(decodeJpeg, tf.float32);
  69. var dims_expander = tf.expand_dims(cast, 0);
  70. var resize = tf.constant(new int[] { input_height, input_width });
  71. var bilinear = tf.image.resize_bilinear(dims_expander, resize);
  72. var sub = tf.subtract(bilinear, new float[] { input_mean });
  73. var normalized = tf.divide(sub, new float[] { input_std });
  74. return with(tf.Session(graph), sess => sess.run(normalized));
  75. });
  76. }
  77. public void PrepareData()
  78. {
  79. Directory.CreateDirectory(dir);
  80. // get model file
  81. string url = "https://storage.googleapis.com/download.tensorflow.org/models/inception5h.zip";
  82. Utility.Web.Download(url, dir, "inception5h.zip");
  83. Utility.Compress.UnZip(Path.Join(dir, "inception5h.zip"), dir);
  84. // download sample picture
  85. Directory.CreateDirectory(Path.Join(dir, "img"));
  86. url = $"https://raw.githubusercontent.com/tensorflow/tensorflow/master/tensorflow/examples/label_image/data/grace_hopper.jpg";
  87. Utility.Web.Download(url, Path.Join(dir, "img"), "grace_hopper.jpg");
  88. url = $"https://raw.githubusercontent.com/SciSharp/TensorFlow.NET/master/data/shasta-daisy.jpg";
  89. Utility.Web.Download(url, Path.Join(dir, "img"), "shasta-daisy.jpg");
  90. }
  91. }
  92. }

tensorflow框架的.NET版本,提供了丰富的特性和API,可以借此很方便地在.NET平台下搭建深度学习训练与推理流程。