Skip to content Skip to sidebar Skip to footer

Converting Arrays And Tensors In Chaquopy

How do I do this? I saw your post saying that you can just pass java Objects to Python methods but this is not working for numpy arrays and TensorFlow tensors. The following, and

Solution 1:

I assume the error you received was "ValueError: only 2 non-keyword arguments accepted".

You probably also got a warning from Android Studio in the call to numpy.array, saying "Confusing argument 'anchors', unclear if a varargs or non-varargs call is desired". This is the source of the problem. You intended to pass one double[][] argument, but unfortunately Java has interpreted it as five double[] arguments.

Android Studio should offer you an automatic fix of casting the parameter to Object, i.e.:

numpy.callAttr("array", (Object)anchors);

This tells the Java compiler that you intend to pass only one argument, and numpy.array will then work correctly.


Solution 2:

I have managed to find two ways that actually work in converting this toy array into proper Python arrays.

  • In Java:
import com.chaquo.python.*;

Python py = Python.getInstance();
PyObject np = py.getModule("numpy");
PyObject anchors_final = np.callAttr("array", anchors[0]);
anchors_final = np.callAttr("expand_dims", anchors_final, 0);
for (int i=1; i < anchors.length; i++){
  PyObject temp_arr = np.callAttr("expand_dims", anchors[i], 0);
  anchors_final = np.callAttr("append", anchors_final, temp_arr, 0);
}
// Then you can pass it to your Python file to do whatever


  • In Python (the simpler way)

After passing the array to your Python function, using for example:

import com.chaquo.python.*;

Python py = Python.getInstance();
PyObject pp = py.getModule("file_name");
PyObject output = pp.callAttr("fnc_head", anchors);

In your Python file, you can simply do:

def fnc_head():
    anchors = [list(x) for x in anchors]
    ...
    return result

These were tested with 2-d arrays. Other array types would likely require modifications.


Post a Comment for "Converting Arrays And Tensors In Chaquopy"