androidpython-3.xpyobjectchaquopy

Converting PyObject in Python to 2D array in Android using Chaquopy


I'm using Chaquopy in my android project. I have a function in my python class which it returns a 2D array as a PyObject type. Now, I want to convert it to 2D array in my java class. How can I achieve this?

EDIT : Here is my Python code :

import numpy as np
from scipy.io import wavfile

def get_python_audio(file_path):
 fs, data_test = wavfile.read(file_path)
 print('data_test:', data_test.shape)
 data = data_test[:, 0]
 data = data[:, np.newaxis]
 print('data:', data.shape)


 return data

Solution

  • Chaquopy 8.x and newer:

    NumPy arrays and Java arrays of the same type can now be converted directly. Assuming get_python_audio returns a 1-dimensional int16 array:

    short[] data = yourModule.callAttr("get_python_audio", filePath).toJava(short[].class);
    

    Chaquopy 7.x and older:

    The fastest way to convert numerical arrays between Java and Python is to use a byte array.

    We'll assume that wavfile.read returns a 1-dimensional int16 array, but this technique is easily adapted to other data types. Then in Python, you can do this:

    def get_python_audio(file_path):
       fs, data_test = wavfile.read(file_path)
       return data_test.tobytes()
    

    And in Java:

    byte[] bytesData = yourModule.callAttr("get_python_audio", filePath).toJava(byte[].class);
    short[] shortData = new short[bytesData.length / 2];
    ByteBuffer.wrap(bytesData).order(ByteOrder.nativeOrder()).asShortBuffer().get(shortData);
    

    If your audio has multiple channels, then you'll have to convert each channel separately.