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.
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
.
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:
CMake 2.6 or higher: This is a cross-platform and an open source building system. You can download it from http://www.cmake.org/cmake/resources/software.html.
Python 2.6 or later with python-dev and python-numpy: This is the Python language that is used to run Java building scripts. You can download Python from http://www.python.org/getit/ and download the packages from http://sourceforge.net/projects/numpy/files/NumPy.
C/C++ compilers: These compilers are required to generate the native code. In Windows, you can install Microsoft Visual Studio Community or Express, which are free, from http://www.visualstudio.com/downloads/. Also, these compilers work with the Visual Studio Professional edition and the versions above 2010 should work fine. You can also make it work with MinGW, which can be downloaded from http://sourceforge.net/projects/mingw/files/Installer/. In Linux, you are advised to use the Gnu C Compiler (GCC) with a simple
sudo apt-get install build-essential
command in Ubuntu or Debian, for instance. In case you work with the Mac, you should use XCode.Java Developer Kit (JDK): JDK is required to generate the JAR files, which will be required for every Java OpenCV program. Recommended versions begin from Oracle, JDK 6, 7, or 8, which can be downloaded from http://www.oracle.com/technetwork/java/javase/downloads/index-jsp-138363.html. Please follow the operating system-specific instructions in the link in order to install it.
Apache Ant: This is a pure Java build tool. Look for binary distributions at http://ant.apache.org/bindownload.cgi. Make sure you set the
ANT_HOME
variable correctly as pointed out in the installation instructions at http://ant.apache.org/manual/index.html.
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.
Note
For more details on how to compile OpenCV for your platform, look for http://docs.opencv.org/doc/tutorials/introduction/table_of_content_introduction/table_of_content_introduction.html.
Congratulations! You are now halfway to becoming a great developer using OpenCV!
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.
In Eclipse, go to File | New | Java Project.
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:Select User Library in the Add Library dialog, and then click Next.
Now, click on the User Libraries… button.
Click on New…. Name your library appropriately, for example,
opencv-3.0.0
. It's time to reference the JAR files.Click on Add JARs….
Select the
opencv-300.jar
file in your filesystem; it should be in theopencv\build\java
folder. Then, point to the native library location expanding your JAR as in the following screenshot: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\
.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.
In case you are more comfortable working with NetBeans, the configuration process is pretty much like Eclipse:
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.
Now, right-click on your Libraries folder and click on Add Library..., as shown in the following screenshot:
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:Now point to your library, which is where the
opencv-300.jar
file is present—usually inopencv/build/java/
. As your library is properly configured, select it in the Add Library dialog.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.
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]
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"/>
.
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.
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:
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 thegenerate goal
command from the archetype plugin. From the documentation, we see thatgenerate 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
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 inD:\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 yourpom.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 insideopencvjar-runtime-3.0.0-natives-windows-x86_64.jar
. Near thejunit
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 usenatives-windows-x86
.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 themvn package
command. But, this will only happen if you addmaven-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 themaven-dependency-plugin
. The last detail is to point your main class when creating a JAR, which is performed bymaven-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 thechapter1/maven-sample
directory in this chapter's sample code.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 yourmy-opencv-app-1.0-SNAPSHOT.jar
in thetarget
folder, as well as copy all the dependent libraries to yourtarget/lib
folder; check for thejunit
,opencvjar
, andopencvjar-runtime
JARs. Also, the native libraries are extracted to thetarget
/natives
folder, soopencv_java300.dll
can be found there. Your compiled classes can also be found in thetarget
/classes
folder. The other generated folders are related to your tests.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 theApp.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 theApp
class. Now we just need to run it. Remember to recompile it by running the following command:mvn package
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 calledrun.bat
, for instance, and save it in theD:\mvnopencv\my-opencv-app
folder.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.
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.
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.