How to Install OpenCv in Linux for Java Application
1. Introduction:
2. Download OpenCV:
unzip opencv-4.3.0.zip
3. Build OpenCV:
Create a directory to build.
mkdir build
cd build
Now, if you don't have installed cmake software please install it using the below command
sudo apt-get install cmake
Next, is to generate and configure with cmake for building executables in our system.
cmake -DBUILD_SHARED_LIBS=OFF ..
Note: When OpenCV is built as a set of static libraries (-DBUILD_SHARED_LIBS=OFF option) the Java bindings dynamic library is all-sufficient, i.e. doesn’t depend on other OpenCV libs, but includes all the OpenCV code inside. Make sure the output of the above command looks like below:
If it doesn't find the ant and java then you may get the following output:
Java:
ant: NO
JNI: NO
Java tests: YES
For this, install and setup your java and install ant
sudo apt install openjdk-8-jdk
sudo apt-get install ant
If you are still getting ant as NO then try the following command to install ant
sudo snap install ant --classic
Now start the build
make -j4
Note: Be careful not to run out of memory during the build. We need 4GB of memory per core. For example, if we compile with 4 cores (e.g. make -j4) we need a machine with at least 16GB of RAM.
The output look likes this and it will take some time.
If everything is fine, you successfully build OpenCV. Make sure the following files are packaged in the corresponding directory.
/opt/opencv-4.3.0/build/lib/libopencv_java430.so
/opt/opencv-4.3.0/build/bin/opencv-430.jar
The path of those files is created according to your OpenCV version and directory. You need to make sure the so and jar file must be created. This jar file contains the java wrapper code which we will used in the sample example.
4. Run Sample Example:
For IntelliJ Idea:
Go to : File >> Project Structure >> Libraries (under project settings)
you can see the + icon at the top left, to add a new project library click on it, and select java and add the path of previously created jar file i.e opencv-430.jar.
It's time to run a sample test example.
import org.opencv.core.CvType;
import org.opencv.core.Mat;
public class SampleTest {
public static void main(String[] args) {
System.load("/opt/opencv-4.3.0/build/lib/libopencv_java430.so");
Mat mat = Mat.eye(3, 3, CvType.CV_8UC1);
System.out.println("mat = " + mat.dump());
}
}
Make sure that you loaded your corresponding .so file.Output:
mat = [ 1, 0, 0;
0, 1, 0;
0, 0, 1]
For those who are running OpenCV in an existing project, you can set up with Gradle project as below:
For Gradle:
Copy the jar file in your project directory package for e.g "libs" and add following inside dependencies in build.gradle file.
dependencies {
//other dependencies
compile fileTree(dir: 'libs', include: '*.jar')
}