Search code examples
javajavacppdeeplearning4jnd4jdl4j

Converting org.bytedeco.javacpp.Mat to Java int/float array


My image is represented as org.bytedeco.javacpp.Mat. And I simply want to convert it to Java array of float/int. Reason behind conversion is that I want to use the Java array in other library (Nd4j) for image permute purposes. I have tried below approaches but they doesn't work.

private static int[] MatToFloatArray1(Mat mat) {
        org.bytedeco.javacpp.BytePointer matData = mat.data();
        byte[] d = new byte[matData.capacity()];
        return toIntArray(d);
    }


private static int[] MatToFloatArray2(Mat mat) {
    org.bytedeco.javacpp.BytePointer matData = mat.data();
    IntBuffer intBuffer = matData.asBuffer().asIntBuffer();
    return intBuffer.array();

}
    private static int[] toIntArray(byte[] d) {
        IntBuffer intBuf =
                ByteBuffer.wrap(d)
                        .order(ByteOrder.BIG_ENDIAN)
                        .asIntBuffer();
        int[] array = new int[intBuf.remaining()];
        return array;

}

Solution

  • The most efficient way is probably something like the following:

    Mat intMat = new Mat();
    mat.convertTo(intMat, CV_32S);
    IntBuffer intBuffer = intMat.createBuffer();
    int[] intArray = new int[intBuffer.capacity()];
    intBuffer.get(intArray);
    

    This is in the case of int, but we can also do the same thing for float:

    Mat floatMat = new Mat();
    mat.convertTo(floatMat, CV_32F);
    FloatBuffer floatBuffer = floatMat.createBuffer();
    float[] floatArray = new float[floatBuffer.capacity()];
    floatBuffer.get(floatArray);