[Java] Enable OpenCV with java8. (For myself)

1 minute read

Primitive man running Java on command line

Introduced because I have no choice but to use OpenCV in university graduation The guide Even if I search now, most of the stories are in Python and C++, and there are few java stories, so I had a hard time.

Reference site

I basically followed the following sites. This is basically more polite. However, with the latest version (4.4.0) of the present, the test code can not be executed well, so write it there. Using OpenCV with Java | JProgramer

Isostal

It is good to execute the downloaded .exe file and extract it to the C drive. I created a folder called OpenCV and expanded it there. 7-Zip self-extracting archive 2020_08_20 15_43_43.png

Pass the path

In the reference site, it is a user variable, but I added it to the system variable. Select “Path” and click [Edit]. At the bottom C:\OpenCV\opencv\build\java\x86 Add this, if you use OpenCV in java, you only need to add this. If you use it in Python or Visual Studio, this is not enough. I have VS2017 in it so I will pass it for it. Classpath.PNG

The last part is [x86] if java is 32bit, [x64] if it is 64bit Since the machine is 64bit, I thought it was 64bit, and when I ran the test code (described later), I got an error like “I’m 32bit! A 64-bit program is unreasonable!” Does not seem to be limited.

test code

The test code of the reference site gives an error in Ver.4.4.0. Specifically, the class that outputs the image is moved to imgcodecs instead of highgui.

Test.java


import org.opencv.core.Core;
import org.opencv.core.CvType;
import org.opencv.core.Mat;
import org.opencv.core.Scalar;
import org.opencv.imgcodecs.Imgcodecs;
 
public class Test{
    public static void main(String[] args){
        System.loadLibrary(Core.NATIVE_LIBRARY_NAME);
        Mat redImg=new Mat(100,200,CvType.CV_8UC3,new Scalar(0,0,255));
        Imgcodecs.imwrite("test.jpg",redImg);
    }
}

The compile command is below ↓

javac -classpath “C:\saved folder\opencv\build\java\opencv-version.jar” Test.java

this

java -cp .;C:\saved folder\opencv\build\java\opencv-version .jar Test

When executed with, a bright red JPG image was output (saved) in the same folder.

If you set the classpath

javac Test.java java Test

You can do it with. See the reference site for details.