Search code examples
pythonjavachaquopy

How to convert an ArrayList<PyObject> to an ArrayList<Scalar>?


I have integrated a java developed app in android studio with python files using chaquopy. The python file returns a List however I am struggling to convert that List to an ArrayList format (In the java file after the list is successfully returned from the Python script)?

My code has the following

ArrayList<Scalar> scalar_list;

Python py = Python.getInstance();

List<PyObject> obj = py.getModule("detect").callAttr("main", image).asList()

scalar_list = new ArrayList<>();

I am trying to write the values of obj into scalar_list so that I can access each value The format for obj is : [[int int int], [int int int], [int int int], [int int int], [int int int]]

I have tried appending it but I receive an error "incompatible types cannot be converted". Any advice? I have also tried using the toJava() function but has not worked to make it into Scalar format so that I can analyse each value of the arraylist.


Solution

  • Your question suggests that your Python object is a 2D "list of lists of integers", but it's not clear how you want to map that onto a 1D list of Scalars. I'll give an answer for a simple 1D list of integers, and hopefully you can adapt that to whatever you need.

    I'm also not sure what you mean by Scalar, but if you're referring to this OpenCV class, then you could convert a list of integers like this:

    for (PyObject elem : obj) {
        scalar_list.add(new Scalar(elem.toInt()));
    }