Java Code Examples for org.tensorflow.Tensor#create()

The following examples show how to use org.tensorflow.Tensor#create() . 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 Tensor<Float> convertBufferedImageToTensor(BufferedImage image) {
    int width = image.getWidth();
    int height = image.getHeight();
    int[] data = new int[width * height];
    image.getRGB(0, 0, width, height, data, 0, width);
    float[][][][] rgbArray = new float[1][height][width][3];
    for (int i = 0; i < height; i++) {
        for (int j = 0; j < width; j++) {
            Color color = new Color(data[i * width + j]);
            rgbArray[0][i][j][0] = color.getRed();
            rgbArray[0][i][j][1] = color.getGreen();
            rgbArray[0][i][j][2] = color.getBlue();
        }
    }
    return Tensor.create(rgbArray, Float.class);
}
 
Example 2
Source File: PoseEstimationTensorflowInputConverter.java    From tensorflow with Apache License 2.0 6 votes vote down vote up
private Tensor<Float> makeImageTensor(byte[] imageBytes) throws IOException {
	ByteArrayInputStream is = new ByteArrayInputStream(imageBytes);
	BufferedImage img = ImageIO.read(is);

	if (img.getType() != BufferedImage.TYPE_3BYTE_BGR) {
		throw new IllegalArgumentException(
				String.format("Expected 3-byte BGR encoding in BufferedImage, found %d", img.getType()));
	}

	// ImageIO.read produces BGR-encoded images, while the model expects RGB.
	int[] data = toIntArray(img);

	//Expand dimensions since the model expects images to have shape: [1, None, None, 3]
	long[] shape = new long[] { BATCH_SIZE, img.getHeight(), img.getWidth(), CHANNELS };

	return Tensor.create(shape, FloatBuffer.wrap(toRgbFloat(data)));
}
 
Example 3
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 4
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 5
Source File: GraphBuilder.java    From cineast with MIT License 5 votes vote down vote up
public <T> Output<T> constant(String name, Object value, Class<T> type) {
  try (Tensor<T> t = Tensor.<T>create(value, type)) {
    return g.opBuilder("Const", name)
        .setAttr("dtype", DataType.fromClass(type))
        .setAttr("value", t)
        .build()
        .<T>output(0);
  }
}
 
Example 6
Source File: Inception5h.java    From cineast with MIT License 5 votes vote down vote up
private static Tensor<Float> readImage(MultiImage img) {
  float[][][] fimg = new float[img.getHeight()][img.getWidth()][3];

  double sum = 0d;

  int[] colors = img.getColors();

  for (int y = 0; y < img.getHeight(); ++y) {
    for (int x = 0; x < img.getWidth(); ++x) {
      int c = colors[x + img.getWidth() * y];
      fimg[y][x][0] = (float) RGBContainer.getRed(c);
      fimg[y][x][1] = (float) RGBContainer.getGreen(c);
      fimg[y][x][2] = (float) RGBContainer.getBlue(c);

      sum += fimg[y][x][0] + fimg[y][x][1] + fimg[y][x][2];

    }
  }

  sum /= (img.getWidth() * img.getHeight());

  for (int y = 0; y < img.getHeight(); ++y) {
    for (int x = 0; x < img.getWidth(); ++x) {
      fimg[y][x][0] -= sum;
      fimg[y][x][1] -= sum;
      fimg[y][x][2] -= sum;

    }
  }

  return Tensor.create(fimg, Float.class);

}
 
Example 7
Source File: LabelImage.java    From tensorflow-java with MIT License 5 votes vote down vote up
<T> Output<T> constant(String name, Object value, Class<T> type) {
  try (Tensor<T> t = Tensor.<T>create(value, type)) {
    return g.opBuilder("Const", name)
        .setAttr("dtype", DataType.fromClass(type))
        .setAttr("value", t)
        .build()
        .<T>output(0);
  }
}
 
Example 8
Source File: TensorFlowService.java    From tensorflow-spring-cloud-stream-app-starters with Apache License 2.0 5 votes vote down vote up
private Tensor toFeedTensor(Object value) {
	if (value instanceof Tensor) {
		return (Tensor) value;
	}
	else if (value instanceof Tuple) {
		return TensorTupleConverter.toTensor((Tuple) value);
	}

	return Tensor.create(value);
}
 
Example 9
Source File: LabelImageTensorflowInputConverter.java    From tensorflow-spring-cloud-stream-app-starters with Apache License 2.0 5 votes vote down vote up
Output constant(String name, Object value) {
	try (Tensor t = Tensor.create(value)) {
		return g.opBuilder("Const", name)
				.setAttr("dtype", t.dataType())
				.setAttr("value", t)
				.build()
				.output(0);
	}
}
 
Example 10
Source File: Recognizer.java    From object-recognition-tensorflow with Apache License 2.0 5 votes vote down vote up
Output constant(String name, Object value) {
    try (Tensor t = Tensor.create(value)) {
        return g.opBuilder("Const", name)
                .setAttr("dtype", t.dataType())
                .setAttr("value", t)
                .build()
                .output(0);
    }
}
 
Example 11
Source File: DLHelpers.java    From orbit-image-analysis with GNU General Public License v3.0 5 votes vote down vote up
public static Tensor<Float> convertBufferedImageToTensor(BufferedImage image, int targetWidth, int targetHeight) {
        //if (image.getWidth()!=DESIRED_SIZE || image.getHeight()!=DESIRED_SIZE)
        {
            // also make it an RGB image
            image = resize(image, targetWidth, targetHeight);
            // image = resize(image,image.getWidth(), image.getHeight());
        }
        int width = image.getWidth();
        int height = image.getHeight();
        Raster r = image.getRaster();
        int[] rgb = new int[3];
        //int[] data = new int[width * height];
        //image.getRGB(0, 0, width, height, data, 0, width);
        float[][][][] rgbArray = new float[1][height][width][3];
        for (int i = 0; i < height; i++) {
            for (int j = 0; j < width; j++) {
                //Color color = new Color(data[i * width + j]);
//                rgbArray[0][i][j][0] = color.getRed() - MEAN_PIXEL[0];
//                rgbArray[0][i][j][1] = color.getGreen() - MEAN_PIXEL[1];
//                rgbArray[0][i][j][2] = color.getBlue() - MEAN_PIXEL[2];
                rgb = r.getPixel(j,i,rgb);
                rgbArray[0][i][j][0] = rgb[0] - MEAN_PIXEL[0];
                rgbArray[0][i][j][1] = rgb[1] - MEAN_PIXEL[1];
                rgbArray[0][i][j][2] = rgb[2] - MEAN_PIXEL[2];
            }
        }
        return Tensor.create(rgbArray, Float.class);
    }
 
Example 12
Source File: GraphBuilder.java    From tensorflow-example-java with Do What The F*ck You Want To Public License 5 votes vote down vote up
public <T> Output<T> constant(String name, Object value, Class<T> type) {
    try (Tensor<T> t = Tensor.<T>create(value, type)) {
        return graph.opBuilder("Const", name)
                .setAttr("dtype", DataType.fromClass(type))
                .setAttr("value", t)
                .build()
                .<T>output(0);
    }
}
 
Example 13
Source File: GraphBuilder.java    From tensorflow-java-examples-spring with Do What The F*ck You Want To Public License 5 votes vote down vote up
public <T> Output<T> constant(String name, Object value, Class<T> type) {
    try (Tensor<T> t = Tensor.<T>create(value, type)) {
        return graph.opBuilder("Const", name)
                .setAttr("dtype", DataType.fromClass(type))
                .setAttr("value", t)
                .build()
                .<T>output(0);
    }
}
 
Example 14
Source File: TensorFlowConverters.java    From konduit-serving with Apache License 2.0 5 votes vote down vote up
public Tensor<?> convert(SerializedNDArray from){
    long[] shape = from.getShape();
    Class<?> tfType = TensorFlowUtil.toTFType(from.getType());
    from.getBuffer().rewind();
    Tensor<?> t = Tensor.create(tfType, shape, from.getBuffer());
    return t;
}
 
Example 15
Source File: TensorFlowService.java    From tensorflow with Apache License 2.0 5 votes vote down vote up
/**
 * Convert an object into {@link Tensor} instance. Supports java primitive types, JSON string encoded
 * tensors or {@link Tensor} instances.
 * @param value Can be a java primitive type, JSON string encoded tensors or {@link Tensor} instances.
 * @return Tensor instance representing the input object value.
 */
private Tensor toFeedTensor(Object value) {
	if (value instanceof Tensor) {
		return (Tensor) value;
	}
	else if (value instanceof String) {
		return TensorJsonConverter.toTensor((String) value);
	}
	else if (value instanceof byte[]) {
		return TensorJsonConverter.toTensor(new String((byte[]) value));
	}

	return Tensor.create(value);
}
 
Example 16
Source File: LongTensorTypeSupport.java    From datacollector with Apache License 2.0 4 votes vote down vote up
@Override
public Tensor<Long> createTensor(long[] shape, LongBuffer buffer) {
  return Tensor.create(shape, buffer);
}
 
Example 17
Source File: TFUtil.java    From JFoolNLTK with Apache License 2.0 4 votes vote down vote up
public static  Tensor createTensor(List<List<Integer>> idList, int maxLength){
    int[][] lList = intListToMat(idList, maxLength);
    Tensor tensor = Tensor.create(lList);
    return tensor;
}
 
Example 18
Source File: Kafka_Streams_TensorFlow_Image_Recognition_Example_IntegrationTest.java    From kafka-streams-machine-learning-examples with Apache License 2.0 4 votes vote down vote up
Output constant(String name, Object value) {
	try (Tensor t = Tensor.create(value)) {
		return g.opBuilder("Const", name).setAttr("dtype", t.dataType()).setAttr("value", t).build().output(0);
	}
}
 
Example 19
Source File: DLHelpers.java    From orbit-image-analysis with GNU General Public License v3.0 4 votes vote down vote up
public static RawDetections executeInceptionGraph(final Session s, final Tensor<Float> input, final int inputWidth, final int inputHeight, final int maxDetections, final int maskWidth, final int maskHeight) {
    // image metas
    //  meta = np.array(
    //        [image_id] +                  # size=1
    //        list(original_image_shape) +  # size=3
    //        list(image_shape) +           # size=3
    //        list(window) +                # size=4 (y1, x1, y2, x2) in image cooredinates
    //        [scale[0]] +                     # size=1 NO LONGER, I dont have time to correct this properly so take only the first element
    //        list(active_class_ids)        # size=num_classes
    //    )
    final FloatBuffer metas = FloatBuffer.wrap(new float[]{
            0,
            inputWidth,inputHeight,3,
            inputWidth,inputHeight,3,
            0,0,inputWidth,inputHeight,
            1,
            0,0
    });
    final Tensor<Float> meta_data = Tensor.create(new long[]{1,14},metas);

    List<Tensor<?>> res = s
            .runner()
            .feed("input_image", input)
            .feed("input_image_meta", meta_data)
            .feed("input_anchors", getAnchors(inputWidth))  // dtype float and shape [?,?,4]
            .fetch("mrcnn_detection/Reshape_1")   // mrcnn_mask/Reshape_1   mrcnn_detection/Reshape_1    mrcnn_bbox/Reshape     mrcnn_class/Reshape_1
            .fetch("mrcnn_mask/Reshape_1")
            .run();

    float[][][] res_detection = new float[1][maxDetections][6];   // mrcnn_detection/Reshape_1   -> y1,x1,y2,x2,class_id,probability (ordered desc)
    float[][][][][] res_mask = new float[1][maxDetections][maskHeight][maskWidth][2];   // mrcnn_mask/Reshape_1
    Tensor<Float> mrcnn_detection = res.get(0).expect(Float.class);
    Tensor<Float> mrcnn_mask = res.get(1).expect(Float.class);
    mrcnn_detection.copyTo(res_detection);
    mrcnn_mask.copyTo(res_mask);

    RawDetections rawDetections = new RawDetections();
    rawDetections.objectBB = res_detection;
    rawDetections.masks = res_mask;
    return rawDetections;
}
 
Example 20
Source File: MtcnnUtil.java    From mtcnn-java with Apache License 2.0 2 votes vote down vote up
/**
 * Converts ND4J array into a {@link Tensor}
 * @param indArray {@link INDArray} to covert
 * @return Returns Float {@link Tensor}
 */
public static Tensor<Float> toTensor(INDArray indArray) {
	return Tensor.create(indArray.shape(), FloatBuffer.wrap(indArray.data().asFloat()));
}