Home Data OpenCV 3.0 Computer Vision with Java

OpenCV 3.0 Computer Vision with Java

By Daniel Lelis Baggio
books-svg-icon Book
eBook $35.99 $24.99
Print $43.99
Subscription $15.99 $10 p/m for three months
$10 p/m for first 3 months. $15.99 p/m after that. Cancel Anytime!
What do you get with a Packt Subscription?
This book & 7000+ ebooks & video courses on 1000+ technologies
60+ curated reading lists for various learning paths
50+ new titles added every month on new and emerging tech
Early Access to eBooks as they are being written
Personalised content suggestions
Customised display settings for better reading experience
50+ new titles added every month on new and emerging tech
Playlists, Notes and Bookmarks to easily manage your learning
Mobile App with offline access
What do you get with a Packt Subscription?
This book & 6500+ ebooks & video courses on 1000+ technologies
60+ curated reading lists for various learning paths
50+ new titles added every month on new and emerging tech
Early Access to eBooks as they are being written
Personalised content suggestions
Customised display settings for better reading experience
50+ new titles added every month on new and emerging tech
Playlists, Notes and Bookmarks to easily manage your learning
Mobile App with offline access
What do you get with eBook + Subscription?
Download this book in EPUB and PDF formats, plus a monthly download credit
This book & 6500+ ebooks & video courses on 1000+ technologies
60+ curated reading lists for various learning paths
50+ new titles added every month on new and emerging tech
Early Access to eBooks as they are being written
Personalised content suggestions
Customised display settings for better reading experience
50+ new titles added every month on new and emerging tech
Playlists, Notes and Bookmarks to easily manage your learning
Mobile App with offline access
What do you get with a Packt Subscription?
This book & 6500+ ebooks & video courses on 1000+ technologies
60+ curated reading lists for various learning paths
50+ new titles added every month on new and emerging tech
Early Access to eBooks as they are being written
Personalised content suggestions
Customised display settings for better reading experience
50+ new titles added every month on new and emerging tech
Playlists, Notes and Bookmarks to easily manage your learning
Mobile App with offline access
What do you get with eBook?
Download this book in EPUB and PDF formats
Access this title in our online reader
DRM FREE - Read whenever, wherever and however you want
Online reader with customised display settings for better reading experience
What do you get with video?
Download this video in MP4 format
Access this title in our online reader
DRM FREE - Watch whenever, wherever and however you want
Online reader with customised display settings for better learning experience
What do you get with video?
Stream this video
Access this title in our online reader
DRM FREE - Watch whenever, wherever and however you want
Online reader with customised display settings for better learning experience
What do you get with Audiobook?
Download a zip folder consisting of audio files (in MP3 Format) along with supplementary PDF
What do you get with Exam Trainer?
Flashcards, Mock exams, Exam Tips, Practice Questions
Access these resources with our interactive certification platform
Mobile compatible-Practice whenever, wherever, however you want
BUY NOW $10 p/m for first 3 months. $15.99 p/m after that. Cancel Anytime!
eBook $35.99 $24.99
Print $43.99
Subscription $15.99 $10 p/m for three months
What do you get with a Packt Subscription?
This book & 7000+ ebooks & video courses on 1000+ technologies
60+ curated reading lists for various learning paths
50+ new titles added every month on new and emerging tech
Early Access to eBooks as they are being written
Personalised content suggestions
Customised display settings for better reading experience
50+ new titles added every month on new and emerging tech
Playlists, Notes and Bookmarks to easily manage your learning
Mobile App with offline access
What do you get with a Packt Subscription?
This book & 6500+ ebooks & video courses on 1000+ technologies
60+ curated reading lists for various learning paths
50+ new titles added every month on new and emerging tech
Early Access to eBooks as they are being written
Personalised content suggestions
Customised display settings for better reading experience
50+ new titles added every month on new and emerging tech
Playlists, Notes and Bookmarks to easily manage your learning
Mobile App with offline access
What do you get with eBook + Subscription?
Download this book in EPUB and PDF formats, plus a monthly download credit
This book & 6500+ ebooks & video courses on 1000+ technologies
60+ curated reading lists for various learning paths
50+ new titles added every month on new and emerging tech
Early Access to eBooks as they are being written
Personalised content suggestions
Customised display settings for better reading experience
50+ new titles added every month on new and emerging tech
Playlists, Notes and Bookmarks to easily manage your learning
Mobile App with offline access
What do you get with a Packt Subscription?
This book & 6500+ ebooks & video courses on 1000+ technologies
60+ curated reading lists for various learning paths
50+ new titles added every month on new and emerging tech
Early Access to eBooks as they are being written
Personalised content suggestions
Customised display settings for better reading experience
50+ new titles added every month on new and emerging tech
Playlists, Notes and Bookmarks to easily manage your learning
Mobile App with offline access
What do you get with eBook?
Download this book in EPUB and PDF formats
Access this title in our online reader
DRM FREE - Read whenever, wherever and however you want
Online reader with customised display settings for better reading experience
What do you get with video?
Download this video in MP4 format
Access this title in our online reader
DRM FREE - Watch whenever, wherever and however you want
Online reader with customised display settings for better learning experience
What do you get with video?
Stream this video
Access this title in our online reader
DRM FREE - Watch whenever, wherever and however you want
Online reader with customised display settings for better learning experience
What do you get with Audiobook?
Download a zip folder consisting of audio files (in MP3 Format) along with supplementary PDF
What do you get with Exam Trainer?
Flashcards, Mock exams, Exam Tips, Practice Questions
Access these resources with our interactive certification platform
Mobile compatible-Practice whenever, wherever, however you want
  1. Free Chapter
    Setting Up OpenCV for Java
About this book
Publication date:
July 2015
Publisher
Packt
Pages
174
ISBN
9781783283972

 

Chapter 1. Setting Up OpenCV for Java

I'm sure you want to start developing astonishing computer vision applications. You must have heard of a nice C/C++ computer vision library called OpenCV to help you do so. But in case you would like to develop the applications using your knowledge of Java programming, we have good news for you. Since the release of OpenCV 2.4.4 in January 2013, Java bindings have been officially developed. So you can use them not only for desktop Java, but also for Scala development.

This chapter will set you up for OpenCV development right away. As Java developers are mostly used to working with tools such as Eclipse, NetBeans, Apache Ant, and Maven, we will cover the details of creating a simple OpenCV application using the environment that the Java developers are more used to.

In this chapter, we will do the following:

  • Get OpenCV with desktop Java support

  • Discuss Java Native Interface (JNI) details

  • Configure Eclipse and NetBeans for OpenCV

  • Create Apache Ant and Maven OpenCV projects

By the end of this chapter, the user should have an OpenCV for Java installation running on his OS which can easily be linked to Eclipse, NetBeans, Apache Ant, or Maven, the most used tools and building systems for Java.

 

Getting OpenCV for Java development


The first thing to notice when working with OpenCV for Java development is that OpenCV is a C++ library that should be compiled with operating system- specific compilers. The native code that would be generated is platform-dependent. So, the native Linux code won't run in Windows, neither will the Android native code run in OSX. This sounds very different from the bytecode generated for Java, which is executed by an interpreter in any platform. In order to get the native code running in a Java Virtual Machine (JVM), one needs the so called Java Native Interface (JNI). This way, the native code will be required for each platform that your application is going to be run on.

It is important to understand that JNI is a native programming interface. It allows the Java code that runs inside a JVM to interoperate with the applications and libraries written in programming languages such as C, C++, and assembly. Since it bridges the gap between Java and other languages, it needs to convert datatypes from these languages, as well as to create some boilerplate code. Curious readers should refer to the gen_java.py script, located in the modules/java/generator folder, which automates most of this work. Lucky Windows users get compiled binaries, which means source C++ OpenCV code, compiled with Windows compilers into native code that runs only on Windows, from OpenCV packages. Users from other operating systems will need to build binaries from the source code, although one can make that in Windows as well. In order to download compiled binaries, we should get version 2.4.4 or higher of the OpenCV Windows package from the OpenCV SourceForge repository, which is located at http://sourceforge.net/projects/opencvlibrary/files/.

Note

Notice that the prebuilt files needed for Java development are located at opencv/build/java/. For instance, if you are working with version 3.0.0 OpenCV, you should see files containing the Java interface in opencv-300.jar and in the x86 and x64 native dynamic libraries, which contains the Java bindings in x86/opencv_java300.dll and x64/opencv_java300.dll.

 

Building OpenCV from the source code


In this section, we are mostly interested in generating all the OpenCV Java class files contained in a JAR file as well as the native dynamic library for Java OpenCV. This is a self-contained library that works with JNI and is required to run a Java OpenCV application.

In case you are working with Linux or OSX, or if you want to build from the source in Windows, then to get the latest features committed in OpenCV, you should use the source code. You can visit the OpenCV download page at http://opencv.org/downloads.html and choose the appropriate link for your distribution.

Another way to get the source code is by using the git tool. Appropriate instructions for installing it can be found at http://git-scm.com/downloads. When using git, use the following commands:

git clone git://github.com/Itseez/opencv.git
cd opencv
git checkout 3.0.0-rc1
mkdir build
cd build

These commands will access the OpenCV developers' repository and download the most updated code from branch 3.0.0-rc1, which is the release candidate for version 3.0.0.

In either method of obtaining the source code, you will need building tools in order to make binaries. The required packages are as follows:

In order to install these software in a Linux distribution such as Ubuntu or Debian, the user should issue the following command:

sudo apt-get install build-essential cmake git libgtk2.0-dev pkg-config libavcodec-dev libavformat-dev libswscale-dev python-dev python-numpy libtbb2 libtbb-dev libjpeg-dev libpng-dev libtiff-dev libjasper-dev libdc1394-22-dev ant

Once you have installed all these packages, you will be ready to build the library. Make sure you are in the build directory, as you should be, if you have followed the preceding Git instructions. In case you downloaded the source file from OpenCV downloads, the parent folder of your build should have CMakeLists.txt as well as the 3rdparty, apps, cmake, data, doc, include, modules, platforms, samples, and test folders.

CMake is a build tool and it will generate your compiler-specific solution files. You should then use your compiler to generate the binary files. Make sure you are in the build directory, as this should follow the last cd build command. If you are using Linux, run the following commands:

cmake -DBUILD_SHARED_LIBS=OFF

If you are using Windows, run the following command:

cmake -DBUILD_SHARED_LIBS=OFF -G "Visual Studio 10"

Notice that it is important to use the DBUILD_SHARED_LIBS=OFF flag, because it will instruct CMake to build OpenCV on a set of static libraries. This way, it will compile a single dynamic link library for Java without dependencies on other libraries. This makes it easier to deploy your Java projects.

Note

If you are using other compilers in Windows, type cmake –help and it will show all the generators available.

In case you want to use MinGW makefiles, just change the CMake command to the following command:

cmake -DBUILD_SHARED_LIBS=OFF -G "MinGW Makefiles"

One of the key points to watch for when generating project files through CMake is that java is one of the modules that is going to be built. You should see a screen as shown in the following screenshot:

In case you can't see java as one of the to-be-built modules, like in the following screenshot, you should look for a couple of things, such as whether Ant is correctly configured. Also make sure that you have set the ANT_HOME environment variable and that Python is correctly configured. Check if NumPy is installed by simply typing numpy import * in a Python shell and check for any errors:

In case you are in doubt about the Python and Java installations, slide down to check their configurations. They should be similar to the next screenshot:

Once everything has been correctly configured, it is time to start compiling the sources. In order to do so in Windows, type the following:

msbuild /m OpenCV.sln /t:Build /p:Configuration=Release /v:m

Notice that you might get an error saying, 'msbuild' is not recognized as an internal or external command, operable program or batch file. This occurs when you haven't set the msbuild path. In order to set it right, open Visual Studio and in the Tools menu, click Visual Studio Command Prompt. This will yield a fully working command prompt with access to msbuild. Refer to the following screenshot for clearer directions:

In case you are using newer Visual Studio versions, press the Windows key and type VS2012 Command Prompt. This should set up your environment variables.

In order to start building in Linux, simply type the following command:

make -j8

The preceding command will compile the OpenCV library with Java support. Notice that the -j8 flag tells make to run in parallel with eight job threads, which makes the build theoretically faster.

Tip

Downloading the example code

You can download the example code files from your account at http://www.packtpub.com for all the Packt Publishing books you have purchased. If you purchased this book elsewhere, you can visit http://www.packtpub.com/support and register to have the files e-mailed directly to you.

The entire process will last for some minutes before generating a JAR file that contains the Java interfaces, which is located at bin/opencv-300.jar. The native dynamic link library containing Java bindings is generated at lib/libopencv_java300.so or bin/Release/opencv_java300.dll, depending on your operating system. These files will be used when we create our first OpenCV application.

Congratulations! You are now halfway to becoming a great developer using OpenCV!

 

The Java OpenCV project in Eclipse


Using OpenCV in any IDE is pretty simple. It is as simple as adding OpenCV JAR, that is, opencv-300.jar to your classpath. But, as it relies on the native code, you need to point out the dynamic link libraries—so for Linux, .dll for Windows, and dylib for MacOsX.

  1. In Eclipse, go to File | New | Java Project.

  2. Give the new project a descriptive name, such as SimpleSample. Select the project in the Package Explorer, go to the Project menu and click on Properties. On the Java Build Path tab, go to the Libraries tab, and click on the Add Library… button on the right-hand side, as shown in the following screenshot:

  3. Select User Library in the Add Library dialog, and then click Next.

  4. Now, click on the User Libraries… button.

  5. Click on New…. Name your library appropriately, for example, opencv-3.0.0. It's time to reference the JAR files.

  6. Click on Add JARs….

  7. Select the opencv-300.jar file in your filesystem; it should be in the opencv\build\java folder. Then, point to the native library location expanding your JAR as in the following screenshot:

  8. Now, select Native library location by clicking on the Edit… button on the right-hand side of the window and set your native libraries' location folder, for example, opencv\build\java\x64\.

  9. Now that OpenCV is properly configured, just select it in your Add library dialog by pressing Finish.

Notice that your project now points to the OpenCV JAR. You can also browse the main classes from the Package Explorer, as seen in the following screenshot:

After the The NetBeans configuration section, a source code to create a simple OpenCV application can be found.

 

The NetBeans configuration


In case you are more comfortable working with NetBeans, the configuration process is pretty much like Eclipse:

  1. Select File | New Project.... On the Projects tab, select Java Application and click on Next. Give the new project an appropriate name and click on Finish.

  2. Now, right-click on your Libraries folder and click on Add Library..., as shown in the following screenshot:

  3. As we haven't gone through this process before, a library for OpenCV won't exist. Click on the Create... button on the right-hand side of the pane. It will open a dialog asking for the library name—name it as OpenCV—and the Library type, for which you should leave the default option Class Libraries. In the next screen, on the Classpath tab, click Add JAR/Folder... like in the next screenshot:

  4. Now point to your library, which is where the opencv-300.jar file is present—usually in opencv/build/java/. As your library is properly configured, select it in the Add Library dialog.

  5. The last detail to provide is the path for the libraries' native files. Right-click on your project name in the Projects tab and select Properties. Go to the Run item on the tree and under VM Options, set the library path by typing -Djava.library.path=C:\Users\baggio\Downloads\opencv\build\java\x64 in the text box.

Make sure you change the given path to the one where your OpenCV installation is, and that it points to the folder where the native libraries are, that is, opencv_java300.dll in Windows, or libopencv_java300.so in Linux. Now, add the SimpleSample class code in your project, as pointed. Run the sample and make sure that you don't get any errors.

 

A Java OpenCV simple application


It's time to create a simple application that will show that we can now compile and execute Java code with OpenCV. Create a new Java class containing a Main method and paste the code given as follows. It simply creates a 5 x 10 OpenCV matrix, sets some of its rows and columns, and prints the result to the standard output.

Make sure you load the correct dynamic link libraries through a call to System.loadlibrary("opencv_java300"). Since, you might want to change the library version later, a better approach would be to use the Core.NATIVE_LIBARAY_NAME constant, which will output the correct library name. You can also find this file in the code repository for chapter1 of this book, under ant/src.

import org.opencv.core.Core;
import org.opencv.core.Mat;
import org.opencv.core.CvType;
import org.opencv.core.Scalar;

class SimpleSample {

  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());
  }

}

According to Oracle's documentation, it states that, class can have any number of static initialization blocks. And they can appear anywhere in the class body. The runtime system guarantees that static initialization blocks are called in the order that they appear in the source code.

You should make sure that any calls to the OpenCV library are preceded by a single System.loadLibrary call, in order to load the dynamic libraries. Otherwise, you will receive an java.lang.UnsatisfiedLinkError: org.opencv.core.Mat.n_Mat(IIIDDDD)J error. This generally occurs in a static block.

If everything goes well, you should see the following output in the console:

Welcome to OpenCV 3.0.0-rc1
OpenCV Mat: Mat [ 5*10*CV_8UC1, isCont=true, isSubmat=false, nativeObj=0x2291b70, dataAddr=0x229bbd0 ]
OpenCV Mat data:
[ 0, 0, 0, 0, 0, 5, 0, 0, 0, 0;
  1, 1, 1, 1, 1, 5, 1, 1, 1, 1;
  0, 0, 0, 0, 0, 5, 0, 0, 0, 0;
  0, 0, 0, 0, 0, 5, 0, 0, 0, 0;
  0, 0, 0, 0, 0, 5, 0, 0, 0, 0]
 

Building your project with Ant


If you want to rely on Apache Ant for building instead of using an IDE, a build.xml file is provided in the OpenCV samples. You can find this file in this chapter's repository as well. The following are its contents:

<project name="SimpleSample" basedir="." default="rebuild-run">
    <property name="src.dir"     value="src"/>
    <property name="lib.dir"     value="${ocvJarDir}"/>
    <path id="classpath">
        <fileset dir="${lib.dir}" includes="**/*.jar"/>
    </path>
    <property name="build.dir"   value="build"/>
    <property name="classes.dir" value="${build.dir}/classes"/>
    <property name="jar.dir"     value="${build.dir}/jar"/>
    <property name="main-class"  value="${ant.project.name}"/>

    <target name="clean">
        <delete dir="${build.dir}"/>
    </target>

    <target name="compile">
        <mkdir dir="${classes.dir}"/>
        <javac includeantruntime="false" srcdir="${src.dir}" destdir="${classes.dir}" classpathref="classpath"/>
    </target>

    <target name="jar" depends="compile">
        <mkdir dir="${jar.dir}"/>
        <jar destfile="${jar.dir}/${ant.project.name}.jar" basedir="${classes.dir}">
            <manifest>
                <attribute name="Main-Class" value="${main-class}"/>
            </manifest>
        </jar>
    </target>

    <target name="run" depends="jar">
        <java fork="true" classname="${main-class}">
            <sysproperty key="java.library.path" path="${ocvLibDir}"/>
            <classpath>
                <path refid="classpath"/>
                <path location="${jar.dir}/${ant.project.name}.jar"/>
            </classpath>
        </java>
    </target>

    <target name="rebuild" depends="clean,jar"/>

    <target name="rebuild-run" depends="clean,run"/>

</project>

This is a basic build.xml Ant file that defines tasks such as cleaning, compiling, and packing a .jar file, running, rebuilding, and rebuild-running. It expects your source code to be in a sibling folder called src. Make sure that the SimpleSample.java source code provided earlier is inside this directory.

Compiling and running the project using Ant is easy. Simply type the following:

ant -DocvJarDir=path/to/dir/containing/opencv-300.jar -DocvLibDir=path/to/dir/containing/opencv_java300/native/library

In case you have downloaded and extracted pre-built binaries, use the following command instead:

ant -DocvJarDir=X:\opencv3.0.0\opencv\build\java -DocvLibDir=X:\opencv3.00\opencv\build\java\x64

A successful run of Ant build.xml will look like the following screenshot:

The provided build.xml file can be reused for building your Java OpenCV applications. In order to use it, make sure that the project name matches your main class name. If your main class is inside the package com.your.company, and it's called MainOpenCV, you should change the first line of build.xml from <project name="SimpleSample" basedir="." default="rebuild-run"> to <project name="com.your.company.MainOpenCV" basedir="." default="rebuild-run">.

You can also hardcode the ocvJarDir and ocvLibDir properties so you won't have to type them while invoking Ant. For ocvJarDir, simply change the <property name="lib.dir" value="${ocvJarDir}"/> command to <property name="lib.dir" value="X:\opencv2.47\opencv\build\java"/>.

 

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 -DgroupId=some.group -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 -DgroupId=com.mycompany.app -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:

    my-opencv-app
    |-- pom.xml
    `-- src
        |-- main
        |   `-- java
        |       `-- com
        |           `-- company
        |               `-- app
        |                   `-- App.java
        `-- test
            `-- java
                `-- com
                    `-- company
                        `-- app
                            `-- AppTest.java

    Note

    Note that the -DgroupId=com.mycompany.app -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="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
      xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/maven-v4_0_0.xsd">  
      
      <repositories>
        <repository>
          <id>javaopencvbook</id>
          <url>https://raw.github.com/JavaOpenCVBook/code/maven2/</url>
        </repository>
     </repositories>
    
     <modelVersion>4.0.0</modelVersion>
    …
    </project>

    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:

    <dependencies>
      <dependency>
        <groupId>junit</groupId>
        <artifactId>junit</artifactId>
        <version>3.8.1</version>
        <scope>test</scope>
      </dependency>
      <dependency>
        <groupId>org.javaopencvbook</groupId>
        <artifactId>opencvjar</artifactId>
        <version>3.0.0</version>
      </dependency>
      <dependency>
        <groupId>org.javaopencvbook</groupId>
        <artifactId>opencvjar-runtime</artifactId>
        <version>3.0.0</version>
        <classifier>natives-windows-x86_64</classifier>
      </dependency>
    </dependencies>

    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:

    <build>
      <plugins>
        <plugin>
          <artifactId>maven-jar-plugin</artifactId>
          <version>2.4</version>
          <configuration>
            <archive>
              <manifest>
                <addClasspath>true</addClasspath>
                <classpathPrefix>lib/</classpathPrefix>
                <mainClass>com.mycompany.app.App</mainClass>
              </manifest>
            </archive>
          </configuration>
        </plugin>
        <plugin>
          <groupId>org.apache.maven.plugins</groupId>
          <artifactId>maven-dependency-plugin</artifactId>
          <version>2.1</version>
          <executions>
            <execution>
              <id>copy-dependencies</id>
              <phase>package</phase>
              <goals>
                <goal>copy-dependencies</goal>
              </goals>
              <configuration>
                <outputDirectory>${project.build.directory}/lib</outputDirectory>
                <overWriteReleases>false</overWriteReleases>
                <overWriteSnapshots>false</overWriteSnapshots>
                <overWriteIfNewer>true</overWriteIfNewer>
              </configuration>
            </execution>
          </executions>
        </plugin>
        <plugin>
          <groupId>com.googlecode.mavennatives</groupId>
          <artifactId>maven-nativedependencies-plugin</artifactId>
          <version>0.0.7</version>
          <executions>
            <execution>
              <id>unpacknatives</id>
              <phase>generate-resources</phase>
              <goals>
                <goal>copy</goal>
              </goals>
            </execution>
          </executions>
        </plugin>
      </plugins>
    </build>

    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 App.java 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 App.java file. Simply add the following code:

    package com.mycompany.app;
    
    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 App.java 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 opencv_java300.so 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 opencv_java300.so 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.

 

Summary


This chapter provided several different approaches for setting up OpenCV for Java, that is, by either installing compiled binaries or compiling it from the source. It also pointed to instructions for making the main configurations in Eclipse and NetBeans IDE as well as for using building tools such as Ant and Maven. The user should be ready to easily start using OpenCV in his/her Java projects.

The next chapter will go deeper into OpenCV and address basic tasks such as handling images through matrices, reading image files, retrieving frames from a webcam, and creating nice Swing GUIs for your computer vision applications.

About the Author
  • Daniel Lelis Baggio

    Daniel Lélis Baggio has started his works in computer vision through medical image processing at InCor (Instituto do Coração – Heart Institute) in São Paulo, Brazil, where he worked with intra-vascular ultrasound (IVUS) image segmentation. After that he has focused on GPGPU and ported that algorithm to work with NVidia's Cuda. He has also dived into 6 degrees of freedom head tracking with Natural User Interface group through a project called EHCI (http://code.google.com/p/ehci/ ). He also wrote “Mastering OpenCV with Practical Computer Vision Projects” from Packt Publishing.

    Browse publications by this author
Latest Reviews (4 reviews total)
4.5 The only issue is there is no support for the latest version.
It covers part of major topics in openCV. It does not provide major java classes and their methods in openCV. I want to know how to convert C++ openCV code to java code.
It is well explained. I like the examples. I just don't like going to the separated code examples. I would prefer to be included in the book.
OpenCV 3.0 Computer Vision with Java
Unlock this book and the full library FREE for 7 days
Start now