1 Introduction to Java Development {#tutorial_java_dev_intro} 2 ================================ 3 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. 8 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. 11 12 What we'll do in this guide 13 --------------------------- 14 15 In 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 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. 23 24 Get proper OpenCV 25 ----------------- 26 27 Starting from version 2.4.4 OpenCV includes desktop Java bindings. 28 29 ### Download 30 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/). 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 36 sources. 37 38 Another option to get OpenCV sources is to clone [OpenCV git 39 repository](https://github.com/Itseez/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. 43 44 ### Build 45 46 Let's build OpenCV: 47 @code{.bash} 48 git clone git://github.com/Itseez/opencv.git 49 cd opencv 50 git checkout 2.4 51 mkdir build 52 cd build 53 @endcode 54 Generate a Makefile or a MS Visual Studio\* solution, or whatever you use for building executables 55 in your system: 56 @code{.bash} 57 cmake -DBUILD_SHARED_LIBS=OFF .. 58 @endcode 59 or 60 @code{.bat} 61 cmake -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 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. 67 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. 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} 76 export JAVA_HOME=/usr/lib/jvm/java-6-oracle 77 cmake -DBUILD_SHARED_LIBS=OFF .. 78 @endcode 79 80 Now start the build: 81 @code{.bash} 82 make -j8 83 @endcode 84 or 85 @code{.bat} 86 msbuild /m OpenCV.sln /t:Build /p:Configuration=Release /v:m 87 @endcode 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. 91 92 Java sample with Ant 93 -------------------- 94 95 @note The described sample is provided with OpenCV library in the `opencv/samples/java/ant` 96 folder. 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 148 SBT project for Java and Scala 149 ------------------------------ 150 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. 153 154 First, download and install [SBT](http://www.scala-sbt.org/) using the instructions on its [web 155 site](http://www.scala-sbt.org/). 156 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: 159 @code{.bash} 160 cd <somewhere outside opencv> 161 mkdir JavaSample 162 @endcode 163 Now we will create the necessary folders and an SBT project: 164 @code{.bash} 165 cd JavaSample 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 168 @endcode 169 Now open `project/build.scala` in your favorite editor and paste the following. It defines your 170 project: 171 @code{.scala} 172 import sbt._ 173 import Keys._ 174 175 object 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 195 Now edit `project/plugins.sbt` and paste the following. This will enable auto-generation of an 196 Eclipse project: 197 @code{.scala} 198 addSbtPlugin("com.typesafe.sbteclipse" % "sbteclipse-plugin" % "2.1.0") 199 @endcode 200 Now run sbt from the `JavaSample` root and from within SBT run eclipse to generate an eclipse 201 project: 202 @code{.bash} 203 sbt # Starts the sbt console 204 eclipse # Running "eclipse" from within the sbt console 205 @endcode 206 You should see something like this: 207 208 ![](images/sbt_eclipse.png) 209 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. 213 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: 216 @code{.java} 217 public class HelloOpenCV { 218 public static void main(String[] args) { 219 System.out.println("Hello, OpenCV"); 220 } 221 @endcode 222 } 223 224 Now execute run from the sbt console, or more concisely, run sbt run from the command line: 225 @code{.bash} 226 sbt run 227 @endcode 228 You should see something like this: 229 230 ![](images/sbt_run.png) 231 232 ### Running SBT samples 233 234 Now we'll create a simple face detection application using OpenCV. 235 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 238 project. 239 @code{.bash} 240 mkdir lib 241 cp <opencv_dir>/build/bin/opencv_<version>.jar lib/ 242 sbt eclipse 243 @endcode 244 Next, create the directory `src/main/resources` and download this Lena image into it: 245 246 ![](images/lena.png) 247 248 Make sure it's called `"lena.png"`. Items in the resources directory are available to the Java 249 application at runtime. 250 251 Next, copy `lbpcascade_frontalface.xml` from `opencv/data/lbpcascades/` into the `resources` 252 directory: 253 @code{.bash} 254 cp <opencv_dir>/data/lbpcascades/lbpcascade_frontalface.xml src/main/resources/ 255 @endcode 256 Now modify src/main/java/HelloOpenCV.java so it contains the following Java code: 257 @code{.java} 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; 266 267 // 268 // Detects faces in an image, draws boxes around them, and writes the results 269 // to "faceDetection.png". 270 // 271 class 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 299 public 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 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 312 already been loaded. 313 314 Now run the face detection app using \`sbt run\`: 315 @code{.bash} 316 sbt run 317 @endcode 318 You should see something like this: 319 320 ![](images/sbt_run_face.png) 321 322 It should also write the following image to `faceDetection.png`: 323 324 ![](images/faceDetection.png) 325 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! 328