java读取tensorflow中图像的分类模型
经常在tensorflow中训练的图像模型,实际部署常见的⽤的是c++,实际java中也可以部署,在图像分类中,图像的预处理较为简单,只要做去均值和⽅差话(归⼀化),就可以使⽤,上午刚刚跟同事跑通了⾊情模型,
先看下依赖吧,其中tensorflow的版本必须是1.4.0以上,我看下1.2.1,1.3.0其中缺失了⼀个这个类,pes.Uint8,这个不能运⾏成功,只有在1.4.0的版本才开始添加成功,
. <dependency>
. <groupId&sorflow</groupId>
. <artifactId>tensorflow</artifactId>
. <version>1.4.0</version>
. </dependency>
直接看代码:
.
st;
2.
. import java.io.IOException;
. import java.io.PrintStream;
. import java.nio.charset.Charset;
. import java.nio.file.Files;
. import java.nio.file.Path;
. import java.nio.file.Paths;
. import java.util.Arrays;
. import java.util.List;
. sorflow.DataType;
.
sorflow.Graph;
. sorflow.Output;
. sorflow.Session;
. sorflow.Tensor;
. sorflow.TensorFlow;
16. sorflow.TensorFlow;
17. pes.UInt8;
18. public static void main(String[] args){
19.
20. String modelDir ="/Users/shuubiasahi/Downloads/inception5h";
21. String imageFile ="/Users/shuubiasahi/Desktop/timg.jpeg";
22.
.  byte[] graphDef = (modelDir,"sexy_inception_v4_freeze.pb"));
. List<String> labels =
.  (modelDir,"sexy_"));
.  byte[] imageBytes = (imageFile));
. Long time=System.currentTimeMillis();
. try(Tensor<Float> image = constructAndExecuteGraphToNormalizeImage(imageBytes)){
. float[] labelProbabilities = executeInceptionGraph(graphDef, image);
. int bestLabelIdx = maxIndex(labelProbabilities);
.  System.out.println(
.  String.format("BEST MATCH: %s (%.2f%% likely)",
.
  (bestLabelIdx),
.  labelProbabilities[bestLabelIdx] * 100f));
. }
.
. }
38.
. private static Tensor<Float> constructAndExecuteGraphToNormalizeImage(byte[] imageBytes){ . try(Graph g =new Graph()){
. GraphBuilder b =new GraphBuilder(g);
. // Some constants specific to the pre-trained model at:
. // /models/inception5h.zip
. //
. // - The model was trained with images scaled to 224x224 pixels.
. // - The colors, represented as R, G, B in 1-byte each were converted to
47. // float using (value - Mean)/Scale.
48.  final int H =299;
49.  final int W =299;
50.  final float mean =128f;
51.  final float scale =128f;
52.
. // Since the graph is being constructed once per execution here, we can use a constant for the . // input image. If the graph were to be re-used for multiple input images, a placeholder would . // have been more appropriate.
.  final Output<String> input = b.constant("input", imageBytes);
.  final Output<Float> output =
.  b.div(
.  b.sub(
.  b.resizeBilinear(
.  b.expandDims(
.  b.cast(b.decodeJpeg(input,3),Float.class),
.  b.constant("make_batch",0)),
.  b.constant("size",new int[]{H, W})),
.  b.constant("mean", mean)),
.  b.constant("scale", scale));
. try(Session s =new Session(g)){
.
return s.runner().fetch(output.op().name()).run().get(0).expect(Float.class);
. }
. }
. }
72.
. private static float[] executeInceptionGraph(byte[] graphDef,Tensor<Float> image){
. try(Graph g =new Graph()){
.  g.importGraphDef(graphDef);
. try(Session s =new Session(g);
Tensor<Float> result =
77. Tensor<Float> result =
78.  s.runner().feed("input", image).fetch("InceptionV4/Logits/Predictions").run().get(0).expect(Float.class)){
79.  final long[] rshape = result.shape();
80. if(result.numDimensions()!=2|| rshape[0]!=1){
81. throw new RuntimeException(
82. String.format(
83. "Expected model to produce a [1 N] shaped tensor where N is the number of labels, instead it produced one with shape
%s",
84. String(rshape)));
85. }
86. int nlabels =(int) rshape[1];
87. pyTo(new float[1][nlabels])[0];
88. }
89. }
90. }
91.
. private static int maxIndex(float[] probabilities){
. int best =0;
. for(int i =1; i < probabilities.length;++i){
. if(probabilities[i]> probabilities[best]){
.  best = i;
. }
.
}
. return best;
. }
101.
. private static byte[] readAllBytesOrExit(Path path){
. try{
. adAllBytes(path);
. }catch(IOException e){
. println("Failed to read ["+ path +"]: "+ e.getMessage());
107. it(1);
108. }
109. return null;
110. }
111.
. private static List<String> readAllLinesOrExit(Path path){
. try{
. adAllLines(path,Charset.forName("UTF-8"));
. }catch(IOException e){
. println("Failed to read ["+ path +"]: "+ e.getMessage());
. it(0);
. }
. return null;
.
}
121.
. // In the fullness of time, equivalents of the methods of this class should be auto-generated from . // the OpDefs linked into libtensorflow_jni.so. That would match what is done in other languages . // like Python, C++ and Go.
. static class GraphBuilder{
. GraphBuilder(Graph g){
. this.g = g;
. }
129.
. Output<Float> div(Output<Float> x,Output<Float> y){
. return binaryOp("Div", x, y);tensorflow版本选择
. }
133.
. <T>Output<T> sub(Output<T> x,Output<T> y){
. return binaryOp("Sub", x, y);
. }
137.

版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系QQ:729038198,我们将在24小时内删除。