0

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;

}
Samuel Audet
  • 4,964
  • 1
  • 26
  • 33
  • 2
    How exactly does it not work? What are the errors/issues you encounter? – Castaglia Mar 03 '16 at 04:37
  • int[] resizedImageArray1 = MatToFloatArray1(resizedImage); int[] resizedImageArray2 = MatToFloatArray2(resizedImage); resizedImageArray1 comes out to be of zero sized. And in second call, I get UnsupportedOperationException as the array which backs this buffer is empty as well. – ashish bhutani Mar 03 '16 at 07:08

1 Answers1

3

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);
Samuel Audet
  • 4,964
  • 1
  • 26
  • 33