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.

ImageBackgroundRemoval.cs 2.1 kB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263
  1. using System;
  2. using System.Collections.Generic;
  3. using System.IO;
  4. using System.Text;
  5. using Tensorflow;
  6. using TensorFlowNET.Examples.Utility;
  7. using static Tensorflow.Python;
  8. namespace TensorFlowNET.Examples.ImageProcess
  9. {
  10. /// <summary>
  11. /// This example removes the background from an input image.
  12. ///
  13. /// https://github.com/susheelsk/image-background-removal
  14. /// </summary>
  15. public class ImageBackgroundRemoval : IExample
  16. {
  17. public int Priority => 15;
  18. public bool Enabled { get; set; } = true;
  19. public bool ImportGraph { get; set; } = true;
  20. public string Name => "Image Background Removal";
  21. string dataDir = "deeplabv3";
  22. string modelDir = "deeplabv3_mnv2_pascal_train_aug";
  23. string modelName = "frozen_inference_graph.pb";
  24. public bool Run()
  25. {
  26. PrepareData();
  27. // import GraphDef from pb file
  28. var graph = new Graph().as_default();
  29. graph.Import(Path.Join(dataDir, modelDir, modelName));
  30. Tensor output = graph.OperationByName("SemanticPredictions");
  31. with(tf.Session(graph), sess =>
  32. {
  33. // Runs inference on a single image.
  34. sess.run(output, new FeedItem(output, "[np.asarray(resized_image)]"));
  35. });
  36. return false;
  37. }
  38. public void PrepareData()
  39. {
  40. // get mobile_net_model file
  41. string fileName = "deeplabv3_mnv2_pascal_train_aug_2018_01_29.tar.gz";
  42. string url = $"http://download.tensorflow.org/models/{fileName}";
  43. Web.Download(url, dataDir, fileName);
  44. Compress.ExtractTGZ(Path.Join(dataDir, fileName), dataDir);
  45. // xception_model, better accuracy
  46. /*fileName = "deeplabv3_pascal_train_aug_2018_01_04.tar.gz";
  47. url = $"http://download.tensorflow.org/models/{fileName}";
  48. Web.Download(url, modelDir, fileName);
  49. Compress.ExtractTGZ(Path.Join(modelDir, fileName), modelDir);*/
  50. }
  51. }
  52. }

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