Win10之后,许多之前常用的应用,包括录音机、照相机等,都被归为了 Microsoft App Store 所管理的范畴,无法直接通过诸如 Process.Start(“video.exe”)、Process.Start(“camera.exe”)等命令调用。目前较为可行的方法是,通过调用 cmd,再将自动填入命令,最终实现 App 的调用。示例代码如下:
TFGraph graph = new TFGraph();
//重点是下面的这句,把训练好的pb文件给读出来字节,然后导入
string modelPath = Directory.GetCurrentDirectory() + "\\model.pb";
byte[] model = File.ReadAllBytes(modelPath);
graph.Import(model);
var tensor = ImageUtil.CreateTensorFromImageFile(picturePath);
using (var sess = new TFSession(graph))
{
// 计算类别概率
var runner = sess.GetRunner();
runner.AddInput(graph["Mul"][0], tensor);
var r = runner.Run(graph.Softmax(graph["final_result"][0]));
var v = (float[,])r.GetValue();
}
其中,ImageUtil 代码如下:
publicstaticclassImageUtil
{
publicstatic TFTensor CreateTensorFromImageFile(byte[] contents, TFDataType destinationDataType = TFDataType.Float)
{
var tensor = TFTensor.CreateString(contents);
TFOutput input, output;
// Construct a graph to normalize the image
using (var graph = ConstructGraphToNormalizeImage(out input, out output, destinationDataType))
{
// Execute that graph to normalize this one image
using (var session = new TFSession(graph))
{
var normalized = session.Run(
inputs: new[] { input },
inputValues: new[] { tensor },
outputs: new[] { output });
return normalized[0];
}
}
}
// Convert the image in filename to a Tensor suitable as input to the Inception model.
publicstatic TFTensor CreateTensorFromImageFile(string file, TFDataType destinationDataType = TFDataType.Float)
{
//Thread.Sleep(500);
var contents = File.ReadAllBytes(file);
// DecodeJpeg uses a scalar String-valued tensor as input.
var tensor = TFTensor.CreateString(contents);
TFOutput input, output;
// Construct a graph to normalize the image
using (var g = ConstructGraphToNormalizeImage(out input, out output, destinationDataType))
{
// Execute that graph to normalize this one image
using (var sess = new TFSession(g))
{
var normalized = sess.Run(
inputs: new[] { input },
inputValues: new[] { tensor },
outputs: new[] { output });
return normalized[0];
}
}
}
privatestatic TFGraph ConstructGraphToNormalizeImage(out TFOutput input, out TFOutput output, TFDataType destinationDataType = TFDataType.Float)
{
// 以下四个参数,根据模型的输入层确定
constint W = 299;
constint H = 299;
constfloat Mean = 128;
constfloat Scale = 128;
var graph = new TFGraph();
input = graph.Placeholder(TFDataType.String);
output = graph.Cast(
graph.Div(x: graph.Sub(x: graph.ResizeBilinear(images: graph.ExpandDims(input: graph.Cast(graph.DecodeJpeg(contents: input, channels: 3), DstT: TFDataType.Float),
dim: graph.Const(0, "make_batch")),
size: graph.Const(newint[] { W, H }, "INPUT_SIZE")),
y: graph.Const(Mean, "IMAGE_MEAN")),
y: graph.Const(Scale, "IMAGE_STD")), destinationDataType);
return graph;
}
}