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

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119
  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 int Priority => 7;
  23. public bool Enabled { get; set; } = true;
  24. public string Name => "Image Recognition Inception";
  25. public bool ImportGraph { get; set; } = false;
  26. string dir = "ImageRecognitionInception";
  27. string pbFile = "tensorflow_inception_graph.pb";
  28. string labelFile = "imagenet_comp_graph_label_strings.txt";
  29. List<NDArray> file_ndarrays = new List<NDArray>();
  30. public bool Run()
  31. {
  32. PrepareData();
  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 labels = File.ReadAllLines(Path.Join(dir, labelFile));
  41. var result_labels = new List<string>();
  42. var sw = new Stopwatch();
  43. with(tf.Session(graph), sess =>
  44. {
  45. foreach (var nd in file_ndarrays)
  46. {
  47. sw.Restart();
  48. var results = sess.run(output_operation.outputs[0], new FeedItem(input_operation.outputs[0], nd));
  49. results = np.squeeze(results);
  50. int idx = np.argmax(results);
  51. Console.WriteLine($"{labels[idx]} {results[idx]} in {sw.ElapsedMilliseconds}ms", Color.Tan);
  52. result_labels.Add(labels[idx]);
  53. }
  54. });
  55. return result_labels.Contains("military uniform");
  56. }
  57. private NDArray ReadTensorFromImageFile(string file_name,
  58. int input_height = 224,
  59. int input_width = 224,
  60. int input_mean = 117,
  61. int input_std = 1)
  62. {
  63. return with(tf.Graph().as_default(), graph =>
  64. {
  65. var file_reader = tf.read_file(file_name, "file_reader");
  66. var decodeJpeg = tf.image.decode_jpeg(file_reader, channels: 3, name: "DecodeJpeg");
  67. var cast = tf.cast(decodeJpeg, tf.float32);
  68. var dims_expander = tf.expand_dims(cast, 0);
  69. var resize = tf.constant(new int[] { input_height, input_width });
  70. var bilinear = tf.image.resize_bilinear(dims_expander, resize);
  71. var sub = tf.subtract(bilinear, new float[] { input_mean });
  72. var normalized = tf.divide(sub, new float[] { input_std });
  73. return with(tf.Session(graph), sess => sess.run(normalized));
  74. });
  75. }
  76. public void PrepareData()
  77. {
  78. Directory.CreateDirectory(dir);
  79. // get model file
  80. string url = "https://storage.googleapis.com/download.tensorflow.org/models/inception5h.zip";
  81. Utility.Web.Download(url, dir, "inception5h.zip");
  82. Utility.Compress.UnZip(Path.Join(dir, "inception5h.zip"), dir);
  83. // download sample picture
  84. Directory.CreateDirectory(Path.Join(dir, "img"));
  85. url = $"https://raw.githubusercontent.com/tensorflow/tensorflow/master/tensorflow/examples/label_image/data/grace_hopper.jpg";
  86. Utility.Web.Download(url, Path.Join(dir, "img"), "grace_hopper.jpg");
  87. url = $"https://raw.githubusercontent.com/SciSharp/TensorFlow.NET/master/data/shasta-daisy.jpg";
  88. Utility.Web.Download(url, Path.Join(dir, "img"), "shasta-daisy.jpg");
  89. // load image file
  90. var files = Directory.GetFiles(Path.Join(dir, "img"));
  91. for (int i = 0; i < files.Length; i++)
  92. {
  93. var nd = ReadTensorFromImageFile(files[i]);
  94. file_ndarrays.Add(nd);
  95. }
  96. }
  97. }
  98. }