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 5.0 kB

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