1 Introduction to Java Development {#tutorial_java_dev_intro}
2 ================================
4 As of OpenCV 2.4.4, OpenCV supports desktop Java development using nearly the same interface as for
5 Android development. This guide will help you to create your first Java (or Scala) application using
6 OpenCV. We will use either [Apache Ant](http://ant.apache.org/) or [Simple Build Tool
7 (SBT)](http://www.scala-sbt.org/) to build the application.
9 If you want to use Eclipse head to @ref tutorial_java_eclipse. For further reading after this guide, look at
10 the @ref tutorial_android_dev_intro tutorials.
12 What we'll do in this guide
13 ---------------------------
15 In this guide, we will:
17 - Get OpenCV with desktop Java support
18 - Create an Ant or SBT project
19 - Write a simple OpenCV application in Java or Scala
21 The same process was used to create the samples in the `samples/java` folder of the OpenCV
22 repository, so consult those files if you get lost.
27 Starting from version 2.4.4 OpenCV includes desktop Java bindings.
31 The most simple way to get it is downloading the appropriate package of **version 2.4.4 or higher**
32 from the [OpenCV SourceForge repository](http://sourceforge.net/projects/opencvlibrary/files/).
34 @note Windows users can find the prebuilt files needed for Java development in the
35 `opencv/build/java/` folder inside the package. For other OSes it's required to build OpenCV from
38 Another option to get OpenCV sources is to clone [OpenCV git
39 repository](https://github.com/opencv/opencv/). In order to build OpenCV with Java bindings you need
40 JDK (Java Development Kit) (we recommend [Oracle/Sun JDK 6 or
41 7](http://www.oracle.com/technetwork/java/javase/downloads/)), [Apache Ant](http://ant.apache.org/)
42 and Python v2.6 or higher to be installed.
48 git clone git://github.com/opencv/opencv.git
54 Generate a Makefile or a MS Visual Studio\* solution, or whatever you use for building executables
57 cmake -DBUILD_SHARED_LIBS=OFF ..
61 cmake -DBUILD_SHARED_LIBS=OFF -G "Visual Studio 10" ..
64 @note When OpenCV is built as a set of **static** libraries (-DBUILD_SHARED_LIBS=OFF option) the
65 Java bindings dynamic library is all-sufficient, i.e. doesn't depend on other OpenCV libs, but
66 includes all the OpenCV code inside.
68 Examine the output of CMake and ensure java is one of the
69 modules "To be built". If not, it's likely you're missing a dependency. You should troubleshoot by
70 looking through the CMake output for any Java-related tools that aren't found and installing them.
72 ![](images/cmake_output.png)
74 @note If CMake can't find Java in your system set the JAVA_HOME environment variable with the path to installed JDK before running it. E.g.:
76 export JAVA_HOME=/usr/lib/jvm/java-6-oracle
77 cmake -DBUILD_SHARED_LIBS=OFF ..
86 msbuild /m OpenCV.sln /t:Build /p:Configuration=Release /v:m
88 Besides all this will create a jar containing the Java interface (`bin/opencv-244.jar`) and a native
89 dynamic library containing Java bindings and all the OpenCV stuff (`lib/libopencv_java244.so` or
90 `bin/Release/opencv_java244.dll` respectively). We'll use these files later.
95 @note The described sample is provided with OpenCV library in the `opencv/samples/java/ant`
98 - Create a folder where you'll develop this sample application.
100 - In this folder create the `build.xml` file with the following content using any text editor:
101 @include samples/java/ant/build.xml
102 @note This XML file can be reused for building other Java applications. It describes a common folder structure in the lines 3 - 12 and common targets for compiling and running the application.
103 When reusing this XML don't forget to modify the project name in the line 1, that is also the
104 name of the main class (line 14). The paths to OpenCV jar and jni lib are expected as parameters
105 ("${ocvJarDir}" in line 5 and "${ocvLibDir}" in line 37), but you can hardcode these paths for
106 your convenience. See [Ant documentation](http://ant.apache.org/manual/) for detailed
107 description of its build file format.
109 - Create an `src` folder next to the `build.xml` file and a `SimpleSample.java` file in it.
111 - Put the following Java code into the `SimpleSample.java` file:
113 import org.opencv.core.Core;
114 import org.opencv.core.Mat;
115 import org.opencv.core.CvType;
116 import org.opencv.core.Scalar;
120 static{ System.loadLibrary(Core.NATIVE_LIBRARY_NAME); }
122 public static void main(String[] args) {
123 System.out.println("Welcome to OpenCV " + Core.VERSION);
124 Mat m = new Mat(5, 10, CvType.CV_8UC1, new Scalar(0));
125 System.out.println("OpenCV Mat: " + m);
127 mr1.setTo(new Scalar(1));
129 mc5.setTo(new Scalar(5));
130 System.out.println("OpenCV Mat data:\n" + m.dump());
135 - Run the following command in console in the folder containing `build.xml`:
137 ant -DocvJarDir=path/to/dir/containing/opencv-244.jar -DocvLibDir=path/to/dir/containing/opencv_java244/native/library
141 ant -DocvJarDir=X:\opencv-2.4.4\bin -DocvLibDir=X:\opencv-2.4.4\bin\Release
143 The command should initiate [re]building and running the sample. You should see on the
144 screen something like this:
146 ![](images/ant_output.png)
148 SBT project for Java and Scala
149 ------------------------------
151 Now we'll create a simple Java application using SBT. This serves as a brief introduction to those
152 unfamiliar with this build tool. We're using SBT because it is particularly easy and powerful.
154 First, download and install [SBT](http://www.scala-sbt.org/) using the instructions on its [web
155 site](http://www.scala-sbt.org/).
157 Next, navigate to a new directory where you'd like the application source to live (outside `opencv`
158 dir). Let's call it "JavaSample" and create a directory for it:
160 cd <somewhere outside opencv>
163 Now we will create the necessary folders and an SBT project:
166 mkdir -p src/main/java # This is where SBT expects to find Java sources
167 mkdir project # This is where the build definitions live
169 Now open `project/build.scala` in your favorite editor and paste the following. It defines your
175 object JavaSampleBuild extends Build {
176 def scalaSettings = Seq(
177 scalaVersion := "2.10.0",
178 scalacOptions ++= Seq(
186 Project.defaultSettings ++
190 val settings = buildSettings ++ Seq(name := "JavaSample")
191 Project(id = "JavaSample", base = file("."), settings = settings)
195 Now edit `project/plugins.sbt` and paste the following. This will enable auto-generation of an
198 addSbtPlugin("com.typesafe.sbteclipse" % "sbteclipse-plugin" % "2.1.0")
200 Now run sbt from the `JavaSample` root and from within SBT run eclipse to generate an eclipse
203 sbt # Starts the sbt console
204 eclipse # Running "eclipse" from within the sbt console
206 You should see something like this:
208 ![](images/sbt_eclipse.png)
210 You can now import the SBT project to Eclipse using Import ... -\> Existing projects into workspace.
211 Whether you actually do this is optional for the guide; we'll be using SBT to build the project, so
212 if you choose to use Eclipse it will just serve as a text editor.
214 To test that everything is working, create a simple "Hello OpenCV" application. Do this by creating
215 a file `src/main/java/HelloOpenCV.java` with the following contents:
217 public class HelloOpenCV {
218 public static void main(String[] args) {
219 System.out.println("Hello, OpenCV");
224 Now execute run from the sbt console, or more concisely, run sbt run from the command line:
228 You should see something like this:
230 ![](images/sbt_run.png)
232 ### Running SBT samples
234 Now we'll create a simple face detection application using OpenCV.
236 First, create a `lib/` folder and copy the OpenCV jar into it. By default, SBT adds jars in the lib
237 folder to the Java library search path. You can optionally rerun sbt eclipse to update your Eclipse
241 cp <opencv_dir>/build/bin/opencv_<version>.jar lib/
244 Next, create the directory `src/main/resources` and download this Lena image into it:
248 Make sure it's called `"lena.png"`. Items in the resources directory are available to the Java
249 application at runtime.
251 Next, copy `lbpcascade_frontalface.xml` from `opencv/data/lbpcascades/` into the `resources`
254 cp <opencv_dir>/data/lbpcascades/lbpcascade_frontalface.xml src/main/resources/
256 Now modify src/main/java/HelloOpenCV.java so it contains the following Java code:
258 import org.opencv.core.Core;
259 import org.opencv.core.Mat;
260 import org.opencv.core.MatOfRect;
261 import org.opencv.core.Point;
262 import org.opencv.core.Rect;
263 import org.opencv.core.Scalar;
264 import org.opencv.imgcodecs.Imgcodecs;
265 import org.opencv.objdetect.CascadeClassifier;
268 // Detects faces in an image, draws boxes around them, and writes the results
269 // to "faceDetection.png".
271 class DetectFaceDemo {
273 System.out.println("\nRunning DetectFaceDemo");
275 // Create a face detector from the cascade file in the resources
277 CascadeClassifier faceDetector = new CascadeClassifier(getClass().getResource("/lbpcascade_frontalface.xml").getPath());
278 Mat image = Imgcodecs.imread(getClass().getResource("/lena.png").getPath());
280 // Detect faces in the image.
281 // MatOfRect is a special container class for Rect.
282 MatOfRect faceDetections = new MatOfRect();
283 faceDetector.detectMultiScale(image, faceDetections);
285 System.out.println(String.format("Detected %s faces", faceDetections.toArray().length));
287 // Draw a bounding box around each face.
288 for (Rect rect : faceDetections.toArray()) {
289 Imgproc.rectangle(image, new Point(rect.x, rect.y), new Point(rect.x + rect.width, rect.y + rect.height), new Scalar(0, 255, 0));
292 // Save the visualized detection.
293 String filename = "faceDetection.png";
294 System.out.println(String.format("Writing %s", filename));
295 Imgcodecs.imwrite(filename, image);
299 public class HelloOpenCV {
300 public static void main(String[] args) {
301 System.out.println("Hello, OpenCV");
303 // Load the native library.
304 System.loadLibrary(Core.NATIVE_LIBRARY_NAME);
305 new DetectFaceDemo().run();
309 Note the call to System.loadLibrary(Core.NATIVE_LIBRARY_NAME). This command must be executed
310 exactly once per Java process prior to using any native OpenCV methods. If you don't call it, you
311 will get UnsatisfiedLink errors. You will also get errors if you try to load OpenCV when it has
314 Now run the face detection app using \`sbt run\`:
318 You should see something like this:
320 ![](images/sbt_run_face.png)
322 It should also write the following image to `faceDetection.png`:
324 ![](images/faceDetection.png)
326 You're done! Now you have a sample Java application working with OpenCV, so you can start the work
327 on your own. We wish you good luck and many years of joyful life!