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.

LabelImage.cs 4.4 kB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120
  1. using ICSharpCode.SharpZipLib.GZip;
  2. using ICSharpCode.SharpZipLib.Tar;
  3. using NumSharp.Core;
  4. using System;
  5. using System.Collections.Generic;
  6. using System.IO;
  7. using System.Linq;
  8. using System.Net;
  9. using System.Text;
  10. using System.Threading;
  11. using System.Threading.Tasks;
  12. using Tensorflow;
  13. namespace TensorFlowNET.Examples
  14. {
  15. /// <summary>
  16. /// Port from tensorflow\examples\label_image\label_image.py
  17. /// </summary>
  18. public class LabelImage : Python, IExample
  19. {
  20. string dir = "label_image_data";
  21. string pbFile = "inception_v3_2016_08_28_frozen.pb";
  22. string labelFile = "imagenet_slim_labels.txt";
  23. string picFile = "grace_hopper.jpg";
  24. int input_height = 299;
  25. int input_width = 299;
  26. int input_mean = 0;
  27. int input_std = 255;
  28. string input_layer = "input";
  29. string output_layer = "InceptionV3/Predictions/Reshape_1";
  30. public void Run()
  31. {
  32. PrepareData();
  33. var graph = LoadGraph(Path.Join(dir, pbFile));
  34. var t = ReadTensorFromImageFile(Path.Join(dir, picFile),
  35. input_height: input_height,
  36. input_width: input_width,
  37. input_mean: input_mean,
  38. input_std: input_std);
  39. var input_name = "import/" + input_layer;
  40. var output_name = "import/" + output_layer;
  41. var input_operation = graph.get_operation_by_name(input_name);
  42. var output_operation = graph.get_operation_by_name(output_name);
  43. NDArray results = null;
  44. with<Session>(tf.Session(graph), sess =>
  45. {
  46. results = sess.run(output_operation.outputs[0], new FeedItem(input_operation.outputs[0], t));
  47. });
  48. // equivalent np.squeeze
  49. results.reshape(results.shape.Where(x => x > 1).ToArray());
  50. // top_k = results.argsort()[-5:][::-1]
  51. var top_k = results.Data<int>().Take(5).ToArray();
  52. var labels = LoadLabels(Path.Join(dir, labelFile));
  53. foreach (var i in top_k)
  54. Console.WriteLine($"{labels[i]}, {results[i]}");
  55. }
  56. private string[] LoadLabels(string file)
  57. {
  58. return File.ReadAllLines(file);
  59. }
  60. private Graph LoadGraph(string modelFile)
  61. {
  62. var graph = tf.Graph();
  63. var graph_def = GraphDef.Parser.ParseFrom(File.ReadAllBytes(modelFile));
  64. importer.import_graph_def(graph_def);
  65. return graph;
  66. }
  67. private NDArray ReadTensorFromImageFile(string file_name,
  68. int input_height = 299,
  69. int input_width = 299,
  70. int input_mean = 0,
  71. int input_std = 255)
  72. {
  73. string input_name = "file_reader";
  74. string output_name = "normalized";
  75. Tensor image_reader = null;
  76. var file_reader = tf.read_file(file_name, input_name);
  77. image_reader = tf.image.decode_jpeg(file_reader, channels: 3, name: "jpeg_reader");
  78. var float_caster = tf.cast(image_reader, tf.float32);
  79. var dims_expander = tf.expand_dims(float_caster, 0);
  80. var resized = tf.image.resize_bilinear(dims_expander, new int[] { input_height, input_width });
  81. var normalized = tf.divide(tf.subtract(resized, new float[] { input_mean }), new float[] { input_std });
  82. return with<Session, NDArray>(tf.Session(), sess =>
  83. {
  84. var result = sess.run(normalized);
  85. return result;
  86. });
  87. }
  88. private void PrepareData()
  89. {
  90. Directory.CreateDirectory(dir);
  91. // get model file
  92. string url = "https://storage.googleapis.com/download.tensorflow.org/models/inception_v3_2016_08_28_frozen.pb.tar.gz";
  93. string zipFile = Path.Join(dir, $"{pbFile}.tar.gz");
  94. Utility.Web.Download(url, zipFile);
  95. if (!File.Exists(Path.Join(dir, pbFile)))
  96. Utility.Compress.ExtractTGZ(zipFile, dir);
  97. // download sample picture
  98. string pic = "grace_hopper.jpg";
  99. Utility.Web.Download($"https://raw.githubusercontent.com/tensorflow/tensorflow/master/tensorflow/examples/label_image/data/{pic}", Path.Join(dir, pic));
  100. }
  101. }
  102. }

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