Book Image

OpenCV 3.0 Computer Vision with Java

By : Daniel Lelis Baggio
Book Image

OpenCV 3.0 Computer Vision with Java

By: Daniel Lelis Baggio

Overview of this book

Table of Contents (15 chapters)
OpenCV 3.0 Computer Vision with Java
About the Author
About the Reviewers

The Java OpenCV Maven configuration

Apache Maven is a more complex build automation tool, primarily used for Java projects. It describes not only how software is built, but also how it depends on other libraries. Its projects are configured through a Project Object Model, named pom.xml. Maven dependencies are usually located in Maven 2 Central Repository. In case they aren't found there, you will need to add other repositories. You can also create a local repository and add your own dependencies there. At the time of writing this book, there were no public dependencies for Java OpenCV. So we will cover not only the process of installing the Java OpenCV Maven dependencies in a local repository but also how to use this book's Maven repository for the Windows builds of OpenCV 3.0.0 version. In case OpenCV developers host public Maven repositories, minor changes will be required. You will only need to find out the official OpenCV JAR groupId, artifactId, and version and put them in your pom.xml.

In order to make your project dependent on any library, you only need to provide three fields in your pom.xml. They are groupId, artifactId, and version. The recommended way to make your project depend on libraries that are not hosted in the Central Maven Repository, is to install them using a simple command, like mvn install:install-file -Dfile=non-maven-proj.jar -DartifactId=non-maven-proj -Dversion=1 -Dpackaging=jar.

We will show you how to use the Packt repository for window builds in the next section and then we will give you the details on how to install them on your local repository, in case you need it.

Creating a Windows Java OpenCV Maven project pointing to the Packt repository

This section shows how to create a basic Maven project and how to customize it so that it adds OpenCV dependencies. Besides this, it will generate an Eclipse project so that the readers can easily generate a project in Windows. A major advantage here is that there is no need to build or download the OpenCV library manually.

Although the Maven learning curve might be a little tougher than straightaway creating your project in your favorite IDE, it pays off in the long term span. The best part of using Maven is that you won't need to install OpenCV at all since all dependencies, including native files, are automatically downloaded. We'll show you how to do it in the following simple steps:

  1. Build a project from an archetype: Create an empty folder for your project. Let's name it as D:\mvnopencv. In that folder, type the following command:

    mvn archetype:generate -DartifactId=my-opencv-app -DarchetypeArtifactId=maven-archetype-quickstart -DinteractiveMode=false

    Let's break it down into parts. The mvn archetype:generate command tells Maven to run the generate goal command from the archetype plugin. From the documentation, we see that generate goal creates a Maven project from an archetype; it asks the user to choose an archetype from the archetype catalog, and retrieves it from the remote repository. Once retrieved, it is processed to create a working Maven project. This way, we deduce that the -DarchetypeArtifactId=maven-archetype-quickstart parameter is the selected archetype. This will generate a Java project with the following structure:

    |-- pom.xml
    `-- src
        |-- main
        |   `-- java
        |       `-- com
        |           `-- company
        |               `-- app
        |                   `--
        `-- test
            `-- java
                `-- com
                    `-- company
                        `-- app


    Note that the -DartifactId=my-opencv-app properties will fill pom.xml and provide a part of the project tree.

  2. Add OpenCV dependencies: Since this is a project generated from a general Maven archetype, we should customize it so that it will look like a Java OpenCV project. In order to do that, we will need to add our dependencies. Open the generated pom.xml file in D:\mvnopencv\my-opencv-app. We should first add the Java OpenCV dependencies. Since they don't exist in the Maven central repository at the time of writing this book, you will also need to point to an online repository. We have provided native files for Windows x86 and Windows 64-bits. In order to add the Packt Maven repository, simply add the following lines to your pom.xml file:

    <project xmlns="" xmlns:xsi=""

    Now, also add the OpenCV dependencies. In order to compile your code, you will only need to add the OpenCV JAR dependency. In case you also want to execute it, you will need the Windows natives as well. These have been packed inside opencvjar-runtime-3.0.0-natives-windows-x86.jar for 32-bit architectures. For 64-bit architectures, these are packed inside opencvjar-runtime-3.0.0-natives-windows-x86_64.jar. Near the junit dependencies, add the following:


    Notice the classifier property set to opencvjar-runtime. It is set to natives-windows-x86_64. This is the value you should use for a 64-bit platform. In case you want it for a 32-bit platform, just use natives-windows-x86.

  3. Configure build plugins: The opencvjar-runtime dependencies only include files such as .dll, .so, and so on. These files will be extracted to your target while executing the mvn package command. But, this will only happen if you add maven-nativedependencies-plugin. Besides, it is also important that you copy all the JAR libraries to your /lib folder when creating your distributable JAR. This will be dealt with by the maven-dependency-plugin. The last detail is to point your main class when creating a JAR, which is performed by maven-jar-plugin. All the build plugin configurations should be added as follows:


    You can see the final pom.xml file in the chapter1/maven-sample directory in this chapter's sample code.

  4. Create a package: Now, you should check if everything's correct by making a package. Simply type the following command:

    mvn package

    The preceding should download all the plugins and dependencies, compile your file from the archetype, generate your my-opencv-app-1.0-SNAPSHOT.jar in the target folder, as well as copy all the dependent libraries to your target/lib folder; check for the junit, opencvjar, and opencvjar-runtime JARs. Also, the native libraries are extracted to the target /natives folder, so opencv_java300.dll can be found there. Your compiled classes can also be found in the target /classes folder. The other generated folders are related to your tests.

  5. Customize your code: Now, we will change the source file to use the simple OpenCV functions. Navigate to D:\mvnopencv\my-opencv-app\src\main\java\com\mycompany\app and edit the file. Simply add the following code:

    import org.opencv.core.Core;
    import org.opencv.core.Mat;
    import org.opencv.core.CvType;
    import org.opencv.core.Scalar;
    public class App
      static{ System.loadLibrary(Core.NATIVE_LIBRARY_NAME); }
      public static void main(String[] args) {
        System.out.println("Welcome to OpenCV " + Core.VERSION);
        Mat m = new Mat(5, 10, CvType.CV_8UC1, new Scalar(0));
        System.out.println("OpenCV Mat: " + m);
        Mat mr1 = m.row(1);
        mr1.setTo(new Scalar(1));
        Mat mc5 = m.col(5);
        mc5.setTo(new Scalar(5));
        System.out.println("OpenCV Mat data:\n" + m.dump());

    It is the same code from SimpleSample that we just put in the App class. Now we just need to run it. Remember to recompile it by running the following command:

    mvn package
  6. Execute your code: Execute the generated JAR, pointing the native files in the /native folder through the -Djava.library.path property. This should be as simple as typing the following:

    D:\mvnopencv\my-opencv-app>java   -Djava.library.path=target\natives -jar target\my-opencv-app-1.0-SNAPSHOT.jar

    Well done! Now you should have the same output as when running the SimpleSample class. In case you want to execute your project through a .bat file, simply type the preceding command in a file called run.bat, for instance, and save it in the D:\mvnopencv\my-opencv-app folder.

  7. Generate an Eclipse project: Now, you will be able to take advantage of some Maven features such as creating an Eclipse project by simply typing the following command:

    mvn eclipse:eclipse

In order to get the project inside Eclipse, open your workspace and then go to File | Import.... Then, choose Existing Projects into Workspace, click on Next | Browse... in the Select root directory radio button, and browse to D:\mvnopencv\my-opencv-app. It should recognize this folder as an Eclipse project. Then simply click on Finish.

In case you want to run your project now, beware that there are two warnings here. Eclipse does not recognize Maven by default. So, you will have an error telling you that "The project cannot be built until build path errors are resolved", "Unbound classpath variable: 'M2_REPO/org/javaopencvbook/opencvjar/3.0.0/opencvjar-3.0.0.jar' in project 'my-opencv-app'".

This error simply means that your M2_REPO variable isn't defined. Go to Window | Preferences, and type classpath variables in the search box. Selecting it in the tree will bring you the tab to define this variable. Click on New... and the New Variable Entry dialog box will appear. In the Name input, call it M2_REPO and in the Path input, choose Folder... and browse to your Maven repository. This should be located in a folder similar to C:/Users/baggio/.m2/repository. Click on Ok, and then Ok again in the Preferences dialog box. It will ask for a full rebuild. Click on Yes, and then the error should be gone.

If you try to run your class by right-clicking Run As | Java Application, it should give you the following exception: Exception in thread "main" java.lang.UnsatisfiedLinkError: no opencv_java300 in java.library.path.

It only means that Eclipse hasn't found your native files. Fixing it is as easy as expanding your project and locating the Referenced Libraries | opencvjar-3.0.0.jar. Right-click it and choose Properties. Select Native Library at the left and in the Location path, click Workspace..., my-opencv-app | target | natives. Remember that this folder will only exist if you have previously run the mvn package command. Run the App class again and it should work.

Creating a Java OpenCV Maven project pointing to a local repository

The same instructions given in the previous section apply here. The only differences are that you will not need to add any additional repository to your pom.xml since they will be located in your local repository, and that you must install and create all the JARs in the Packt' repository in your machine. We assume that you have already obtained the opencv-300.jar and the native files required for your architecture, that is, if you are in Linux, you have already compiled.

In order to put your artifacts in a local repository, you must use the goal install-file from the install plugin. Firstly, you should install the opencv jar file. It should be in your build directory, in a folder that will look like D:\opencv\build\bin. In that folder, type in the following command:

mvn install:install-file -Dfile=opencvjar-3.0.0.jar -DgroupId=opencvjar -DartifactId=opencvjar -Dversion=3.0.0 -Dpackaging=jar

Make sure you use the same groupId and artifactId when referring to it in your pom.xml dependencies. Now, in order to install the native files, almost the same procedure will be used. Instead of installing the native file itself, it is advisable to convert it to a .jar file before installation. If you are using Linux, simply create a ZIP file from the and rename it as opencv_java300.jar. In fact, a JAR file is a ZIP file that obeys some standards. After you have created your JAR file, it is time to install it in your local Maven repository. Simply type the following command:

mvn install:install-file -Dfile=opencvjar -runtime-natives-linux-x86.jar -DgroupId=opencvjar -DartifactId=opencvjar-runtime -Dversion=3.0.0 -Dpackaging=jar -Dclassifier=natives-linux-x86

Notice the natives-linux-x86 classifier. This is important for the dependencies to specify their architecture. After typing it, you should have both the dependencies installed. Now, simply update your pom.xml file to refer to groupId opencvjar instead of org.javaopencvbook. Following the instructions from the previous section should make you ready to use Maven from your local repository.