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
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
€8.99 €26.99
Paperback
€32.99
Subscription
Free Trial
Renews at €18.99p/m

What do you get with Print?

Product feature icon Instant access to your digital eBook copy whilst your Print order is Shipped
Product feature icon Paperback book shipped to your preferred address
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

Shipping Address

Billing Address

Shipping Methods
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
Estimated delivery fee Deliver to Lithuania

Premium delivery 7 - 10 business days

€25.95
(Includes tracking information)

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 : 9781783283972
Vendor :
Intel
Category :
Languages :
Tools :

What do you get with Print?

Product feature icon Instant access to your digital eBook copy whilst your Print order is Shipped
Product feature icon Paperback book shipped to your preferred address
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

Shipping Address

Billing Address

Shipping Methods
Estimated delivery fee Deliver to Lithuania

Premium delivery 7 - 10 business days

€25.95
(Includes tracking information)

Product Details

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

Packt Subscriptions

See our plans and pricing
Modal Close icon
€18.99 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
€189.99 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 €5 each
Feature tick icon Exclusive print discounts
€264.99 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 €5 each
Feature tick icon Exclusive print discounts

Frequently bought together


Stars icon
Total 111.97
Learning OpenCV 3 Computer Vision with Python (Update)
€41.99
OpenCV Computer Vision with Java
€32.99
Natural Language Processing with Java
€36.99
Total 111.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

What is the delivery time and cost of print book? Chevron down icon Chevron up icon

Shipping Details

USA:

'

Economy: Delivery to most addresses in the US within 10-15 business days

Premium: Trackable Delivery to most addresses in the US within 3-8 business days

UK:

Economy: Delivery to most addresses in the U.K. within 7-9 business days.
Shipments are not trackable

Premium: Trackable delivery to most addresses in the U.K. within 3-4 business days!
Add one extra business day for deliveries to Northern Ireland and Scottish Highlands and islands

EU:

Premium: Trackable delivery to most EU destinations within 4-9 business days.

Australia:

Economy: Can deliver to P. O. Boxes and private residences.
Trackable service with delivery to addresses in Australia only.
Delivery time ranges from 7-9 business days for VIC and 8-10 business days for Interstate metro
Delivery time is up to 15 business days for remote areas of WA, NT & QLD.

Premium: Delivery to addresses in Australia only
Trackable delivery to most P. O. Boxes and private residences in Australia within 4-5 days based on the distance to a destination following dispatch.

India:

Premium: Delivery to most Indian addresses within 5-6 business days

Rest of the World:

Premium: Countries in the American continent: Trackable delivery to most countries within 4-7 business days

Asia:

Premium: Delivery to most Asian addresses within 5-9 business days

Disclaimer:
All orders received before 5 PM U.K time would start printing from the next business day. So the estimated delivery times start from the next day as well. Orders received after 5 PM U.K time (in our internal systems) on a business day or anytime on the weekend will begin printing the second to next business day. For example, an order placed at 11 AM today will begin printing tomorrow, whereas an order placed at 9 PM tonight will begin printing the day after tomorrow.


Unfortunately, due to several restrictions, we are unable to ship to the following countries:

  1. Afghanistan
  2. American Samoa
  3. Belarus
  4. Brunei Darussalam
  5. Central African Republic
  6. The Democratic Republic of Congo
  7. Eritrea
  8. Guinea-bissau
  9. Iran
  10. Lebanon
  11. Libiya Arab Jamahriya
  12. Somalia
  13. Sudan
  14. Russian Federation
  15. Syrian Arab Republic
  16. Ukraine
  17. Venezuela
What is custom duty/charge? Chevron down icon Chevron up icon

Customs duty are charges levied on goods when they cross international borders. It is a tax that is imposed on imported goods. These duties are charged by special authorities and bodies created by local governments and are meant to protect local industries, economies, and businesses.

Do I have to pay customs charges for the print book order? Chevron down icon Chevron up icon

The orders shipped to the countries that are listed under EU27 will not bear custom charges. They are paid by Packt as part of the order.

List of EU27 countries: www.gov.uk/eu-eea:

A custom duty or localized taxes may be applicable on the shipment and would be charged by the recipient country outside of the EU27 which should be paid by the customer and these duties are not included in the shipping charges been charged on the order.

How do I know my custom duty charges? Chevron down icon Chevron up icon

The amount of duty payable varies greatly depending on the imported goods, the country of origin and several other factors like the total invoice amount or dimensions like weight, and other such criteria applicable in your country.

For example:

  • If you live in Mexico, and the declared value of your ordered items is over $ 50, for you to receive a package, you will have to pay additional import tax of 19% which will be $ 9.50 to the courier service.
  • Whereas if you live in Turkey, and the declared value of your ordered items is over € 22, for you to receive a package, you will have to pay additional import tax of 18% which will be € 3.96 to the courier service.
How can I cancel my order? Chevron down icon Chevron up icon

Cancellation Policy for Published Printed Books:

You can cancel any order within 1 hour of placing the order. Simply contact customercare@packt.com with your order details or payment transaction id. If your order has already started the shipment process, we will do our best to stop it. However, if it is already on the way to you then when you receive it, you can contact us at customercare@packt.com using the returns and refund process.

Please understand that Packt Publishing cannot provide refunds or cancel any order except for the cases described in our Return Policy (i.e. Packt Publishing agrees to replace your printed book because it arrives damaged or material defect in book), Packt Publishing will not accept returns.

What is your returns and refunds policy? Chevron down icon Chevron up icon

Return Policy:

We want you to be happy with your purchase from Packtpub.com. We will not hassle you with returning print books to us. If the print book you receive from us is incorrect, damaged, doesn't work or is unacceptably late, please contact Customer Relations Team on customercare@packt.com with the order number and issue details as explained below:

  1. If you ordered (eBook, Video or Print Book) incorrectly or accidentally, please contact Customer Relations Team on customercare@packt.com within one hour of placing the order and we will replace/refund you the item cost.
  2. Sadly, if your eBook or Video file is faulty or a fault occurs during the eBook or Video being made available to you, i.e. during download then you should contact Customer Relations Team within 14 days of purchase on customercare@packt.com who will be able to resolve this issue for you.
  3. You will have a choice of replacement or refund of the problem items.(damaged, defective or incorrect)
  4. Once Customer Care Team confirms that you will be refunded, you should receive the refund within 10 to 12 working days.
  5. If you are only requesting a refund of one book from a multiple order, then we will refund you the appropriate single item.
  6. Where the items were shipped under a free shipping offer, there will be no shipping costs to refund.

On the off chance your printed book arrives damaged, with book material defect, contact our Customer Relation Team on customercare@packt.com within 14 days of receipt of the book with appropriate evidence of damage and we will work with you to secure a replacement copy, if necessary. Please note that each printed book you order from us is individually made by Packt's professional book-printing partner which is on a print-on-demand basis.

What tax is charged? Chevron down icon Chevron up icon

Currently, no tax is charged on the purchase of any print book (subject to change based on the laws and regulations). A localized VAT fee is charged only to our European and UK customers on eBooks, Video and subscriptions that they buy. GST is charged to Indian customers for eBooks and video purchases.

What payment methods can I use? Chevron down icon Chevron up icon

You can pay with the following card types:

  1. Visa Debit
  2. Visa Credit
  3. MasterCard
  4. PayPal
What is the delivery time and cost of print books? Chevron down icon Chevron up icon

Shipping Details

USA:

'

Economy: Delivery to most addresses in the US within 10-15 business days

Premium: Trackable Delivery to most addresses in the US within 3-8 business days

UK:

Economy: Delivery to most addresses in the U.K. within 7-9 business days.
Shipments are not trackable

Premium: Trackable delivery to most addresses in the U.K. within 3-4 business days!
Add one extra business day for deliveries to Northern Ireland and Scottish Highlands and islands

EU:

Premium: Trackable delivery to most EU destinations within 4-9 business days.

Australia:

Economy: Can deliver to P. O. Boxes and private residences.
Trackable service with delivery to addresses in Australia only.
Delivery time ranges from 7-9 business days for VIC and 8-10 business days for Interstate metro
Delivery time is up to 15 business days for remote areas of WA, NT & QLD.

Premium: Delivery to addresses in Australia only
Trackable delivery to most P. O. Boxes and private residences in Australia within 4-5 days based on the distance to a destination following dispatch.

India:

Premium: Delivery to most Indian addresses within 5-6 business days

Rest of the World:

Premium: Countries in the American continent: Trackable delivery to most countries within 4-7 business days

Asia:

Premium: Delivery to most Asian addresses within 5-9 business days

Disclaimer:
All orders received before 5 PM U.K time would start printing from the next business day. So the estimated delivery times start from the next day as well. Orders received after 5 PM U.K time (in our internal systems) on a business day or anytime on the weekend will begin printing the second to next business day. For example, an order placed at 11 AM today will begin printing tomorrow, whereas an order placed at 9 PM tonight will begin printing the day after tomorrow.


Unfortunately, due to several restrictions, we are unable to ship to the following countries:

  1. Afghanistan
  2. American Samoa
  3. Belarus
  4. Brunei Darussalam
  5. Central African Republic
  6. The Democratic Republic of Congo
  7. Eritrea
  8. Guinea-bissau
  9. Iran
  10. Lebanon
  11. Libiya Arab Jamahriya
  12. Somalia
  13. Sudan
  14. Russian Federation
  15. Syrian Arab Republic
  16. Ukraine
  17. Venezuela