Search code examples
androidopencvjunit

Setting up OpenCV v4.8.0 Android SDK for JUnit Tests [MacOS]


I had a hard time setting up OpenCV for JUnit tests on Android using MacOS. On the normal app OpenCV was working without any problems but JUnit Tests did not work.

The error that has been thrown is the following: java.lang.UnsatisfiedLinkError: no opencv_java4 in java.library.path: [/Users/patrick/Library/Java/Extensions, /Library/Java/Extensions, /Network/Library/Java/Extensions, /System/Library/Java/Extensions, /usr/lib/java, .]

I've read a lot of forums and tutorials but they all were either out-dated or not working for me. E.g. adapting the homebrew formula for Java installation, using instrumented tests or directly building the Java sources.

I would now like to share an updated way to setup OpenCV v4.8.0 for JUnit Tests working on Android.


Solution

  • Here is what I did to make it work:

    1. wget -O opencv.zip https://github.com/opencv/opencv/archive/4.8.0.zip
    2. unzip opencv.zip
    3. cd opencv-4.8.0
    4. mkdir build && cd build
    cmake -DCMAKE_SYSTEM_PROCESSOR=arm64 \
    --DCMAKE_OSX_ARCHITECTURES=arm64 \ 
    -DWITH_OPENJPEG=OFF \ 
    -DWITH_IPP=OFF \ 
    -D CMAKE_BUILD_TYPE=RELEASE \ 
    -D CMAKE_INSTALL_PREFIX=/usr/local/opencv \ 
    -D JAVA_INCLUDE_PATH=$JAVA_HOME/include \ 
    -D JAVA_AWT_LIBRARY=$JAVA_HOME/jre/lib/amd64/libawt.so \ 
    -D JAVA_JVM_LIBRARY=$JAVA_HOME/jre/lib/arm/server/libjvm.so \ 
    -D BUILD_opencv_python2=OFF \ 
    -D BUILD_opencv_java=ON \ 
    -D INSTALL_PYTHON_EXAMPLES=OFF \ 
    -D INSTALL_C_EXAMPLES=OFF \ 
    -D OPENCV_ENABLE_NONFREE=OFF \ 
    -D BUILD_EXAMPLES=ON ..
    
    1. Check that "java" is listed under "To be built": enter image description here
    2. make -j<cores>

    Now you should see the library: lib/libopencv_java480.dylib

    I found that setting System.setProperty("java.library.path", "/.../opencv-4.8.0/build/lib/libopencv_java480.dylib") in the JUnit test did not work for me. Therefore I just copied the .dylib into a directory that is being looked at by the JUnit test:

    sudo cp lib/libopencv_java480.dylib /Library/Java/Extensions/libopencv_java480.dylib

    Finally, this is the JUnit test (in Kotlin) that worked:

    class UnitTest {
        @BeforeEach
        fun setUp() {
            System.loadLibrary( "opencv_java480" )
            // do some OpenCV stuff
        }
    }
    

    In the build.gradle file I've added the following (on root level):

    tasks.withType(Test) {
        useJUnitPlatform()
    }