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.1 kB

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