OpenCV Java Tutorials

how to attach opencv java with netbeans and opencv 3 java face recognition and how to use opencv with java and opencv java access mat elements
OliviaCutts Profile Pic
OliviaCutts,France,Teacher
Published Date:01-08-2017
Your Website URL(Optional)
Comment
OpenCV Java Tutorials Documentation Release1.0 Luigi De Russis, Alberto Sacco Jul 11, 2017CHAPTER1 InstallingOpenCVforJava Introduction to OpenCV for Java As of OpenCV 2.4.4, OpenCV supports desktop Java development. This tutorial will help you install OpenCV on your desktop operating system. Install the latest Java version Download the latest Java JDK from the Oracle website. Now you should be able to install the last Java JDK by open the file just downloaded. Install the latest Eclipse version Download the latest Eclipse version at the Eclipse Download page choosing the Eclipse IDE for Java Developers version (suggested). Extract the downloaded compressed file and put the resulting folder wherever you want to. You don’t need to install anything. Alternatively, you can try the Eclipse installer. Install OpenCV 3.x under Windows First of all you should download the OpenCV library (version 3.x) from here. Then, extract the downloaded OpenCV file in a location of your choice. Once you get the folder opencv put in wherever you prefer. Now the only two things that you will need are: the opencv-3xx.jar file located at \opencv\build\java and the opencv_java3xx.dll library located at \opencv\build\java\x64 (for 64-bit systems) or \opencv\build\java\x86 (for 32-bit systems). The 3xx suffix of each file is a shortcut for the current OpenCV version, e.g., it will be 300 for OpenCV 3.0 and 310 for OpenCV 3.1. 3OpenCV Java Tutorials Documentation, Release 1.0 Install OpenCV 3.x under macOS The quickest way to obtain OpenCV under macOS is to use Homebrew. After installing Homebrew, you have to check whether the XCode Command Line Tools are already installed on your system. To do so, open the Terminal and execute: xcode-select install If macOS asks for installing such tools, proceed with the download and installation. Otherwise, continue with the OpenCV installation. To install OpenCV (with Java support) through Homebrew, you need to add the science tap to Home- brew: brew tap homebrew/science and effectively install OpenCV:brew install opencv3 HEAD with-contrib with-java After the installation of OpenCV, the needed jar file and the dylib library will be located at /usr/local/opt/ opencv3/share/OpenCV/java/. Install OpenCV 3.x under Linux Please, note: the following instructions are also useful if you want to compile OpenCV under Windows or macOS. Linux package management systems (apt-get, yum, etc.) may provide the needed version of the OpenCV library. As first step, download and install CMake and Apache Ant, if you don’t have any of these. Download the OpenCV library from the its website. Extract the downloaded OpenCV file in a location of your choice and open CMake ( cmake-gui ). Put the location of the extracted OpenCV library in the Where is the source code field (e.g., /opencv/) and insert the destination directory of your build in theWhere to build the binaries field (e.g., /opencv/build). At last, check theGrouped andAdvanced checkboxes. 4 Chapter 1. Installing OpenCV for JavaOpenCV Java Tutorials Documentation, Release 1.0 Now press Configure and use the default compilers for Unix Makefiles. Please, be sure to have installed a C/C++ compiler. In the Ungrouped Entries group, insert the path to the Apache Ant executable (e.g., / apache-ant-1.9.6/bin/ant). In theBUILD group, unselect: • BUILD_PERF_TESTS • BUILD_SHARED_LIBRARY to make the Java bindings dynamic library all-sufficient • BUILD_TESTS • BUILD_opencv_python In theCMAKE group, set toDebug (orRelease) theCMAKE_BUILD_TYPE In theJAVA group: • insert the Java AWT include path (e.g.,`/usr/lib/jvm/java-1.8.0/include/) • insert the Java AWT library path (e.g.,/usr/lib/jvm/java-1.8.0/include/jawt.h) • insert the Java include path (e.g.,/usr/lib/jvm/java-1.8.0/include/) 1.6. Install OpenCV 3.x under Linux 5OpenCV Java Tutorials Documentation, Release 1.0 • insert the alternative Java include path (e.g.,/usr/lib/jvm/java-1.8.0/include/linux) • insert the JVM library path (e.g.,/usr/lib/jvm/java-1.8.0/include/jni.h) PressConfigure twice, and the CMake window should appear with a white background. Now, pressGenerate and close CMake. Now open the terminal, go to the build folder of OpenCV and compile everything with the command: make -j. Notice that the -j flag tells make to run in parallel with the maximum number of allowed job threads, which makes the build theoretically faster. Wait for the process to be completed... If everything went well you should have opencv-3xx.jar in the/opencv/build/bin directory andlibopencv_java3xx.so in the/opencv/ build/lib directory. The 3xx suffix of each file is a shortcut for the current OpenCV version, e.g., it will be 300 for OpenCV 3.0 and 310 for OpenCV 3.1. This is everything you need. 6 Chapter 1. Installing OpenCV for JavaOpenCV Java Tutorials Documentation, Release 1.0 Set up OpenCV for Java in Eclipse Open Eclipse and select a workspace of your choice. Create a User Library, ready to be used on all your next projects: go toWindow Preferences.... From the menu navigate under Java Build Path User Libraries and choose New.... Enter a name for the library (e.g., opencv) and select the newly created user library. Choose Add External JARs..., browse to selectopencv-3xx.jar from your computer. After adding the jar, extend it, selectNative library location and pressEdit.... 1.7. Set up OpenCV for Java in Eclipse 7OpenCV Java Tutorials Documentation, Release 1.0 Select External Folder... and browse to select the folder containing the OpenCV libraries (e.g., C:\opencv\build\java\x64 under Windows). In case of MacOS, if you installed OpenCV without Homebrew, you need to create a soft link with .dylib extension for the .so file. E.g., from the terminal, type: ln -s libopencv_java300.so libopencv_java300.dylib Set up OpenCV for Java in other IDEs (experimental) If you are using IntelliJ, you can specify the location of the library with the VM argument -Djava.library. path=/opencv/build/lib. 8 Chapter 1. Installing OpenCV for JavaCHAPTER2 YourFirstJavaApplicationwithOpenCV Note: We assume that by now you have already read the previous tutorials. If not, please check previous tutorials at http://opencv-java-tutorials.readthedocs.org/en/latest/index.html. You can also find the source code and resources at https://github.com/opencv-java/ A Java application with OpenCV This tutorial will guide you through the creation of a simple Java console application using the OpenCV library in Eclipse. What we will do in this tutorial In this guide, we will: • Create a new Java Project • Add a User Library to the project • Write some OpenCV code • Build and Run the application Create a New Project Open Eclipse and create a new Java project; open theFile menu, go toNew and click onJava Project. 9OpenCV Java Tutorials Documentation, Release 1.0 In theNew Java Project dialog write the name of your project and click onFinish. Add a User Library If you followed the previous tutorial (Installing OpenCV for Java), you should already have the OpenCV library set in your workspace’s user libraries; if not please check out the previous tutorial. Now you should be ready to add the library to your project. Inside Eclipse’sPackage Explorer just right-click on your project’s folder and go toBuild Path Add Libraries.... SelectUser Libraries and click onNext, check the checkbox of the OpenCV library and clickFinish. 10 Chapter 2. Your First Java Application with OpenCVOpenCV Java Tutorials Documentation, Release 1.0 Create a simple application Now add a new Class to your project by right-clicking on your project’s folder and go toNew Class. Write a name of your choice for both the package and the class then click onFinish. Now we are ready to write the code of our first application. Let’s start by defining themain method: public class HelloCV public static void main(String args) System.loadLibrary(Core.NATIVE_LIBRARY_NAME); Mat mat = Mat.eye(3, 3, CvType.CV_8UC1); System.out.println("mat = " + mat.dump()); First of all we need to load the OpenCV Native Library previously set on our project. System.loadLibrary(Core.NATIVE_LIBRARY_NAME); Then we can define a new Mat. Note: The class Mat represents an n-dimensional dense numerical single-channel or multi-channel array. It can be used to store real or complex-valued vectors and matrices, grayscale or color images, voxel volumes, vector fields, point clouds, tensors, histograms. For more details check out the OpenCV page. Mat mat = Mat.eye(3, 3, CvType.CV_8UC1); TheMat.eye represents a identity matrix, we set the dimensions of it (3x3) and the type of its elements. As you can notice, if you leave the code just like this, you will get some error; this is due to the fact that eclipse can’t resolve some variables. You can locate your mouse cursor on the words that seem to be errors and wait for a dialog to pop up and click on the voiceImport.... If you do that for all the variables we have added to the code the following rows: import org.opencv.core.Core; import org.opencv.core.CvType; import org.opencv.core.Mat; We can now try to build and run our application by clicking on the Run button. You should have the following output: 2.5. Create a simple application 11OpenCV Java Tutorials Documentation, Release 1.0 The whole source code is available on GitHub. 12 Chapter 2. Your First Java Application with OpenCVCHAPTER3 YourFirstJavaFXApplicationwithOpenCV Note: We assume that by now you have already read the previous tutorials. If not, please check previous tutorials at http://opencv-java-tutorials.readthedocs.org/en/latest/index.html. You can also find the source code and resources at https://github.com/opencv-java/ A JavaFX application with OpenCV This tutorial will guide you through the creation of a simple JavaFX GUI application using the OpenCV library in Eclipse. What we will do in this tutorial In this guide, we will: • Install thee(fx)clipse plugin and (optionally) Scene Builder. • Work with Scene Builder. • Write and Run our application. Your First Application in JavaFX The application you will write by following this tutorial is going to capture a video stream from a webcam and, then, it will display it on the user interface (GUI). We will create the GUI with Scene Builder: it is will have a button, which will allow us to start and stop the stream, and a simple image view container where we will put each stream frame. 13OpenCV Java Tutorials Documentation, Release 1.0 Installing e(fx)clipse plugin and Scene Builder In Eclipse, install the e(fx)clipse plugin, by following the guide at http://www.eclipse.org/efxclipse/install. htmlfortheambitious. If you choose not to install such a plugin, you have to create a traditional Java project, only. Download and install JavaFX Scene Builder 2.0 from http://www.oracle.com/technetwork/java/ javafxscenebuilder-1x-archive-2199384.html. Now you can create a new JavaFX project. Go to File New Project... and select JavaFX project.... Choose a name for your project and clickNext. 14 Chapter 3. Your First JavaFX Application with OpenCVOpenCV Java Tutorials Documentation, Release 1.0 Now add your OpenCV user library to your project and clickNext. 3.4. Installing e(fx)clipse plugin and Scene Builder 15OpenCV Java Tutorials Documentation, Release 1.0 Choose a name for your package, for the FXML file and for the Controller Class. The FXML file will contain the description of your GUI in FXML language, while the Controller Class will handle all the method and event which have to be called and managed when the user interacts with the GUI’s components. Working with Scene Builder If you have installed Scene Builder you can now right click on your FXML file in Eclipse and select Open with SceneBuilder. Scene Builder can help construct you gui by interacting with a graphic interface; this allows you to see a real time preview of your window and modify your components and their position just by editing the graphic preview. Let’s take a look at what I’m talking about. At fist the FXML file will have just an AnchorPane. An AnchorPane allows the edges of child nodes to be anchored to an offset from the anchorpane’s edges. If the anchorpane has a border and/or padding set, the offsets will be measured from the inside edge of those insets. The anchorpane lays out each managed child regardless of the child’s visible property value; unmanaged children are ignored for all layout calculations. You can go ahead and delete the anchorpane and add a BorderPane instead. A BorderPane lays out children in top, left, right, bottom, and center positions. 16 Chapter 3. Your First JavaFX Application with OpenCVOpenCV Java Tutorials Documentation, Release 1.0 You can add a BorderPane by dragging from theContainer menu a borderpane and then drop it in theHierarchy menu. Now we can add the button that will allow us to start and stop the stream. Take a button component from the Controls menu and drop it on the BOTTOM field of our BP. As we can see, on the right we will get three menus (Properties, Layout, Code) which are used to customize our selected component. For example we can change text of our button in “Start Camera” in theText field under theProperties menu and the id of the button (e.g. “start_btn”) in thefx:id field under theCode menu. 3.5. Working with Scene Builder 17OpenCV Java Tutorials Documentation, Release 1.0 We are going to need the id of the button later, in order to edit the button properties from our Controller‘s methods. As you can see our button is too close to the edge of the windows, so we should add some bottom margin to it; to do so we can add this information in theLayout menu. In order to make the button work, we have to set the name of the method (e.g. “startCamera”) that will execute the action we want to preform in the fieldOnAction under theCode menu. 18 Chapter 3. Your First JavaFX Application with OpenCVOpenCV Java Tutorials Documentation, Release 1.0 Now, we shall add an ImageView component from theControls menu into the CENTER field of our BP. Let’s also edit the id of the image view (e.g. “currentFrame”), and add some margin to it. Finally we have to tell which Controller class will mange the GUI, we can do so by adding our controller class name in theController class field under theController menu located in the bottom left corner of the window. We just created our first GUI by using Scene Builder, if you save the file and return to Eclipse you will notice that some FXML code has been generated automatically. 3.5. Working with Scene Builder 19OpenCV Java Tutorials Documentation, Release 1.0 Key Concepts in JavaFX The Stage is where the application will be displayed (e.g., a Windows’ window). A Scene is one container of Nodes that compose one “page” of your application. A Node is an element in the Scene, with a visual appearance and an interactive behavior. Nodes may be hierarchically nested . In the Main class we have to pass to the start function our primary stage: public void start(Stage primaryStage) and load the fxml file that will populate our stage, the root element of the scene and the controller class: FXMLLoader loader = new FXMLLoader(getClass().getResource("FXHelloCV.fxml")); BorderPane root = (BorderPane) loader.load(); FXController controller = loader.getController(); Managing GUI Interactions With the Controller Class For our application we need to do basically two thing: control the button push and the refreshment of the image view. To do so we have to create a reference between the gui components and a variable used in our controller class: FXML private Button button; FXML private ImageView currentFrame; TheFXML tag means that we are linking our variable to an element of the fxml file and the value used to declare the variable has to equal to the id set for that specific element. TheFXML tag is used with the same meaning for the Actions set under the Code menu in a specific element. for: Button fx:id="button" mnemonicParsing="false" onAction="startCamera" text="Start ˓→Camera" BorderPane.alignment="CENTER" we set: FXML protected void startCamera(ActionEvent event) ... Video Capturing Essentially, all the functionalities required for video manipulation is integrated in the VideoCapture class. private VideoCapture capture = new VideoCapture(); This on itself builds on the FFmpeg open source library. A video is composed of a succession of images, we re- fer to these in the literature as frames. In case of a video file there is a frame rate specifying just how long is between two frames. While for the video cameras usually there is a limit of just how many frames they can dig- italize per second. In our case we set as frame rate 30 frames per sec. To do so we initialize a timer (i.e., a `ScheduledExecutorService`) that will open a background task every 33 milliseconds. 20 Chapter 3. Your First JavaFX Application with OpenCVOpenCV Java Tutorials Documentation, Release 1.0 Runnable frameGrabber = new Runnable() ... this.timer = Executors.newSingleThreadScheduledExecutor(); this.timer.scheduleAtFixedRate(frameGrabber, 0, 33, TimeUnit. ˓→MILLISECONDS); To check if the binding of the class to a video source was successful or not use theisOpened function: if (this.capture.isOpened()) ... Closing the video is automatic when the objects destructor is called. However, if you want to close it before this you need to call its release function. this.capture.release(); The frames of the video are just simple images. Therefore, we just need to extract them from the VideoCapture object and put them inside a Mat one. Mat frame = new Mat(); The video streams are sequential. You may get the frames one after another by the read or the overloaded operator. this.capture.read(frame); Now we are going to convert our image from BGR to Grayscale format. OpenCV has a really nice function to do this kind of transformations: Imgproc.cvtColor(frame, frame, Imgproc.COLOR_BGR2GRAY); As you can see, cvtColor takes as arguments: • a source image (frame) • a destination image (frame), in which we will save the converted image. • an additional parameter that indicates what kind of transformation will be performed. In this case we use COLOR_BGR2GRAY (because ofimread has BGR default channel order in case of color images). Now in order to put the captured frame into the ImageView we need to convert the Mat in a Image. We first create a buffer to store the Mat. MatOfByte buffer = new MatOfByte(); Then we can put the frame into the buffer by using theimencode function: Imgcodecs.imencode(".png", frame, buffer); This encodes an image into a memory buffer. The function compresses the image and stores it in the memory buffer that is resized to fit the result. Note: imencode returns single-row matrix of typeCV_8UC1 that contains encoded image as array of bytes. It takes three parameters: • (”.png”) File extension that defines the output format. • (frame) Image to be written. • (buffer) Output buffer resized to fit the compressed image. 3.8. Video Capturing 21

Advise: Why You Wasting Money in Costly SEO Tools, Use World's Best Free SEO Tool Ubersuggest.