org.tensorflow.Session Java Examples

The following examples show how to use org.tensorflow.Session. You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example #1
Source File: DLSegment.java    From orbit-image-analysis with GNU General Public License v3.0 6 votes vote down vote up
public static void main3(String[] args) throws IOException {
    Session s = DLSegment.buildSession(DEMO_MODEL_NAME);

    BufferedImage sourceImage = ImageIO.read(new File(INPUT_IMAGE));
    BufferedImage bi1 = new BufferedImage(1024,1024,BufferedImage.TYPE_INT_RGB);
    bi1.getGraphics().drawImage(sourceImage,0,0,null);
    bi1.getGraphics().drawImage(sourceImage,512,0,null);
    bi1.getGraphics().drawImage(sourceImage,0,512,null);
    bi1.getGraphics().drawImage(sourceImage,512,512,null);
    BufferedImage bi2 = new BufferedImage(512,512,BufferedImage.TYPE_INT_RGB);
    bi2.getGraphics().drawImage(bi1,0,0,512,512,null);
    sourceImage = bi2;

    Tensor<Float> inputTensor = convertBufferedImageToTensor(sourceImage);
    BufferedImage bufferedImage =  DLSegment.segmentInput(inputTensor,s, Color.black, Color.green);
    s.close();

    BufferedImage bi3 = new BufferedImage(512,512,BufferedImage.TYPE_INT_RGB);
    bi3.getGraphics().drawImage(bufferedImage,0,0,1024,1024,null);

    ImageIO.write(bi3, "jpg", new File(DEMO_OUTPUT_IMAGE));
}
 
Example #2
Source File: ShapeOpsTest.java    From java with Apache License 2.0 6 votes vote down vote up
/**
 * Test of size method, of class ShapeOps.
 */
@Test
public void testSize_Shape() {
    try (Graph g = new Graph();
            Session session = new Session(g)) {
        Scope scope = new Scope(g);
        Operand operand = Constant.arrayOf(scope, new float[]{1, 2, 3, 4, 5, 6, 7, 8});
        Operand actual = Reshape.create(scope, operand, Constant.vectorOf(scope, new long[]{4, 2, 1}));
        Shape<TInt64> tfshape = Shape.create(scope, actual, TInt64.DTYPE);
        Operand<TInt64> size = ShapeOps.size(scope, tfshape, TInt64.DTYPE);

        AtomicInteger index = new AtomicInteger();
        try (Tensor<TInt64> result1 = session.runner().fetch(size.asOutput()).run().get(0).expect(TInt64.DTYPE)) {
            result1.data().scalars().forEach(s -> assertEquals(8, s.getLong()));
        }
    }
}
 
Example #3
Source File: ConstantTest.java    From java with Apache License 2.0 6 votes vote down vote up
@Test
public void createStrings() throws IOException {
  DataBuffer<String> buffer = DataBuffers.ofObjects("1", "2", "3", "4");
  Shape shape = Shape.of(4);
  NdArray<String> array = NdArrays.wrap(shape, buffer);

  try (Graph g = new Graph();
      Session sess = new Session(g)) {
    Scope scope = new Scope(g);
    Constant<TString> op1 = Constant.tensorOf(scope, shape, buffer);
    Constant<TString> op2 = Constant.tensorOf(scope, array);
    try (AutoCloseableList<Tensor<?>> t =
        new AutoCloseableList<>(sess.runner().fetch(op1).fetch(op2).run())) {
      assertEquals(array, t.get(0).expect(TString.DTYPE).data());
      assertEquals(array, t.get(1).expect(TString.DTYPE).data());
    }
  }
}
 
Example #4
Source File: MRCNNCorpusCallosum.java    From orbit-image-analysis with GNU General Public License v3.0 6 votes vote down vote up
public static void main(String[] args) throws IOException {
    Date startDate = new Date();
    MRCNNCorpusCallosum maskRCNN = new MRCNNCorpusCallosum();
    byte[] graphDef = Files.readAllBytes(Paths.get(MODEL_FN));
    try (Graph g = maskRCNN.loadGraph(graphDef);
         Session s = maskRCNN.createSession(g)) {
        BufferedImage originalImage = ImageIO.read(new File(INPUT_IMAGE));
        long startt = System.currentTimeMillis();
        Tensor<Float> input = DLHelpers.convertBufferedImageToTensor(originalImage, size, size);
        if (input != null) {
            RawDetections rawDetections = DLHelpers.executeInceptionGraph(s, input, size, size, MAX_DETECTIONS, maskWidth, maskHeight);
            Detections detections = maskRCNN.processDetections(size,size,rawDetections);
            BufferedImage outputImage = DLHelpers.augmentDetections(originalImage, detections);
            ImageIO.write(outputImage, "png", new File(OUTPUT_IMAGE));
        }
        long used = System.currentTimeMillis()-startt;
        System.out.println("time used: "+used/1000d);
    }

    long elapsedTimeInSec = (new Date().getTime() - startDate.getTime()) / 1000;
    System.out.println(String.format("Ended in %ds .", elapsedTimeInSec));
}
 
Example #5
Source File: GradientsTest.java    From java with Apache License 2.0 6 votes vote down vote up
@Test
public void createGradients() {
  try (Graph g = new Graph();
      Session sess = new Session(g)) {
    Ops tf = Ops.create(g);

    Output<TFloat32> x = tf.placeholder(TFloat32.DTYPE).output();
    Output<TFloat32> y0 = tf.math.square(x).y();
    Output<TFloat32> y1 = tf.math.square(y0).y();

    Gradients grads = Gradients.create(tf.scope(), y1, Arrays.asList(x, y0));

    assertNotNull(grads);
    assertNotNull(grads.dy());
    assertEquals(2, grads.dy().size());

    try (Tensor<TFloat32> c = TFloat32.scalarOf(3.0f);
        AutoCloseableList<Tensor<?>> outputs =
            new AutoCloseableList<>(
                sess.runner().feed(x, c).fetch(grads.dy(0)).fetch(grads.dy(1)).run())) {

      assertEquals(108.0f, outputs.get(0).expect(TFloat32.DTYPE).data().getFloat(), 0.0f);
      assertEquals(18.0f, outputs.get(1).expect(TFloat32.DTYPE).data().getFloat(), 0.0f);
    }
  }
}
 
Example #6
Source File: GradientsTest.java    From java with Apache License 2.0 6 votes vote down vote up
@Test
public void createGradientsWithSum() {
  try (Graph g = new Graph();
      Session sess = new Session(g)) {
    Ops tf = Ops.create(g);

    Output<TFloat32> x = tf.placeholder(TFloat32.DTYPE).output();
    Output<TFloat32> y0 = tf.math.square(x).y();
    Output<TFloat32> y1 = tf.math.square(y0).y();

    Gradients grads = Gradients.create(tf.scope(), Arrays.asList(y0, y1), Arrays.asList(x));

    assertNotNull(grads);
    assertNotNull(grads.dy());
    assertEquals(1, grads.dy().size());

    try (Tensor<TFloat32> c = TFloat32.scalarOf(3.0f);
        AutoCloseableList<Tensor<?>> outputs =
            new AutoCloseableList<>(sess.runner().feed(x, c).fetch(grads.dy(0)).run())) {

      assertEquals(114.0f, outputs.get(0).expect(TFloat32.DTYPE).data().getFloat(), 0.0f);
    }
  }
}
 
Example #7
Source File: GradientsTest.java    From java with Apache License 2.0 6 votes vote down vote up
@Test
public void createGradientsWithInitialValues() {
  try (Graph g = new Graph();
      Session sess = new Session(g)) {
    Ops tf = Ops.create(g);

    Output<TFloat32> x = tf.placeholder(TFloat32.DTYPE).output();
    Output<TFloat32> y0 = tf.math.square(x).y();
    Output<TFloat32> y1 = tf.math.square(y0).y();

    Gradients grads0 = Gradients.create(tf.scope(), y1, Arrays.asList(y0));
    Gradients grads1 = Gradients.create(tf.scope(), y0, Arrays.asList(x), Gradients.dx(grads0.dy()));

    assertNotNull(grads1);
    assertNotNull(grads1.dy());
    assertEquals(1, grads1.dy().size());

    try (Tensor<TFloat32> c = TFloat32.scalarOf(3.0f);
        AutoCloseableList<Tensor<?>> outputs =
            new AutoCloseableList<>(
                sess.runner().feed(x, c).fetch(grads1.dy(0)).run())) {

      assertEquals(108.0f, outputs.get(0).expect(TFloat32.DTYPE).data().getFloat(), 0.0f);
    }
  }
}
 
Example #8
Source File: ConstantTest.java    From java with Apache License 2.0 6 votes vote down vote up
@Test
public void createFloats() {
  FloatDataBuffer buffer = DataBuffers.of(1.0f, 2.0f, 3.0f, 4.0f);
  Shape shape = Shape.of(4);
  FloatNdArray array = NdArrays.wrap(shape, buffer);

  try (Graph g = new Graph();
      Session sess = new Session(g)) {
    Scope scope = new Scope(g);
    Constant<TFloat32> op1 = Constant.tensorOf(scope, shape, buffer);
    Constant<TFloat32> op2 = Constant.tensorOf(scope, array);
    try (AutoCloseableList<Tensor<?>> t =
        new AutoCloseableList<>(sess.runner().fetch(op1).fetch(op2).run())) {
      assertEquals(array, t.get(0).expect(TFloat32.DTYPE).data());
      assertEquals(array, t.get(1).expect(TFloat32.DTYPE).data());
    }
  }
}
 
Example #9
Source File: ShapeOpsTest.java    From java with Apache License 2.0 6 votes vote down vote up
/**
 * Test of flatten method, of class ShapeOps.
 */
@Test
public void testFlatten_Operand() {
    try (Graph g = new Graph();
            Session session = new Session(g)) {
        Scope scope = new Scope(g);
        Operand<TFloat32> operand = Constant.arrayOf(scope, new float[]{1, 2, 3, 4, 5, 6, 7, 8});
        Shape<TInt64> expResult = Shape.create(scope, operand, TInt64.DTYPE);
        Operand<TFloat32> reshaped = Reshape.create(scope, operand, Constant.vectorOf(scope, new long[]{4, 2, 1}));
        Operand actual = ShapeOps.flatten(scope, reshaped);
        Shape<TInt64> tfshape = Shape.create(scope, actual, TInt64.DTYPE);

        AtomicInteger index = new AtomicInteger();
        try (Tensor<TInt64> result1 = session.runner().fetch(tfshape.asOutput()).run().get(0).expect(TInt64.DTYPE);
                Tensor<TInt64> result2 = session.runner().fetch(expResult.asOutput()).run().get(0).expect(TInt64.DTYPE)) {
            result1.data().scalars().forEach(s -> assertEquals(
                    result2.data().getLong(index.getAndIncrement()), s.getLong()));
        }
    }
}
 
Example #10
Source File: ShapeOpsTest.java    From java with Apache License 2.0 6 votes vote down vote up
/**
 * Test of size method, of class ShapeOps.
 */
@Test
public void testSize_Shape_Operand() {
    try (Graph g = new Graph();
            Session session = new Session(g)) {
        Scope scope = new Scope(g);
        Operand operand = Constant.arrayOf(scope, new float[]{1, 2, 3, 4, 5, 6, 7, 8});
        Operand actual = Reshape.create(scope, operand, Constant.vectorOf(scope, new long[]{4, 2, 1}));
        Shape<TInt32> tfshape = Shape.create(scope, actual);

        Operand<TInt32> size = ShapeOps.size(scope, tfshape, Constant.scalarOf(scope, 0));
        try (Tensor<TInt32> result = session.runner().fetch(size.asOutput()).run().get(0).expect(TInt32.DTYPE)) {
            result.data().scalars().forEach(s -> assertEquals(4, s.getInt()));
        }

        size = ShapeOps.size(scope, tfshape, Constant.scalarOf(scope, 1));
        try (Tensor<TInt32> result = session.runner().fetch(size.asOutput()).run().get(0).expect(TInt32.DTYPE)) {
            result.data().scalars().forEach(s -> assertEquals(2, s.getInt()));
        }

        size = ShapeOps.size(scope, tfshape, Constant.scalarOf(scope, 2));
        try (Tensor<TInt32> result = session.runner().fetch(size.asOutput()).run().get(0).expect(TInt32.DTYPE)) {
            result.data().scalars().forEach(s -> assertEquals(1, s.getInt()));
        }
    }
}
 
Example #11
Source File: ShapeOpsTest.java    From java with Apache License 2.0 6 votes vote down vote up
/**
 * Test of size method, of class ShapeOps.
 */
@Test
public void testSize_Operand_Operand() {
    try (Graph g = new Graph();
            Session session = new Session(g)) {
        Scope scope = new Scope(g);
        Operand operand = Constant.arrayOf(scope, new float[]{1, 2, 3, 4, 5, 6, 7, 8});
        Operand actual = Reshape.create(scope, operand, Constant.vectorOf(scope, new long[]{4, 2, 1}));

        Operand<TInt32> size = ShapeOps.size(scope, actual, Constant.scalarOf(scope, 0));
        try (Tensor<TInt32> result = session.runner().fetch(size.asOutput()).run().get(0).expect(TInt32.DTYPE)) {
            result.data().scalars().forEach(s -> assertEquals(4, s.getInt()));
        }

        size = ShapeOps.size(scope, actual, Constant.scalarOf(scope, 1));
        try (Tensor<TInt32> result = session.runner().fetch(size.asOutput()).run().get(0).expect(TInt32.DTYPE)) {
            result.data().scalars().forEach(s -> assertEquals(2, s.getInt()));
        }

        size = ShapeOps.size(scope, actual, Constant.scalarOf(scope, 2));
        try (Tensor<TInt32> result = session.runner().fetch(size.asOutput()).run().get(0).expect(TInt32.DTYPE)) {
            result.data().scalars().forEach(s -> assertEquals(1, s.getInt()));
        }
    }
}
 
Example #12
Source File: ShapeOpsTest.java    From java with Apache License 2.0 6 votes vote down vote up
/**
 * Test of squeeze method, of class ShapeOps.
 */
@Test
public void testSqueeze() {
    try (Graph g = new Graph();
            Session session = new Session(g)) {
        Scope scope = new Scope(g);
        Operand operand = Constant.arrayOf(scope, new float[]{1, 2, 3, 4, 5, 6, 7, 8});
        Operand actual = Reshape.create(scope, operand, Constant.vectorOf(scope, new long[]{4, 1, 2, 1}));
        Shape<TInt32> tfshape = Shape.create(scope, actual);

        Operand<TInt32> squeezed = ShapeOps.squeeze(scope, tfshape);
        AtomicInteger index = new AtomicInteger();
        int[] expected = {4, 2};
        try (Tensor<TInt32> result = session.runner().fetch(squeezed.asOutput()).run().get(0).expect(TInt32.DTYPE)) {
            result.data().scalars().forEach(s -> {
                assertEquals(expected[index.getAndIncrement()], s.getInt());
            });
        }
        assertEquals(expected.length, index.get());

    }
}
 
Example #13
Source File: GeneratedOperationsTest.java    From java with Apache License 2.0 6 votes vote down vote up
/**
 * Test for Ops.withControlDependencies.
 *
 * <p>Creates an add node with a control dependency to an assign node. In other words, the assign
 * node is a control input to the add node. When the add node is run, the assign node is expected
 * to have run beforehand due to the control dependency.
 */
@Test
public void testControlDependencies() {
  try (Graph g = new Graph();
      Session sess = new Session(g)) {
    Ops ops = Ops.create(g);
    Operand<TInt32> variable = ops.variable(Shape.scalar(), TInt32.DTYPE);
    Operand<?> initVariable = ops.assign(variable, ops.constant(0));
    ArrayList<Op> controls = new ArrayList<>();
    controls.add(ops.assign(variable, ops.constant(3)));
    Operand<TInt32> x =
        ops.withControlDependencies(controls).math.add(variable, ops.constant(0));
    sess.runner().addTarget(initVariable).run();
    try (Tensor<TInt32> result = sess.runner().fetch(x).run().get(0).expect(TInt32.DTYPE)) {
      assertEquals(3, result.data().getInt());
    }
  }
}
 
Example #14
Source File: TfTest.java    From orbit-image-analysis with GNU General Public License v3.0 6 votes vote down vote up
public static void main(String[] args) throws Exception {
    try (Graph g = new Graph()) {
        final String value = "Hello from " + TensorFlow.version();

        // Construct the computation graph with a single operation, a constant
        // named "MyConst" with a value "value".
        try (Tensor t = Tensor.create(value.getBytes("UTF-8"))) {
            // The Java API doesn't yet include convenience functions for adding operations.
            g.opBuilder("Const", "MyConst").setAttr("dtype", t.dataType()).setAttr("value", t).build();
        }

        // Execute the "MyConst" operation in a Session.
        try (Session s = new Session(g);
            Tensor output = s.runner().fetch("MyConst").run().get(0)) {
            System.out.println(new String(output.bytesValue(), "UTF-8"));
        }
    }

}
 
Example #15
Source File: TensorFlowGraphModelTest.java    From zoltar with Apache License 2.0 6 votes vote down vote up
@Test
public void testDummyLoadOfTensorFlowGraphWithPrefix() throws Exception {
  final String prefix = "test";
  final Path graphFile = createADummyTFGraph();
  try (final TensorFlowGraphModel model =
          TensorFlowGraphModel.create(graphFile.toUri(), null, prefix);
      final Session session = model.instance();
      final Tensor<Double> double3 = Tensors.create(3.0D)) {
    List<Tensor<?>> result = null;
    try {
      result =
          session
              .runner()
              .fetch(prefix + "/" + mulResult)
              .feed(prefix + "/" + inputOpName, double3)
              .run();
      assertEquals(result.get(0).doubleValue(), 6.0D, Double.MIN_VALUE);
    } finally {
      if (result != null) {
        result.forEach(Tensor::close);
      }
    }
  }
}
 
Example #16
Source File: AbstractClassifier.java    From tensorboot with Apache License 2.0 6 votes vote down vote up
@Override
public O classify(I input) {
    Assert.notNull(model, "Classifier is not initialized");
    log.trace("Started image processing");
    try (Session session = new Session(model);
         Tensor<T> inputTensor = getInputTensor(input)) {
        log.trace("Started inference");
        List<Tensor<?>> outputs =
                session
                        .runner()
                        .feed(inputLayerName, inputTensor)
                        .fetch(outputLayerName)
                        .run();

        log.trace("Finished inference");
        try (@SuppressWarnings("unchecked") Tensor<T> output = (Tensor<T>) outputs.get(0)) {
            return convertToResult(output);
        }
    }
}
 
Example #17
Source File: HelloTensorFlow.java    From tensorflow-example-java with Do What The F*ck You Want To Public License 6 votes vote down vote up
public static void main(String[] args) throws Exception {
    try (Graph graph = new Graph()) {
        final String value = "Hello from " + TensorFlow.version();

        // Construct the computation graph with a single operation, a constant
        // named "MyConst" with a value "value".
        try (Tensor t = Tensor.create(value.getBytes("UTF-8"))) {
            // The Java API doesn't yet include convenience functions for adding operations.
            graph.opBuilder("Const", "MyConst").setAttr("dtype", t.dataType()).setAttr("value", t).build();
        }

        // Execute the "MyConst" operation in a Session.
        try (Session s = new Session(graph);
             Tensor output = s.runner().fetch("MyConst").run().get(0)) {
            System.out.println(new String(output.bytesValue(), "UTF-8"));
        }
    }
}
 
Example #18
Source File: ObjectDetector.java    From tensorflow-example-java with Do What The F*ck You Want To Public License 6 votes vote down vote up
/**
 * Pre-process input. It resize the image and normalize its pixels
 * @param imageBytes Input image
 * @return Tensor<Float> with shape [1][416][416][3]
 */
private Tensor<Float> normalizeImage(final byte[] imageBytes) {
    try (Graph graph = new Graph()) {
        GraphBuilder graphBuilder = new GraphBuilder(graph);

        final Output<Float> output =
            graphBuilder.div( // Divide each pixels with the MEAN
                graphBuilder.resizeBilinear( // Resize using bilinear interpolation
                        graphBuilder.expandDims( // Increase the output tensors dimension
                                graphBuilder.cast( // Cast the output to Float
                                        graphBuilder.decodeJpeg(
                                                graphBuilder.constant("input", imageBytes), 3),
                                        Float.class),
                                graphBuilder.constant("make_batch", 0)),
                        graphBuilder.constant("size", new int[]{SIZE, SIZE})),
                graphBuilder.constant("scale", MEAN));

        try (Session session = new Session(graph)) {
            return session.runner().fetch(output.op().name()).run().get(0).expect(Float.class);
        }
    }
}
 
Example #19
Source File: TFPredictor.java    From JFoolNLTK with Apache License 2.0 6 votes vote down vote up
public void initModel(String modelPath, int numClass) {
    if (isInit) {
        return;
    }

    this.numClass = numClass;
    this.modelPath = modelPath;
    byte[] modelByte = null;

    Path path = Paths.get(modelPath);
    try {
        modelByte = Files.readAllBytes(path);
        this.graph.importGraphDef(modelByte);
        this.session = new Session(graph);
    } catch (Exception e) {
        e.printStackTrace();
        System.out.println(e.getMessage());
        System.out.println("load model " + modelPath.toString() + " error ");
    }
    isInit = true;
}
 
Example #20
Source File: DemoImportGraph.java    From TensorFlow-Java-Examples with GNU General Public License v3.0 6 votes vote down vote up
public static void main(String[] args) throws IOException {
    try (Graph graph = new Graph()) {
        //导入图
        byte[] graphBytes = IOUtils.toByteArray(new FileInputStream("model.pb"));
        graph.importGraphDef(graphBytes);

        //根据图建立Session
        try(Session session = new Session(graph)){
            //相当于TensorFlow Python中的sess.run(z, feed_dict = {'x': 10.0})
            float z = session.runner()
                    .feed("x", Tensor.create(10.0f))
                    .fetch("z").run().get(0).floatValue();
            System.out.println(z);
        }
    }

}
 
Example #21
Source File: HelloTF.java    From neo4j-ml-procedures with Apache License 2.0 6 votes vote down vote up
public static void main(String[] args) throws Exception {
    try (Graph g = new Graph()) {
        final String value = "Hello from " + TensorFlow.version();

        // Construct the computation graph with a single operation, a constant
        // named "MyConst" with a value "value".
        try (Tensor t = Tensor.create(value.getBytes("UTF-8"))) {
            // The Java API doesn't yet include convenience functions for adding operations.
            g.opBuilder("Const", "MyConst").setAttr("dtype", t.dataType()).setAttr("value", t).build();
        }

        // Execute the "MyConst" operation in a Session.
        try (Session s = new Session(g);
             Tensor output = s.runner().fetch("MyConst").run().get(0)) {
            System.out.println(new String(output.bytesValue(), "UTF-8"));
        }
    }
}
 
Example #22
Source File: LabelImage.java    From java-ml-projects with Apache License 2.0 6 votes vote down vote up
private float[] executeInceptionGraph(byte[] graphDef, Tensor image) {
	try (Graph g = new Graph()) {
		g.importGraphDef(graphDef);
		try (Session s = new Session(g);
				Tensor result = s.runner().feed("input", image).fetch("output").run().get(0)) {
			final long[] rshape = result.shape();
			if (result.numDimensions() != 2 || rshape[0] != 1) {
				throw new RuntimeException(String.format(
						"Expected model to produce a [1 N] shaped tensor where N is the number of labels, instead it produced one with shape %s",
						Arrays.toString(rshape)));
			}
			int nlabels = (int) rshape[1];
			return result.copyTo(new float[1][nlabels])[0];
		}
	}
}
 
Example #23
Source File: Kafka_Streams_TensorFlow_Image_Recognition_Example_IntegrationTest.java    From kafka-streams-machine-learning-examples with Apache License 2.0 6 votes vote down vote up
private static float[] executeInceptionGraph(byte[] graphDef, Tensor image) {
	try (Graph g = new Graph()) {
		g.importGraphDef(graphDef);
		try (Session s = new Session(g);
				Tensor result = s.runner().feed("input", image).fetch("output").run().get(0)) {
			final long[] rshape = result.shape();
			if (result.numDimensions() != 2 || rshape[0] != 1) {
				throw new RuntimeException(String.format(
						"Expected model to produce a [1 N] shaped tensor where N is the number of labels, instead it produced one with shape %s",
						Arrays.toString(rshape)));
			}
			int nlabels = (int) rshape[1];
			return result.copyTo(new float[1][nlabels])[0];
		}
	}
}
 
Example #24
Source File: LabelImage.java    From tensorflow-java with MIT License 6 votes vote down vote up
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 =
            s.runner().feed("input", image).fetch("output").run().get(0).expect(Float.class)) {
      final long[] rshape = result.shape();
      if (result.numDimensions() != 2 || rshape[0] != 1) {
        throw new RuntimeException(
            String.format(
                "Expected model to produce a [1 N] shaped tensor where N is the number of labels, instead it produced one with shape %s",
                Arrays.toString(rshape)));
      }
      int nlabels = (int) rshape[1];
      return result.copyTo(new float[1][nlabels])[0];
    }
  }
}
 
Example #25
Source File: Recognizer.java    From object-recognition-tensorflow with Apache License 2.0 6 votes vote down vote up
private static float[] executeInceptionGraph(byte[] graphDef, Tensor image) {
    try (Graph g = new Graph()) {
        g.importGraphDef(graphDef);
        try (Session s = new Session(g);
                Tensor result = s.runner().feed("DecodeJpeg/contents", image).fetch("softmax").run().get(0)) {
            final long[] rshape = result.shape();
            if (result.numDimensions() != 2 || rshape[0] != 1) {
                throw new RuntimeException(
                        String.format(
                                "Expected model to produce a [1 N] shaped tensor where N is the number of labels, instead it produced one with shape %s",
                                Arrays.toString(rshape)));
            }
            int nlabels = (int) rshape[1];
            return result.copyTo(new float[1][nlabels])[0];
        }
    }
}
 
Example #26
Source File: DLSegment.java    From orbit-image-analysis with GNU General Public License v3.0 6 votes vote down vote up
public static SegmentationResult segmentTile(int tileX, int tileY, OrbitTiledImageIOrbitImage orbitImage, Session s, OrbitModel segModel, boolean writeImg) throws Exception {
    Raster tileRaster = orbitImage.getTile(tileX, tileY);
    //BufferedImage ori = new BufferedImage(orbitImage.getColorModel(), (WritableRaster) tileRaster.createTranslatedChild(0,0), false, null);
    //ImageIO.write(ori, "jpeg", new File(path + File.separator +"tile" + tileX + "x" + tileY + "_ori1.jpg"));

    BufferedImage maskOriginal = maskRaster(tileRaster,orbitImage, s, writeImg);

    int factor = 2;
    maskOriginal = getShiftedMask(orbitImage, s, tileRaster, maskOriginal, factor, 0, 512, false);
    maskOriginal = getShiftedMask(orbitImage, s, tileRaster, maskOriginal, factor, 0, -512, false);
    maskOriginal = getShiftedMask(orbitImage, s, tileRaster, maskOriginal, factor, 512, 0, false);
    maskOriginal = getShiftedMask(orbitImage, s, tileRaster, maskOriginal, factor, -512, 0, false);
   // maskOriginal = getShiftedMask(orbitImage, s, tileRaster, maskOriginal, factor, 0, 0, true);

    //ImageIO.write(maskOriginal, "jpeg", new File(path + File.separator +"tile" + tileX + "x" + tileY + "_seg1.jpg"));
    SegmentationResult segmentationResult = getSegmentationResult(segModel, maskOriginal);
    return segmentationResult;
}
 
Example #27
Source File: DLSegment.java    From orbit-image-analysis with GNU General Public License v3.0 6 votes vote down vote up
private static BufferedImage getShiftedMask(OrbitTiledImageIOrbitImage orbitImage,Session s, Raster tileRaster, BufferedImage maskOriginal, int factor, int dx, int dy, boolean flip) throws Exception {
    Rectangle rect = tileRaster.getBounds();
    rect.translate(dx,dy);
    if (!orbitImage.getBounds().contains(rect)) {
        return maskOriginal;
    }
    try {
        Raster shiftraster = orbitImage.getData(rect);
        if (flip) {
            shiftraster = flipRaster(shiftraster);
        }
        BufferedImage mask2 = maskRaster(shiftraster, orbitImage, s, false);
        if (flip) {
            mask2 = flipImage(mask2);
        }
        maskOriginal = combineMasks(maskOriginal, mask2, dx / factor, dy / factor);
    } catch (Exception e) {
        logger.warn("Could not shift raster, returning original image (rect="+rect+" img.bounds="+orbitImage.getBounds()+")", e);
    }
    return maskOriginal;
}
 
Example #28
Source File: ObjectDetector.java    From tensorflow-java-examples-spring with Do What The F*ck You Want To Public License 6 votes vote down vote up
/**
 * Pre-process input. It resize the image and normalize its pixels
 * @param imageBytes Input image
 * @return Tensor<Float> with shape [1][416][416][3]
 */
private Tensor<Float> normalizeImage(final byte[] imageBytes) {
    try (Graph graph = new Graph()) {
        GraphBuilder graphBuilder = new GraphBuilder(graph);

        final Output<Float> output =
            graphBuilder.div( // Divide each pixels with the MEAN
                graphBuilder.resizeBilinear( // Resize using bilinear interpolation
                        graphBuilder.expandDims( // Increase the output tensors dimension
                                graphBuilder.cast( // Cast the output to Float
                                        graphBuilder.decodeJpeg(
                                                graphBuilder.constant("input", imageBytes), 3),
                                        Float.class),
                                graphBuilder.constant("make_batch", 0)),
                        graphBuilder.constant("size", new int[]{applicationProperties.getImageSize(), applicationProperties.getImageSize()})),
                graphBuilder.constant("scale", applicationProperties.getImageMean()));

        try (Session session = new Session(graph)) {
            return session.runner().fetch(output.op().name()).run().get(0).expect(Float.class);
        }
    }
}
 
Example #29
Source File: LabelImage.java    From java-ml-projects with Apache License 2.0 5 votes vote down vote up
private Tensor constructAndExecuteGraphToNormalizeImage(byte[] imageBytes) {
	try (Graph g = new Graph()) {
		GraphBuilder b = new GraphBuilder(g);
		// Some constants specific to the pre-trained model at:
		// https://storage.googleapis.com/download.tensorflow.org/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
		// float using (value - Mean)/Scale.
		final int H = 224;
		final int W = 224;
		final float mean = 117f;
		final float scale = 1f;

		// 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 input = b.constant("input", imageBytes);
		final Output output = b
				.div(b.sub(
						b.resizeBilinear(b.expandDims(b.cast(b.decodeJpeg(input, 3), DataType.FLOAT),
								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);
		}
	}
}
 
Example #30
Source File: RNTensorflowInference.java    From react-native-tensorflow with Apache License 2.0 5 votes vote down vote up
private static TfContext createContext(ReactContext reactContext, String model) throws IOException {
    byte[] b = new ResourceManager(reactContext).loadResource(model);

    Graph graph = new Graph();
    graph.importGraphDef(b);
    Session session = new Session(graph);
    Session.Runner runner = session.runner();

    return new TfContext(session, runner, graph);
}