Run python script (with numpy dependency) from java

久未见 提交于 2019-12-19 11:48:26

问题


In a java application I need to use a specific image processing algorithm that is currently implemented in python. What would be the best approach, knowing that this script uses the Numpy library ?

I alreayd tried to compile the script to java using the jythonc compiler but it seems that it doesn't support dependencies on native libraries like Numpy. I also tried to use Jepp but I get an ImportError when importing Numpy, too.

Any suggestion ?


回答1:


If you're using Numpy you probably have to just use C Python, as it's a compiled extension. I'd recommend saving the image to disk, perhaps as a temporary file, and then calling the Python as a subprocess. If you're dealing with binary data you could even try memory mapping the data in Java and passing in in the path to the subprocess.

Alternatively, depending on your circumstances, you could set up a simple data processing server in Python which accepts requests and returns processed data.




回答2:


While Joe's answer may be simple, you will have performance issue if the image is big (2 complete write and read). I am no Java expert, but according to http://wiki.cacr.caltech.edu/danse/index.php/Communication_between_Java_and_Python#Communication_through_bindings, you can developp c <--> java bindings. You can do the same with python (with ctypes or cython if you don't want to learn the python c api).

With those, you can build yourself a nice python <--> java bridge in c, and pass around a pointer to the image data (which will be faster than writing and reading it on the hard drive).




回答3:


For using numpy within a Java process, Jep now supports numpy. You can also use jpy or JyNI.

With those libraries you could pass the images between Java and Python as byte arrays and ndarrays as you do your calculations.



来源:https://stackoverflow.com/questions/7891586/run-python-script-with-numpy-dependency-from-java

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!