Building Java Wrapper For OpenCV

In my last post, I explained how OpenCV is built on Windows environment using MinGW. Here I will explain how OpenCV for Java can be built using MinGW.

Java has a wide range of proven coding practices such as high level abstraction, easy memory management and more. This is an endeavour of the OpenCV community to bring best of both worlds where C++ is used at the development level and Java (not to mention python) at the implementation level. And this has opened up more audience levels after OpenCV adapted Java and python languages.

It is of course easy to download OpenCV pre-built libraries for java. But pre-built files are only available for Windows and for other OSes, it is required to build from source. Further, the java bindings are only available for main modules in the opencv main repo and not for opencv extra modules, at least as of now.

What if you need opencv extra modules in java wrappers. Then you are left with only option. Build it from the source! This blog covers most of the part related to Windows environment, still you would be able to grasp the main steps involving in the process on any OSes.

Pre-requisites

Java path

Figure 1: Set System Paths for Ant & Java

  1. Download python 2.6+
  2. Download jdk 6+ as java binding for OpenCV needs it.
  3. Set java path as shown in the Figure 1.
    1. Set ‘JAVA_HOME’ variable under ‘User variables’
    2. Set ‘Path’ variable under ‘System variables’
  4. Download Ant (say at ‘ant-dir’)
  5. Set ant path variables (refer Figure 1) referring this
  6. Download CMake
  7. Download MinGW and set path

CMake

Follow cmake variable settings under CMake Configuration in the previous blog. Additionally uncheck ‘BUILD_SHARED_LIBS’ under ‘BUILD’ category as shown in the Figure 2.

No shared

Figure 2: Uncheck shared library option

Once you ‘Configure’ (please select MinGW Makefiles and click’Finish’), you will see a new option, ‘BUILD_FAT_JAVA_LIB’ which specifies that a java wrapper will be created for all OpenCV libraries enabled.

For me, whatever the reason (if you know, please point me out) the set paths for ant, java and python had no effect on cmake and they were not picked at the configuration. You can check it after ‘Configure’ in the generating window whether Java wrappers: is set to YES or NO. If it’s YES, you are through and simply ignore the following steps and just click ‘Configure’. But for me it was NO. Therefore I had to manually set paths using cmake-gui.

Ant path

Figure 3: Set Ant path in cmake

Give the path ‘<ant-dir>\bin\ant.bat’ for ‘ANT_EXECUTABLE’ under ‘Ungroped Entries’ as shown in the Figure 3. (Don’t worry on the other un-set paths under ‘Ungrouped Entries’ as those are not required under this topic)

Set java paths in cmake-gui as shown in the Figure 4.

Then ‘Configure’, you will see ‘BUILD_opencv_java’ is checked under BUILD category.

 

Java path cmake

Figure 4: Set Java path in cmake

MinGW

Follow the steps given under MinGW Compilation in the previous blog.

Note: Strangely mingw32-make has invoked ‘jre’ path instead of ‘jdk’ though I have set paths in both system and cmake-gui correctly. It searches for tools.jar in ‘<jre-dir>/lib’ folder while it is of course resides in ‘<jdk-dir>/lib’. I copied tools.jar and pasted inside ‘<jre-dir>/lib’ to proceed with the building process. (I know this is not the recommended way of doing this. But for the moment it worked for me. If you know a better way of doing this, please point me)

OpenCV Extra Modules

Follow the steps given under OpenCV Extra Modules in the previous blog.

Though the above steps will include extra modules in ‘opencv_java’ library, it will not bind java libraries with .jar file. For this you will have to specify in each of your preferred extra modules that you need java binding at .jar file.

E.g.: If you need ‘text’ module in ‘opencv_contrib’,

  1. Open file <opencv_contrib_path>\modules\text\CMakeLists.txt> and search for the line containing ‘ocv_define_module’ option.
  2. Add ‘java’ at the end of the module list as

ocv_define_module(text opencv_ml … WRAP python java)

If the ‘ocv_define_module’ does not contain ‘WRAP’, then include that before ‘java’. Otherwise you will probably have an error saying ‘cannot find -ljava’.

E.g.: ‘text’ module contains ‘WRAP’ while ‘adas’ does not. Therefore add ‘WRAP java’ as follows in <opencv_contrib_path>\modules\adas\CMakeLists.txt>

ocv_define_module(adas opencv_xobjdetect WRAP java)

 

Using Java Wrappers in Eclipse

The above steps will generate two important files inside ‘<opencv-build>\install\java’. One is ‘libopencv_java300.dll’ static library containing all opencv built libraries. The second is ‘opencv-xxx.jar’ executable file which can now be used as the java binding interface by Eclipse. Please refer this site to configure Eclipse environment in order to use ‘opencv-xxx.jar’ for java wrapping.

 

This is the end of this blog and hope you enjoyed it. It would be great if you can point me mistakes, if you have tackled any. Thank you.

 

49 thoughts on “Building Java Wrapper For OpenCV

  1. Pingback: OpenCV For Mobile Devices Using Android Studio | You, Myself and Community

  2. Pingback: Building OpenCV For Android From Source | You, Myself and Community

  3. I did all steps above but I didn’t see Java Wrapper. All I could see in “Java:” is ant: C:/ant/bin/ant.bat (ver 1.9.7) and Java tests: YES. Did I mess something up or is there any additionals steps I have to take?

    • @Linh, for whatever the reason, the Java paths should be configured manually using cmake-gui. Did you configure it manually? Though you see only two options there, you can add paths manually using cmake-gui. Use ‘+ Add Entry’ in Cmake-gui to add new variables and set Java path as shown in the “Figure 4: Set Java path in cmake”. And try again with the compilation. Ping me back if this does not work.

  4. Pingback: Build OpenCV4Android with Non-free Modules | Code Stuff

  5. hi Zamrath Nizam, i’m using java netbean work station to develop my application, i try use opencv face module(org.Face.face ) but still i can’t append the opencv extra model, I follow the step listed above but java wrapper: no: Java tests: no. even I configured all
    Java paths =
    C:/Program Files/Java/jdk1.8.0_121/include
    C:/Program Files/Java/jdk1.8.0_121/include/jawt.h
    C:/Program Files/Java/jdk1.8.0_121/include
    C:/Program Files/Java/jdk1.8.0_121/include/win32
    C:/Program Files (x86)/Java/jdk1.6.0_10/include/jni.h

    ANT_EXECUTABLE =C:/ant/apache-ant-1.10.1/bin/ant.bat
    but i can’t get BUILD_opencv_java in build module
    either any additional step i missed or ant version problem?

  6. Hi Zamrath,

    I followed all the steps in this tutorial ant obtained the .jar and .lib files. I’m trying to run an openCV app that was working with the downloaded 3.2 version (the version without all contrib modules) and I’m getting the following error “Exception in thread “AWT-EventQueue-0″ java.lang.UnsatisfiedLinkError:” every time I try to instantiate an object from the openCV framework. Can you provide me any hints on what should I do?

    Thanks!

  7. Hello

    Thank you so much for your tutorials it helped me a lot
    I did everything and it worked, but the thing is when I went to eclipse first it says that it can’t find the path to the library so I changed the name of “libopencv_java320” to “opencv_java320” after that it says that I can’t use it because :
    Can’t load IA 32-bit .dll on a AMD 64-bit platform

    Can you please help me ??

    • I changed the name the first time because eclipse said
      no opencv_java320 in java.library.path
      and when I saw in the original opencv folder there was no lib in the dll file that’s why

    • Hi Saad,
      Glad to hear from you.
      What I understand from your issue description is, you are missing to point out the correct path of .dll file of opencv in eclipse. Go to Window->Preferences and select the correct tab, Java->Build path->User Libraries. Now select “Native Library Location” and click “Edit…” button. There you can correctly place the path which contains “libopencv_java320.dll” file.
      One thing you will have to understand is, libopencv_java320.dll file contains all libraries of C++ that can be used by Java wrapper through JNI calls. This will be installed at a location (say “c:/opencv-3.2.0/install/java”) in your computer, if you followed this blog. Therefore you will have to correctly specify this path (“c:/opencv-3.2.0/install/java”) in “Native Library Location”. You can double check whether this path contains your required .dll files here. Sometimes, these are installed at “c:/opencv-3.2.0/install/java/x64”, in this case specify this path. Please let me know, should you require more clarifications.

    • Hey Saâd,

      I had the same issue. The generated files are compiled for on 32 bit and you probably use JDK on 64 bits. To solve this you can install the JDK on 32 bits or you can generate a files for 64 bits.

      Best regards,
      Laureniu Iordache

  8. Hi Zamrath,

    I am running into an issue using Eclipse. After following the guide, I am getting error: java.lang.UnsatisfiedLinkError: no opencv_java320 in java.library.path

    My User Library contains the opencv_java320.jar and my Native Library Location points to the folder containing the libopencv_java320.dll. I am unsure if I did something wrong. The only jar and dll files my build created were the opencv_java320.jar and the libopencv_java320.dll.

    I noticed that a previous response mentioned changing the name of libopencv_java320.dll to opencv_java320.dll, but this change did not resolve the issue.

    Do you have any idea what could be going wrong?

    • Hi Tyler,
      Sorry for the late reply. I hope you should have resolved the issues by now.
      You should have noticed a similar question was asked previously and it has the answer.
      Further, please refer this.

  9. hi,
    please can you tell me what’s the error when I press mingw32-make , I spent 2 days searching for a solution but I didn’t find .
    process_begin: CreateProcess((null), call C:\apache-ant-1.6.5-bin\apache-ant-1.6.5\bin\ant.bat -q -noinput -k debug -Djava.target=1.6 -Djava.source=1.6, …) failed.
    make (e=2): Le fichier spécifié est introuvable.
    mingw32-make[2]: *** [bin/classes.jar] Error 2
    mingw32-make[1]: *** [modules/java/CMakeFiles/opencv_java.dir/all] Error 2
    mingw32-make: *** [all] Error 2
    thanks for avance .

    • Hi amal,
      It is always recommended the versions of tool you are currently having. BTW, try the installation with the option “WITH_IPP=OFF”. However this is not a longterm solution. You can find more on this here.

  10. Hi Zamrath,
    I am using cmake 3.10 gui and it doesnt have the options for setting java path what i mean is like i have the folders for python2 python 3 but not the java folder I manually added the all of the java variable as mentioned in your blog above but still JAVA WRAPPERS & JAVA test both are set to no. Can u guide me where i have gone wrong. And also as u mentioned there will be a option in BUILD as build_opencv_java that is also not present

    • You don’t need toolchain file, If you are currently interested only in Java wrapper for opencv. The tutorial you have mentioned shows steps to cross compile opencv for android. Please set ANT_EXECUTABLE correctly (as pointed out in your previous comment) and let me know whether it works.

      • I don’t have the ANT_EXECUTABLE field in the ungrouped entries. I tried using different versions of cmake but that also did not make a difference one more thing i would like to ask is do i need the python in my system for this process.

  11. First of all thanx a lot !!!
    It worked for me when i changed my target folder. But when i am running mingw32-make i get error and it get stucks at 56%
    CMakeFiles\Makefile2:5015: recipe for target ‘modules/objdetect/CMakeFiles/openc
    v_objdetect.dir/all’ failed
    mingw32-make[1]: *** [modules/objdetect/CMakeFiles/opencv_objdetect.dir/all] Err
    or 2
    mingw32-make[1]: *** Waiting for unfinished jobs….
    [ 56%] Built target opencv_features2d
    Makefile:161: recipe for target ‘all’ failed
    mingw32-make: *** [all] Error 2

    I though the issue was related to features2d so i unchecked this in cmake gui under the build section. After that i got across this stage but again got stuck at 65%. The error log is as follows

    CMakeFiles\Makefile2:4993: recipe for target ‘modules/objdetect/CMakeFiles/openc
    v_objdetect.dir/all’ failed
    mingw32-make[1]: *** [modules/objdetect/CMakeFiles/opencv_objdetect.dir/all] Err
    or 2
    mingw32-make[1]: *** Waiting for unfinished jobs….
    [ 65%] Linking CXX static library ..\..\lib\libopencv_ts310.a
    [ 65%] Built target opencv_ts
    Makefile:161: recipe for target ‘all’ failed
    mingw32-make: *** [all] Error 2
    I can’t figure out what the error is. One more thing i would like to mention i am using -j8 along with command. I hope that is not causing the trouble

      • Thanx for the wonderful post Zamrath. My target was to generate the libopencv_java.so file. What worked for me was to use the tool chain file. Without using that i was not able built and i get the errors which i mentioned above. I got the job done but will be interested to know why it is not building for me without using the tool chain file.

  12. Hi Sir Zamrath, I want to build opencv 3.4 with the extra module for java application and i follow your blog and thank you, i wanna ask if what do i need to change in my configurations because this following error occurs everytime:

    in cmake this is the red lines:
    CMake Warning at C:/opencv3.4/opencv3.4-master/sources/opencv-master/cmake/OpenCVDownload.cmake:190 (message):
    data: Download failed: 6;”Couldn’t resolve host name”

    CMake Warning at C:/opencv3.4/opencv3.4-master/sources/opencv_contrib-master/modules/face/CMakeLists.txt:26 (message):
    Face: Can’t get model file for face alignment

    ////////////////////////////
    in mingw32 this are the errors:
    1st error:
    mingw32-make[2]:*** No rule to make target ‘bin/opencv-340.jar’, needed by java_test/bin/opencv-340.jar. Stop.
    mingw32-make[1] *** [CMakeFiles\Makefile2:14109: modules/java/test/pure_test?CMakeFiles/opencv_test_java.dir/all]Error 2
    mingw32-make : *** [Makefile : 162 all] Error 2

    2nd error:
    mingw32-make[2]: *** [modules\xfeatures2d\CMakeFiles\opencv_xfeatures2d.dir\build.make:93:modules/xfeatures2d/CMakeFiles/opencv_xfeatures2d.dir/src/bosstdesc.cpp.obj]Error1
    mingw32-make[1] *** [CMakeFiles\Makefile2:7308:modules/xfeatures2d/CmakeFiles/mingw32-mak: ***[Makefile:16:all] Error 2

    3rd Error:
    Error occured during initialization of VM
    Too small initial heap
    mingw32-make[2]: *** [modules\java\jar\CMakeFiles\opencv_java_jar.dir\build.make:61 CmakeFiles/dephelper/opencv_java_jar] Error 1
    mingw32-make[1]: *** [CMakeFiles\Makefile2:8181: modules/java/jar/CmakeFiles/opencv_java_jar.dir/all] Error 2
    mingw32-make: *** [MakeFile: 162: all] Error 2

    THANK YOU IN ADVANCE

      • Hi Sir..Thanks for the response actually i surpassed 1st and 2nd error in the mingw32 then the 3rd error occurs and i dont know why it happened..i just need the contribution module because im trying to create a face recognition system using the latest version of opencv in java..do i need to change some of my configurations? Or in the environmental variable?..Thanks

      • Unfortunately I have no exact answer for this.
        Two guesses. First is you don’t have enough virtual memory in your working machine. Try this. Second is your java version is not compatible with the opencv version. Please try with one compatible.

      • Hello Sir Thanks again..i successfully build the latest version of the Opencv with the extra module but when i try to import it to my Netbeans project the java.lang.UnsatisfiedLinkError: no opencv_java340 in java.library.path occurs..i already tried all the solutions provided in this blog but it still occurs..What should i do? Thank you

  13. Hi Zamrath,
    I am trying to build with the option “arm-v7a with neon” but I am getting configuration errors. It works fine when i build with option “arm-v7a”. Can u point what additional things i need to install in my system to make this work ?

      • Thanx for the fast response Zamrath but this doesn’t anwer my question. I am facing trouble (configuration errors) when i select “arm-v7a with neon” in android abi. It works fine for me when i choose the option “arm-v7a”. I think i need to install something in my system to get this running. Do you have any idea what other things i need to get this working.

      • Hi Ayush, it is not so easy to guess the configuration errors from your comments. I appreciate if you would point out those. BTW, have you enabled the following option in cmake to configure it properly?
        -DENABLE_NEON=ON

      • Hello Sir again..im done everything you have said..it still occurs..im having trouble if what is the correct path for the vm option in my netbeans because i found out that there are 3 .dll files and 3 jar file in my build folder..First is in the bin folder then in the install folder and the lib folder..what should i use.?..i play a lot in changing my path to the .dll file and suddenly when i try to run my project an error saying:
        1st error i encountered
        Error cant find or load main class: java returned 139

        When i change again the path theres an error about the unsatisfied error native link about Mat eventhough i have declared the System.loadlibrary (Core.NativeLibrary) in my main function..Please help me Sir im having alot of troubles..im currently out of time for my project..may i ask for your email or can you contact me for some assistance with my email at tvmagallano@gmail.com..Thank you

      • I am assuming this is not related to a path issue. If you want to clarify whther it points to the correct path you can try adding the following line just before your loadLibrary line.
        System.out.printf(“java.library.path: %s%n”, System.getProperty(“java.library.path”));
        System.loadLibrary(“opencv_java340”)
        Or try the following,
        System.loadLibrary(Core.NATIVE_LIBRARY_NAME);
        You can even set your own library path as follows.
        try {
        System.setProperty(“java.library.path”,”YOUR/PATH”);
        Field fieldSysPath = ClassLoader.class.getDeclaredField(“sys_paths”);
        fieldSysPath.setAccessible(true);
        fieldSysPath.set(null, null);
        } catch (Exception ex) {
        System.out.println(“Failed to set Java Library Path: ” + ex.getMessage);
        }

        If this is alos not working, then there is a chance that your installation was incomplete. In that case, please try a fresh-installation or try with a more stable 3.3.1 release instead of 3.4.

  14. Hi Zamarath,
    I was out so was unable to reply. I enable the neon present in the “ENABLE” group still getting errors. The configuration errors are :
    Ungrouped entries
    CPU_BASELINE_REQUIRE ;NEON
    CMAKE_ASM_COMPILER_AR not found
    CMAKE_ASM_COMPILER_RANLIB not found

  15. Hi Zamrath,

    I am trying to install OpenCV with extra modules in Android Studio with yor articles. Firstly i follow /building-opencv-for-android-from-source but my sdk/java folder was not created. I follow your suggestion in comments on that article and try this article correctly. But still my java folder is not created.

    Here is the java part of CMake Log;

    Java: export all functions
    ant: C:/ant/bin/ant.bat (ver 1.10.2)
    Java wrappers: YES
    Java tests: NO

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google photo

You are commenting using your Google account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s