Search icon CANCEL
Subscription
0
Cart icon
Your Cart (0 item)
Close icon
You have no products in your basket yet
Arrow left icon
Explore Products
Best Sellers
New Releases
Books
Videos
Audiobooks
Learning Hub
Conferences
Free Learning
Arrow right icon
OpenCV Computer Vision with Java
OpenCV Computer Vision with Java

OpenCV Computer Vision with Java: Create multiplatform computer vision desktop and web applications using the combination of OpenCV and Java

eBook
R$49.99 R$196.99
Paperback
R$245.99
Subscription
Free Trial
Renews at R$50p/m

What do you get with eBook?

Product feature icon Instant access to your Digital eBook purchase
Product feature icon Download this book in EPUB and PDF formats
Product feature icon Access this title in our online reader with advanced features
Product feature icon DRM FREE - Read whenever, wherever and however you want
OR
Modal Close icon
Payment Processing...
tick Completed

Billing Address

Table of content icon View table of contents Preview book icon Preview Book

OpenCV Computer Vision with Java

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:

Building OpenCV from the source code

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:

Building OpenCV from the source code

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:

Building OpenCV from the source code

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:

Building OpenCV from the source code

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.
    The Java OpenCV project in Eclipse
  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:
    The Java OpenCV project in Eclipse
  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:
    The Java OpenCV project in Eclipse
  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:

The Java OpenCV project in Eclipse

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.
    The NetBeans configuration
  2. Now, right-click on your Libraries folder and click on Add Library..., as shown in the following screenshot:
    The NetBeans configuration
  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:
    The NetBeans configuration
  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.
    The NetBeans configuration

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:

Building your project with Ant

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.

Left arrow icon Right arrow icon

Description

If you are a Java developer, student, researcher, or hobbyist wanting to create computer vision applications in Java then this book is for you. If you are an experienced C/C++ developer who is used to working with OpenCV, you will also find this book very useful for migrating your applications to Java. All you need is basic knowledge of Java, with no prior understanding of computer vision required, as this book will give you clear explanations and examples of the basics.

Who is this book for?

If you are a Java developer, student, researcher, or hobbyist wanting to create computer vision applications in Java then this book is for you. If you are an experienced C/C++ developer who is used to working with OpenCV, you will also find this book very useful for migrating your applications to Java.

What you will learn

  • Create powerful GUIs for computer vision applications with panels, scroll panes, radio buttons, sliders, windows, and mouse interaction using the popular Swing GUI widget toolkit
  • Stretch, shrink, warp, and rotate images, as well as apply image transforms to find edges, lines, and circles, and even use Discrete Fourier Transforms (DFT)
  • Detect foreground or background regions and work with depth images with a Kinect device
  • Learn how to add computer vision capabilities to rock solid Java web applications allowing you to upload photos and create astonishing effects
  • Track faces and apply mixed reality effects such as adding virtual hats to uploaded photos
  • Filter noisy images, work with morphological operators, use flood fill, and threshold the important regions of an image
  • Open and process video streams from webcams or video files

Product Details

Country selected
Publication date, Length, Edition, Language, ISBN-13
Publication date : Jul 30, 2015
Length: 174 pages
Edition : 1st
Language : English
ISBN-13 : 9781783283989
Vendor :
Intel
Category :
Languages :
Tools :

What do you get with eBook?

Product feature icon Instant access to your Digital eBook purchase
Product feature icon Download this book in EPUB and PDF formats
Product feature icon Access this title in our online reader with advanced features
Product feature icon DRM FREE - Read whenever, wherever and however you want
OR
Modal Close icon
Payment Processing...
tick Completed

Billing Address

Product Details

Publication date : Jul 30, 2015
Length: 174 pages
Edition : 1st
Language : English
ISBN-13 : 9781783283989
Vendor :
Intel
Category :
Languages :
Tools :

Packt Subscriptions

See our plans and pricing
Modal Close icon
R$50 billed monthly
Feature tick icon Unlimited access to Packt's library of 7,000+ practical books and videos
Feature tick icon Constantly refreshed with 50+ new titles a month
Feature tick icon Exclusive Early access to books as they're written
Feature tick icon Solve problems while you work with advanced search and reference features
Feature tick icon Offline reading on the mobile app
Feature tick icon Simple pricing, no contract
R$500 billed annually
Feature tick icon Unlimited access to Packt's library of 7,000+ practical books and videos
Feature tick icon Constantly refreshed with 50+ new titles a month
Feature tick icon Exclusive Early access to books as they're written
Feature tick icon Solve problems while you work with advanced search and reference features
Feature tick icon Offline reading on the mobile app
Feature tick icon Choose a DRM-free eBook or Video every month to keep
Feature tick icon PLUS own as many other DRM-free eBooks or Videos as you like for just R$25 each
Feature tick icon Exclusive print discounts
R$800 billed in 18 months
Feature tick icon Unlimited access to Packt's library of 7,000+ practical books and videos
Feature tick icon Constantly refreshed with 50+ new titles a month
Feature tick icon Exclusive Early access to books as they're written
Feature tick icon Solve problems while you work with advanced search and reference features
Feature tick icon Offline reading on the mobile app
Feature tick icon Choose a DRM-free eBook or Video every month to keep
Feature tick icon PLUS own as many other DRM-free eBooks or Videos as you like for just R$25 each
Feature tick icon Exclusive print discounts

Frequently bought together


Stars icon
Total R$ 825.97
Learning OpenCV 3 Computer Vision with Python (Update)
R$306.99
OpenCV Computer Vision with Java
R$245.99
Natural Language Processing with Java
R$272.99
Total R$ 825.97 Stars icon
Banner background image

Table of Contents

8 Chapters
1. Setting Up OpenCV for Java Chevron down icon Chevron up icon
2. Handling Matrices, Files, Cameras, and GUIs Chevron down icon Chevron up icon
3. Image Filters and Morphological Operators Chevron down icon Chevron up icon
4. Image Transforms Chevron down icon Chevron up icon
5. Object Detection Using Ada Boost and Haar Cascades Chevron down icon Chevron up icon
6. Detecting Foreground and Background Regions and Depth with a Kinect Device Chevron down icon Chevron up icon
7. OpenCV on the Server Side Chevron down icon Chevron up icon
Index Chevron down icon Chevron up icon

Customer reviews

Rating distribution
Full star icon Full star icon Full star icon Half star icon Empty star icon 3.4
(5 Ratings)
5 star 20%
4 star 40%
3 star 20%
2 star 0%
1 star 20%
splendkryp May 31, 2018
Full star icon Full star icon Full star icon Full star icon Full star icon 5
Very simple examples and great to start developing with OpenCV
Amazon Verified review Amazon
dreamgast-little Mar 29, 2016
Full star icon Full star icon Full star icon Full star icon Empty star icon 4
My problems with OpenCV were related to the installation of jdk8.0 and to make opencv compile and run on linux. Once installed you need to know about ant, eclipse, netbeans or maven.No easy for beginners but with internet and time.... Once the difficult installation done, you can find most informations on the site opencv.org.Why then 4 stars: This book is a good start for java opencv but not enough information are given about the installation and the reader is left alone to find links in internet for additional help
Amazon Verified review Amazon
CorGai Sep 24, 2015
Full star icon Full star icon Full star icon Full star icon Empty star icon 4
Das Buch beginnt sehr gut brauchbar, auch für Anfänger: Installation von OpenCV unter Eclipse, NetBeans..... Auch das erste Fallbeispiel, ein einfacher Grafik-Filter, ist noch sehr ausführlich erklärt. Danach wird das Buch schnell anspruchsvoller. Für mich - Java-Anfänger - ist das Buch dennoch insgesamt recht gut, weil viele verschiedene Methoden von OpenCV und Swing dargestellt werden. Macht Appetit nach mehr! Ich pesönlich möchte mich in Richtung Objekterkennung weiter entwickeln. Hierzu sind einige wenige Methoden beschrieben. Wer "nur" anwenden will, findet sicher Gefallen an der Begleitsoftware, die von der Verleger-Seite herunter geladen werden kann.
Amazon Verified review Amazon
Amazon Customer Apr 09, 2017
Full star icon Full star icon Full star icon Empty star icon Empty star icon 3
some of the codes in the book are incomplete and you already need to understand java coding to use that book.
Amazon Verified review Amazon
OLFO79 Nov 25, 2016
Full star icon Empty star icon Empty star icon Empty star icon Empty star icon 1
A book dealing with a software library should give an overview over the library like structure, classes,.. I did not find anything like that in the book. It's just a collection of short examples.There are many mistakes in the sample code:The Java-Wrapper has switched rows and columns compared to C++, so you always get only one line from the Hough-Transformation, if you look on the cols instead of the rows of the result. The Canny-Function does not accept aperture > 7, and so on....If you know Java, you will not learn much about Computer Vision from this book. If you know Computer Vision you will not learn much about Java. There's just a lot of source code to fill the pages..
Amazon Verified review Amazon
Get free access to Packt library with over 7500+ books and video courses for 7 days!
Start Free Trial

FAQs

How do I buy and download an eBook? Chevron down icon Chevron up icon

Where there is an eBook version of a title available, you can buy it from the book details for that title. Add either the standalone eBook or the eBook and print book bundle to your shopping cart. Your eBook will show in your cart as a product on its own. After completing checkout and payment in the normal way, you will receive your receipt on the screen containing a link to a personalised PDF download file. This link will remain active for 30 days. You can download backup copies of the file by logging in to your account at any time.

If you already have Adobe reader installed, then clicking on the link will download and open the PDF file directly. If you don't, then save the PDF file on your machine and download the Reader to view it.

Please Note: Packt eBooks are non-returnable and non-refundable.

Packt eBook and Licensing When you buy an eBook from Packt Publishing, completing your purchase means you accept the terms of our licence agreement. Please read the full text of the agreement. In it we have tried to balance the need for the ebook to be usable for you the reader with our needs to protect the rights of us as Publishers and of our authors. In summary, the agreement says:

  • You may make copies of your eBook for your own use onto any machine
  • You may not pass copies of the eBook on to anyone else
How can I make a purchase on your website? Chevron down icon Chevron up icon

If you want to purchase a video course, eBook or Bundle (Print+eBook) please follow below steps:

  1. Register on our website using your email address and the password.
  2. Search for the title by name or ISBN using the search option.
  3. Select the title you want to purchase.
  4. Choose the format you wish to purchase the title in; if you order the Print Book, you get a free eBook copy of the same title. 
  5. Proceed with the checkout process (payment to be made using Credit Card, Debit Cart, or PayPal)
Where can I access support around an eBook? Chevron down icon Chevron up icon
  • If you experience a problem with using or installing Adobe Reader, the contact Adobe directly.
  • To view the errata for the book, see www.packtpub.com/support and view the pages for the title you have.
  • To view your account details or to download a new copy of the book go to www.packtpub.com/account
  • To contact us directly if a problem is not resolved, use www.packtpub.com/contact-us
What eBook formats do Packt support? Chevron down icon Chevron up icon

Our eBooks are currently available in a variety of formats such as PDF and ePubs. In the future, this may well change with trends and development in technology, but please note that our PDFs are not Adobe eBook Reader format, which has greater restrictions on security.

You will need to use Adobe Reader v9 or later in order to read Packt's PDF eBooks.

What are the benefits of eBooks? Chevron down icon Chevron up icon
  • You can get the information you need immediately
  • You can easily take them with you on a laptop
  • You can download them an unlimited number of times
  • You can print them out
  • They are copy-paste enabled
  • They are searchable
  • There is no password protection
  • They are lower price than print
  • They save resources and space
What is an eBook? Chevron down icon Chevron up icon

Packt eBooks are a complete electronic version of the print edition, available in PDF and ePub formats. Every piece of content down to the page numbering is the same. Because we save the costs of printing and shipping the book to you, we are able to offer eBooks at a lower cost than print editions.

When you have purchased an eBook, simply login to your account and click on the link in Your Download Area. We recommend you saving the file to your hard drive before opening it.

For optimal viewing of our eBooks, we recommend you download and install the free Adobe Reader version 9.