1Introduction to Java Development {#tutorial_java_dev_intro} 2================================ 3 4As of OpenCV 2.4.4, OpenCV supports desktop Java development using nearly the same interface as for 5Android development. This guide will help you to create your first Java (or Scala) application using 6OpenCV. 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. 8 9If you want to use Eclipse head to @ref tutorial_java_eclipse. For further reading after this guide, look at 10the @ref tutorial_android_dev_intro tutorials. 11 12What we'll do in this guide 13--------------------------- 14 15In this guide, we will: 16 17- Get OpenCV with desktop Java support 18- Create an Ant or SBT project 19- Write a simple OpenCV application in Java or Scala 20 21The same process was used to create the samples in the `samples/java` folder of the OpenCV 22repository, so consult those files if you get lost. 23 24Get proper OpenCV 25----------------- 26 27Starting from version 2.4.4 OpenCV includes desktop Java bindings. 28 29### Download 30 31The most simple way to get it is downloading the appropriate package of **version 2.4.4 or higher** 32from the [OpenCV SourceForge repository](http://sourceforge.net/projects/opencvlibrary/files/). 33 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 36sources. 37 38Another option to get OpenCV sources is to clone [OpenCV git 39repository](https://github.com/Itseez/opencv/). In order to build OpenCV with Java bindings you need 40JDK (Java Development Kit) (we recommend [Oracle/Sun JDK 6 or 417](http://www.oracle.com/technetwork/java/javase/downloads/)), [Apache Ant](http://ant.apache.org/) 42and Python v2.6 or higher to be installed. 43 44### Build 45 46Let's build OpenCV: 47@code{.bash} 48git clone git://github.com/Itseez/opencv.git 49cd opencv 50git checkout 2.4 51mkdir build 52cd build 53@endcode 54Generate a Makefile or a MS Visual Studio\* solution, or whatever you use for building executables 55in your system: 56@code{.bash} 57cmake -DBUILD_SHARED_LIBS=OFF .. 58@endcode 59or 60@code{.bat} 61cmake -DBUILD_SHARED_LIBS=OFF -G "Visual Studio 10" .. 62@endcode 63 64@note When OpenCV is built as a set of **static** libraries (-DBUILD_SHARED_LIBS=OFF option) the 65Java bindings dynamic library is all-sufficient, i.e. doesn't depend on other OpenCV libs, but 66includes all the OpenCV code inside. 67 68Examine the output of CMake and ensure java is one of the 69modules "To be built". If not, it's likely you're missing a dependency. You should troubleshoot by 70looking through the CMake output for any Java-related tools that aren't found and installing them. 71 72![](images/cmake_output.png) 73 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.: 75@code{.bash} 76export JAVA_HOME=/usr/lib/jvm/java-6-oracle 77cmake -DBUILD_SHARED_LIBS=OFF .. 78@endcode 79 80Now start the build: 81@code{.bash} 82make -j8 83@endcode 84or 85@code{.bat} 86msbuild /m OpenCV.sln /t:Build /p:Configuration=Release /v:m 87@endcode 88Besides all this will create a jar containing the Java interface (`bin/opencv-244.jar`) and a native 89dynamic 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. 91 92Java sample with Ant 93-------------------- 94 95@note The described sample is provided with OpenCV library in the `opencv/samples/java/ant` 96folder. 97 98- Create a folder where you'll develop this sample application. 99 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. 108 109- Create an `src` folder next to the `build.xml` file and a `SimpleSample.java` file in it. 110 111- Put the following Java code into the `SimpleSample.java` file: 112 @code{.java} 113 import org.opencv.core.Core; 114 import org.opencv.core.Mat; 115 import org.opencv.core.CvType; 116 import org.opencv.core.Scalar; 117 118 class SimpleSample { 119 120 static{ System.loadLibrary(Core.NATIVE_LIBRARY_NAME); } 121 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); 126 Mat mr1 = m.row(1); 127 mr1.setTo(new Scalar(1)); 128 Mat mc5 = m.col(5); 129 mc5.setTo(new Scalar(5)); 130 System.out.println("OpenCV Mat data:\n" + m.dump()); 131 } 132 133 } 134 @endcode 135- Run the following command in console in the folder containing `build.xml`: 136 @code{.bash} 137 ant -DocvJarDir=path/to/dir/containing/opencv-244.jar -DocvLibDir=path/to/dir/containing/opencv_java244/native/library 138 @endcode 139 For example: 140 @code{.bat} 141 ant -DocvJarDir=X:\opencv-2.4.4\bin -DocvLibDir=X:\opencv-2.4.4\bin\Release 142 @endcode 143 The command should initiate [re]building and running the sample. You should see on the 144 screen something like this: 145 146 ![](images/ant_output.png) 147 148SBT project for Java and Scala 149------------------------------ 150 151Now we'll create a simple Java application using SBT. This serves as a brief introduction to those 152unfamiliar with this build tool. We're using SBT because it is particularly easy and powerful. 153 154First, download and install [SBT](http://www.scala-sbt.org/) using the instructions on its [web 155site](http://www.scala-sbt.org/). 156 157Next, navigate to a new directory where you'd like the application source to live (outside `opencv` 158dir). Let's call it "JavaSample" and create a directory for it: 159@code{.bash} 160cd <somewhere outside opencv> 161mkdir JavaSample 162@endcode 163Now we will create the necessary folders and an SBT project: 164@code{.bash} 165cd JavaSample 166mkdir -p src/main/java # This is where SBT expects to find Java sources 167mkdir project # This is where the build definitions live 168@endcode 169Now open `project/build.scala` in your favorite editor and paste the following. It defines your 170project: 171@code{.scala} 172import sbt._ 173import Keys._ 174 175object JavaSampleBuild extends Build { 176 def scalaSettings = Seq( 177 scalaVersion := "2.10.0", 178 scalacOptions ++= Seq( 179 "-optimize", 180 "-unchecked", 181 "-deprecation" 182 ) 183 ) 184 185 def buildSettings = 186 Project.defaultSettings ++ 187 scalaSettings 188 189 lazy val root = { 190 val settings = buildSettings ++ Seq(name := "JavaSample") 191 Project(id = "JavaSample", base = file("."), settings = settings) 192 } 193} 194@endcode 195Now edit `project/plugins.sbt` and paste the following. This will enable auto-generation of an 196Eclipse project: 197@code{.scala} 198addSbtPlugin("com.typesafe.sbteclipse" % "sbteclipse-plugin" % "2.1.0") 199@endcode 200Now run sbt from the `JavaSample` root and from within SBT run eclipse to generate an eclipse 201project: 202@code{.bash} 203sbt # Starts the sbt console 204eclipse # Running "eclipse" from within the sbt console 205@endcode 206You should see something like this: 207 208![](images/sbt_eclipse.png) 209 210You can now import the SBT project to Eclipse using Import ... -\> Existing projects into workspace. 211Whether you actually do this is optional for the guide; we'll be using SBT to build the project, so 212if you choose to use Eclipse it will just serve as a text editor. 213 214To test that everything is working, create a simple "Hello OpenCV" application. Do this by creating 215a file `src/main/java/HelloOpenCV.java` with the following contents: 216@code{.java} 217public class HelloOpenCV { 218 public static void main(String[] args) { 219 System.out.println("Hello, OpenCV"); 220 } 221@endcode 222} 223 224Now execute run from the sbt console, or more concisely, run sbt run from the command line: 225@code{.bash} 226sbt run 227@endcode 228You should see something like this: 229 230![](images/sbt_run.png) 231 232### Running SBT samples 233 234Now we'll create a simple face detection application using OpenCV. 235 236First, create a `lib/` folder and copy the OpenCV jar into it. By default, SBT adds jars in the lib 237folder to the Java library search path. You can optionally rerun sbt eclipse to update your Eclipse 238project. 239@code{.bash} 240mkdir lib 241cp <opencv_dir>/build/bin/opencv_<version>.jar lib/ 242sbt eclipse 243@endcode 244Next, create the directory `src/main/resources` and download this Lena image into it: 245 246![](images/lena.png) 247 248Make sure it's called `"lena.png"`. Items in the resources directory are available to the Java 249application at runtime. 250 251Next, copy `lbpcascade_frontalface.xml` from `opencv/data/lbpcascades/` into the `resources` 252directory: 253@code{.bash} 254cp <opencv_dir>/data/lbpcascades/lbpcascade_frontalface.xml src/main/resources/ 255@endcode 256Now modify src/main/java/HelloOpenCV.java so it contains the following Java code: 257@code{.java} 258import org.opencv.core.Core; 259import org.opencv.core.Mat; 260import org.opencv.core.MatOfRect; 261import org.opencv.core.Point; 262import org.opencv.core.Rect; 263import org.opencv.core.Scalar; 264import org.opencv.imgcodecs.Imgcodecs; 265import org.opencv.objdetect.CascadeClassifier; 266 267// 268// Detects faces in an image, draws boxes around them, and writes the results 269// to "faceDetection.png". 270// 271class DetectFaceDemo { 272 public void run() { 273 System.out.println("\nRunning DetectFaceDemo"); 274 275 // Create a face detector from the cascade file in the resources 276 // directory. 277 CascadeClassifier faceDetector = new CascadeClassifier(getClass().getResource("/lbpcascade_frontalface.xml").getPath()); 278 Mat image = Imgcodecs.imread(getClass().getResource("/lena.png").getPath()); 279 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); 284 285 System.out.println(String.format("Detected %s faces", faceDetections.toArray().length)); 286 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)); 290 } 291 292 // Save the visualized detection. 293 String filename = "faceDetection.png"; 294 System.out.println(String.format("Writing %s", filename)); 295 Imgcodecs.imwrite(filename, image); 296 } 297} 298 299public class HelloOpenCV { 300 public static void main(String[] args) { 301 System.out.println("Hello, OpenCV"); 302 303 // Load the native library. 304 System.loadLibrary(Core.NATIVE_LIBRARY_NAME); 305 new DetectFaceDemo().run(); 306 } 307} 308@endcode 309Note the call to System.loadLibrary(Core.NATIVE_LIBRARY_NAME). This command must be executed 310exactly once per Java process prior to using any native OpenCV methods. If you don't call it, you 311will get UnsatisfiedLink errors. You will also get errors if you try to load OpenCV when it has 312already been loaded. 313 314Now run the face detection app using \`sbt run\`: 315@code{.bash} 316sbt run 317@endcode 318You should see something like this: 319 320![](images/sbt_run_face.png) 321 322It should also write the following image to `faceDetection.png`: 323 324![](images/faceDetection.png) 325 326You're done! Now you have a sample Java application working with OpenCV, so you can start the work 327on your own. We wish you good luck and many years of joyful life! 328