eclipse开发opencv官方教程

Introduction to Java Development

Last updated: 12 February, 2013.

As of OpenCV 2.4.4, OpenCV supports desktop Java development using nearly the same interface as for Android development. This guide will help you to create your first Java (or Scala) application using OpenCV. We will use either EclipseApache
Ant
 or the Simple Build Tool (SBT) to build the application.

For further reading after this guide, look at the Introduction
into Android Development
 tutorials.

What we’ll do in this guide

In this guide, we will:

  • Get OpenCV with desktop Java support
  • Create an AntEclipse or SBT project
  • Write a simple OpenCV application in Java or Scala

The same process was used to create the samples in the samples/java folder of the OpenCV repository, so consult those files if you get
lost.

Get OpenCV with desktop Java support

Starting from version 2.4.4 OpenCV includes desktop Java bindings. The most simple way to get it is downloading the appropriate package of version 2.4.4 or higher from the OpenCV
SourceForge repository
.

Note

Windows users can find the prebuilt files needed for Java development in the opencv/build/java/ folder inside the package. For other
OSes it’s required to build OpenCV from sources.

Another option to get OpenCV sources is to clone OpenCV git repository. In order to build OpenCV with Java bindings
you need JDK (we recommend Oracle/Sun
JDK 6 or 7
), Apache Ant and Python v2.6 or higher to be installed.

Build OpenCV

Let’s build OpenCV:

git clone git://github.com/Itseez/opencv.git
cd opencv
git checkout 2.4
mkdir build
cd build

Generate a Makefile or a MS Visual Studio* solution, or whatever you use for building executables in your system:

cmake -DBUILD_SHARED_LIBS=OFF ..

or

cmake -DBUILD_SHARED_LIBS=OFF -G "Visual Studio 10" ..

Note

When OpenCV is built as a set of static libraries (-DBUILD_SHARED_LIBS=OFF option) the Java bindings dynamic library is
all-sufficient, i.e. doesn’t depend on other OpenCV libs, but includes all the OpenCV code inside.

Examine the output of CMake and ensure java is one of the modules “To be built”. If not, it’s likely you’re missing a dependency. You should
troubleshoot by looking through the CMake output for any Java-related tools that aren’t found and installing them.

Now start the build:

make -j8

or

msbuild /m OpenCV.sln /t:Build /p:Configuration=Release /v:m

Besides all this will create a jar containing the Java interface (bin/opencv_2.4.4.jar)
and a native dynamic library containing Java bindings and all the OpenCV stuff (bin/Release/opencv_java244.dllor bin/libopencv_java244.so respectively).
We’ll use these files later.

Create a simple Java sample and an Ant build file for it

Note

The described sample is provided with OpenCV library in the opencv/samples/java/ant folder.

  • Create a folder where you’ll develop this sample application.
  • In this folder create an XML file with the following content using any text editor:

     1
     2
     3
     4
     5
     6
     7
     8
     9
    10
    11
    12
    13
    14
    15
    16
    17
    18
    19
    20
    21
    22
    23
    24
    25
    26
    27
    28
    29
    30
    31
    32
    33
    34
    35
    36
    37
    38
    39
    40
    41
    42
    43
    44
    45
    46
    47
    48
    49

    <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 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>
    

    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.

    When reusing this XML don’t forget to modify the project name in the line 1, that is also the name of the main class (line 14). The paths to OpenCV jar and jni
    lib
     are expected as parameters ("${ocvJarDir}" in line 5 and "${ocvLibDir}" in
    line 37), but you can hardcode these paths for your convenience. See Ant documentation for detailed description of its
    build file format.

  • Create an src folder next to the build.xml file
    and a SimpleSample.java file in it.
  • Put the following Java code into the SimpleSample.java file:
    import org.opencv.core.Mat;
    import org.opencv.core.CvType;
    import org.opencv.core.Scalar;
    
    class SimpleSample {
    
      static{ System.loadLibrary("opencv_java244"); }
    
      public static void main(String[] args) {
        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());
      }
    
    }
    
  • Run the following command in console in the folder containing build.xml:
    ant -DocvJarDir=path/to/dir/containing/opencv-244.jar -DocvLibDir=path/to/dir/containing/opencv_java244/native/library
    

    For example:

    ant -DocvJarDir=X:\opencv-2.4.4\bin -DocvLibDir=X:\opencv-2.4.4\bin\Release
    

    The command should initiate [re]building and running the sample. You should see on the screen something like this:

Create a simple Java project in Eclipse

Now let’s look at the possiblity of using OpenCV in Java when developing in Eclipse IDE.

  • Create a new Eclipse workspace
  • Create a new Java project via File –> New –> Java
    Project

    Call it say “HelloCV”.

  • Open Java Build Path tab on Project
    Properties dialog

    and configure additional library (OpenCV) reference (jar and native library location):

    ` `

    ` `

    ` `

    ` `

    ` `

    ` `

    ` `

    ` `

  • Add a new Java class (say Main) containing the application
    entry:

  • Put some simple OpenCV calls there, e.g.:
    import org.opencv.core.CvType;
    import org.opencv.core.Mat;
    
    public class Main {
        public static void main(String[] args) {
            System.loadLibrary("opencv_java244");
            Mat m  = Mat.eye(3, 3, CvType.CV_8UC1);
            System.out.println("m = " + m.dump());
        }
    }
    
  • Press Run button and find the identity matrix
    content in the Eclipse Console window.

Create an SBT project and samples in Java and Scala

Now we’ll create a simple Java application using SBT. This serves as a brief introduction to those unfamiliar with this build tool. We’re using SBT because it is particularly easy and powerful.

First, download and install SBT using the instructions on its web
site
.

Next, navigate to a new directory where you’d like the application source to live (outside opencv dir). Let’s call it “JavaSample” and
create a directory for it:

cd <somewhere outside opencv>
mkdir JavaSample

Now we will create the necessary folders and an SBT project:

cd JavaSample
mkdir -p src/main/java # This is where SBT expects to find Java sources
mkdir project # This is where the build definitions live

Now open project/build.scala in your favorite editor and paste the following. It defines your project:

 import sbt._
 import Keys._

object JavaSampleBuild extends Build {
  def scalaSettings = Seq(
    scalaVersion := "2.10.0",
    scalacOptions ++= Seq(
      "-optimize",
      "-unchecked",
      "-deprecation"
    )
  )

  def buildSettings =
    Project.defaultSettings ++
    scalaSettings

  lazy val root = {
    val settings = buildSettings ++ Seq(name := "JavaSample")
    Project(id = "JavaSample", base = file("."), settings = settings)
  }
}

Now edit project/plugins.sbt and paste the following. This will enable auto-generation of an Eclipse project:

addSbtPlugin("com.typesafe.sbteclipse" % "sbteclipse-plugin" % "2.1.0")

Now run sbt from the JavaSample root
and from within SBT run eclipse to generate an eclipse project:

sbt # Starts the sbt console
> eclipse # Running "eclipse" from within the sbt console

You should see something like this:

You can now import the SBT project to Eclipse using Import ... -> Existing projects into workspace. Whether you actually
do this is optional for the guide; we’ll be using SBT to build the project, so if you choose to use Eclipse it will just serve as a text editor.

To test that everything is working, create a simple “Hello OpenCV” application. Do this by creating a file src/main/java/HelloOpenCV.java with
the following contents:

 public class HelloOpenCV {
   public static void main(String[] args) {
     System.out.println("Hello, OpenCV");
  }
}

Now execute run from the sbt console, or more concisely, run sbt run from
the command line:

sbt run

You should see something like this:

Copy the OpenCV jar and write a simple application

Now we’ll create a simple face detection application using OpenCV.

First, create a lib/ folder and copy the OpenCV jar into it. By default, SBT adds jars in the lib folder to the Java library search
path. You can optionally rerun sbt eclipse to update your Eclipse project.

mkdir lib
cp <opencv_dir>/build/bin/opencv_<version>.jar lib/
sbt eclipse

Next, create the directory src/main/resources and download this Lena image into it:

Make sure it’s called "lena.png". Items in the resources directory are available to the Java application at runtime.

Next, copy lbpcascade_frontalface.xml from opencv/data/ into
the resources directory:

cp <opencv_dir>/data/lbpcascades/lbpcascade_frontalface.xml src/main/resources/

Now modify src/main/java/HelloOpenCV.java so it contains the following Java code:

import org.opencv.core.Core;
import org.opencv.core.Mat;
import org.opencv.core.MatOfRect;
import org.opencv.core.Point;
import org.opencv.core.Rect;
import org.opencv.core.Scalar;
import org.opencv.highgui.Highgui;
import org.opencv.objdetect.CascadeClassifier;

//
// Detects faces in an image, draws boxes around them, and writes the results
// to "faceDetection.png".
//
class DetectFaceDemo {
  public void run() {
    System.out.println("\nRunning DetectFaceDemo");

    // Create a face detector from the cascade file in the resources
    // directory.
    CascadeClassifier faceDetector = new CascadeClassifier(getClass().getResource("/lbpcascade_frontalface.xml").getPath());
    Mat image = Highgui.imread(getClass().getResource("/lena.png").getPath());

    // Detect faces in the image.
    // MatOfRect is a special container class for Rect.
    MatOfRect faceDetections = new MatOfRect();
    faceDetector.detectMultiScale(image, faceDetections);

    System.out.println(String.format("Detected %s faces", faceDetections.toArray().length));

    // Draw a bounding box around each face.
    for (Rect rect : faceDetections.toArray()) {
        Core.rectangle(image, new Point(rect.x, rect.y), new Point(rect.x + rect.width, rect.y + rect.height), new Scalar(0, 255, 0));
    }

    // Save the visualized detection.
    String filename = "faceDetection.png";
    System.out.println(String.format("Writing %s", filename));
    Highgui.imwrite(filename, image);
  }
}

public class HelloOpenCV {
  public static void main(String[] args) {
    System.out.println("Hello, OpenCV");

    // Load the native library.
    System.loadLibrary("opencv_java244");
    new DetectFaceDemo().run();
  }
}

Note the call to System.loadLibrary("opencv_java244"). This command must be executed exactly once per Java process prior to using any native
OpenCV methods. If you don’t call it, you will getUnsatisfiedLink errors. You will also get errors if you try to
load OpenCV when it has already been loaded.

Now run the face detection app using sbt run:

sbt run

You should see something like this:

It should also write the following image to faceDetection.png:

You’re done! Now you have a sample Java application working with OpenCV, so you can start the work on your own. We wish you good luck and many years of joyful life!

时间: 2024-11-04 22:16:14

eclipse开发opencv官方教程的相关文章

分享《OpenCV官方教程中文版(For Python)》+PDF+段力辉

下载:https://pan.baidu.com/s/1sWxCp2uaQSS8-5TRdEVJyA 更多资料学习:http://blog.51cto.com/14087171 版权说明:本人无版权,请您在体验电子版书籍的同时,支持正版,购买正版书籍!!! 首页如下图 原文地址:http://blog.51cto.com/14087171/2323372

jetty使用教程(嵌入eclipse开发)

在eclipse下面建一个java project 建立目录结构如下: 二级目录: (备注jetty_test是工程的根目录,etc.lib.webRoot为其二级目录) 到jetty的官方网站(http://www.eclipse.org/jetty/)下载jetty的开发包: 我下载的jetty-hightide-8.0.0.v20110901.tar.gz: 把里面的lib目录的jar包和lib/jsp目录下面的jar包导入到工程里面 说明白,其实jetty.xml和webdefault.

如何在Eclipse正确安装配置PyDev插件的官方教程,以及error 问题的解决方法:

官方教程; 1 1 This manual assumes that you have already have Python and/or Jython and/or IronPython installed in your machine, as well as Eclipse. Manual topics: Installing from update site and zips uninstalling Configuring the interpreter specify the py

【OpenCV入门教程之一】 安装OpenCV:OpenCV 3.0、OpenCV 2.4.8、OpenCV 2.4.9 +VS 开发环境配置

本系列文章由@浅墨_毛星云 出品.   文章链接:http://blog.csdn.net/poem_qianmo/article/details/19809337 1.下载和安装OpenCV SDK VS2010不用说,肯定都安装了吧.来说说当前最新的OpenCV版本2.4.8(2014年2月24日),2.4.9 (2014年4月)的下载和安装.与其说是安装,不如叫解压更加合适,因为我们下载的exe安装文件就是一个自解压程序而已. 在官网:http://opencv.org/上找到OpenCV

[游戏开发-学习笔记]菜鸟慢慢飞(三)-官方教程学习小心得

自己的事情自己做 举例:官方教程<Tanks tutorial>中,小坦克:移动,移动的声音,射击,生命值的管理,等Component都挂载在GameObject坦克自己的身上.炮弹,则管理自己的爆炸等. 好处不少: ~开发维护的时候更加方便 ~符合"面对对象"的思想 一个脚本做一件事情 举例:官方教程<Tanks tutorial>中,小坦克:c#脚本分为三个,移动,生命管理,射击. 好处很多: ~在炮弹的爆炸脚本可以单独调用生命管理去更改生命值. ~代码更加

eclipse开发scrapy爬虫工程,附爬虫临门级教程

写在前面 自学爬虫入门之后感觉应该将自己的学习过程整理一下,也为了留个纪念吧. scrapy环境的配置还请自行百度,其实也不难(仅针对windows系统,centos配置了两天,直到现在都没整明白) 就是安装python之后下载pip,setup pip,然后用pip install下载就行了(pyspider也是这样配置的). 附主要资料参考地址 scrapy教程地址  https://www.bilibili.com/video/av13663892?t=129&p=2 eclipse开发s

Linux上搭建Hadoop2.6.3集群以及WIN7通过Eclipse开发MapReduce的demo

近期为了分析国内航空旅游业常见安全漏洞,想到了用大数据来分析,其实数据也不大,只是生产项目没有使用Hadoop,因此这里实际使用一次. 先看一下通过hadoop分析后的结果吧,最终通过hadoop分析国内典型航空旅游业厂商的常见安全漏洞个数的比例效果如下: 第一次正式使用Hadoop,肯定会遇到非常多的问题,参考了很多网络上的文章,我把自己从0搭建到使用的过程记录下来,方便以后自己或其他人参考. 之前简单用过storm,适合实时数据的处理.hadoop更偏向静态数据的处理,网上很多hadoop的

【OpenCV入门教程之三】 图像的载入,显示和输出 一站式完全解析

了解过之前老版本OpenCV的童鞋们都应该清楚,对于OpenCV1.0时代的基于 C 语言接口而建的图像存储格式IplImage*,如果在退出前忘记release掉的话,就会造成内存泄露.而且用起来超级麻烦,我们往往在debug的时候,很大一部分时间在纠结手动释放内存的问题.虽然对于小型的程序来说手动管理内存不是问题,但一旦我们写的代码变得越来越庞大,我们便会开始越来越多地纠缠于内存管理的问题,而不是着力解决你的开发目标. 这,就有些舍本逐末的感觉了. 而自从OpenCV踏入2.0时代,用Mat

Eclipse开发Android程序如何在手机上运行

android开发不论是在真机上调试还是最终发布到真机上都非常简单,过程如下: 1.安装usb驱动 手机要能与电脑相连,当然要安驱动了.效果就是你插入手机,电脑显示驱动已识别.驱动安装的官方教程:http://developer.android.com/sdk/win-usb.html 官方教程概述: 不同的Android手机有对应不同的驱动,对于Nexus One, and Nexus S,见官方教程“Downloading the Goolge USB Driver”部分,直接用Androi