Commit 7e5eee5b authored by Andrey Kamaev's avatar Andrey Kamaev Committed by OpenCV Buildbot

Merge pull request #301 from emchristiansen:javasample2.4

parents f58dffe3 2853bab4
......@@ -8,4 +8,5 @@
.. |Author_FernandoI| unicode:: Fernando U+0020 Iglesias U+0020 Garc U+00ED a
.. |Author_EduardF| unicode:: Eduard U+0020 Feicho
.. |Author_AlexB| unicode:: Alexandre U+0020 Benoit
.. |Author_EricCh| unicode:: Eric U+0020 Christiansen
.. |Author_AndreyP| unicode:: Andrey U+0020 Pavlenko
This diff is collapsed.
......@@ -101,6 +101,26 @@ Here you can read tutorials about how to set up your computer to work with the O
:height: 90pt
:width: 90pt
* **Desktop Java**
.. tabularcolumns:: m{100pt} m{300pt}
.. cssclass:: toctableopencv
================ =================================================
|JavaLogo| **Title:** :ref:`Java_Dev_Intro`
*Compatibility:* > OpenCV 2.4.4
*Authors:* |Author_EricCh| and |Author_AndreyP|
Explains how to build and run a simple desktop Java application using Eclipse, Ant or the Simple Build Tool (SBT).
================ =================================================
.. |JavaLogo| image:: images/Java_logo.png
:height: 90pt
:width: 90pt
* **Android**
.. tabularcolumns:: m{100pt} m{300pt}
......@@ -238,10 +258,11 @@ Here you can read tutorials about how to set up your computer to work with the O
../linux_eclipse/linux_eclipse
../windows_install/windows_install
../windows_visual_studio_Opencv/windows_visual_studio_Opencv
../desktop_java/java_dev_intro
../android_binary_package/android_dev_intro
../android_binary_package/O4A_SDK
../android_binary_package/dev_with_OCV_on_Android
../ios_install/ios_install
../display_image/display_image
../load_save_image/load_save_image
../how_to_write_a_tutorial/how_to_write_a_tutorial
\ No newline at end of file
../how_to_write_a_tutorial/how_to_write_a_tutorial
<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>
\ No newline at end of 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());
}
}
<?xml version="1.0" encoding="UTF-8"?>
<classpath>
<classpathentry kind="src" path="src"/>
<classpathentry kind="con" path="org.eclipse.jdt.launching.JRE_CONTAINER/org.eclipse.jdt.internal.debug.ui.launcher.StandardVMType/JavaSE-1.7"/>
<classpathentry kind="con" path="org.eclipse.jdt.USER_LIBRARY/opencv-2.4.4"/>
<classpathentry kind="output" path="bin"/>
</classpath>
<?xml version="1.0" encoding="UTF-8"?>
<projectDescription>
<name>HelloCV</name>
<comment></comment>
<projects>
</projects>
<buildSpec>
<buildCommand>
<name>org.eclipse.jdt.core.javabuilder</name>
<arguments>
</arguments>
</buildCommand>
</buildSpec>
<natures>
<nature>org.eclipse.jdt.core.javanature</nature>
</natures>
</projectDescription>
eclipse.preferences.version=1
org.eclipse.jdt.core.compiler.codegen.inlineJsrBytecode=enabled
org.eclipse.jdt.core.compiler.codegen.targetPlatform=1.7
org.eclipse.jdt.core.compiler.codegen.unusedLocal=preserve
org.eclipse.jdt.core.compiler.compliance=1.7
org.eclipse.jdt.core.compiler.debug.lineNumber=generate
org.eclipse.jdt.core.compiler.debug.localVariable=generate
org.eclipse.jdt.core.compiler.debug.sourceFile=generate
org.eclipse.jdt.core.compiler.problem.assertIdentifier=error
org.eclipse.jdt.core.compiler.problem.enumIdentifier=error
org.eclipse.jdt.core.compiler.source=1.7
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());
}
}
A demo of the Java wrapper for OpenCV with two examples:
1) feature detection and matching and
2) face detection.
The examples are coded in Scala and Java.
Anyone familiar with Java should be able to read the Scala examples.
Please feel free to contribute code examples in Scala or Java, or any JVM language.
To run the examples:
1) Install OpenCV and copy the OpenCV jar to lib/.
This jar must match the native libraries installed in your system.
If this isn't the case, you may get a java.lang.UnsatisfiedLinkError at runtime.
2) Go to the root directory and type "sbt/sbt run".
This should generate images in your current directory.
import sbt._
import Keys._
object OpenCVJavaDemoBuild 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 := "OpenCVJavaDemo")
Project(id = "OpenCVJavaDemo", base = file("."), settings = settings)
}
}
addSbtPlugin("com.typesafe.sbteclipse" % "sbteclipse-plugin" % "2.1.0")
java -Xms512M -Xmx1536M -Xss1M -XX:+CMSClassUnloadingEnabled -XX:MaxPermSize=384M -jar `dirname $0`/sbt-launch.jar "$@"
\ No newline at end of file
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".
*/
public 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(
"/AverageMaleFace.jpg").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);
}
}
\ No newline at end of file
/*
* The main runner for the Java demos.
* Demos whose name begins with "Scala" are written in the Scala language,
* demonstrating the generic nature of the interface.
* The other demos are in Java.
* Currently, all demos are run, sequentially.
*
* You're invited to submit your own examples, in any JVM language of
* your choosing so long as you can get them to build.
*/
object Main extends App {
// We must load the native library before using any OpenCV functions.
// You must load this library _exactly once_ per Java invocation.
// If you load it more than once, you will get a java.lang.UnsatisfiedLinkError.
System.loadLibrary("opencv_java")
ScalaCorrespondenceMatchingDemo.run()
ScalaDetectFaceDemo.run()
new DetectFaceDemo().run()
}
import org.opencv.highgui.Highgui
import org.opencv.features2d.DescriptorExtractor
import org.opencv.features2d.Features2d
import org.opencv.core.MatOfKeyPoint
import org.opencv.core.Mat
import org.opencv.features2d.FeatureDetector
import org.opencv.features2d.DescriptorMatcher
import org.opencv.core.MatOfDMatch
import reflect._
/*
* Finds corresponding points between a pair of images using local descriptors.
* The correspondences are visualized in the image "scalaCorrespondences.png",
* which is written to disk.
*/
object ScalaCorrespondenceMatchingDemo {
def run() {
println(s"\nRunning ${classTag[this.type].toString.replace("$", "")}")
// Detects keypoints and extracts descriptors in a given image of type Mat.
def detectAndExtract(mat: Mat) = {
// A special container class for KeyPoint.
val keyPoints = new MatOfKeyPoint
// We're using the SURF detector.
val detector = FeatureDetector.create(FeatureDetector.SURF)
detector.detect(mat, keyPoints)
println(s"There were ${keyPoints.toArray.size} KeyPoints detected")
// Let's just use the best KeyPoints.
val sorted = keyPoints.toArray.sortBy(_.response).reverse.take(50)
// There isn't a constructor that takes Array[KeyPoint], so we unpack
// the array and use the constructor that can take any number of
// arguments.
val bestKeyPoints: MatOfKeyPoint = new MatOfKeyPoint(sorted: _*)
// We're using the SURF descriptor.
val extractor = DescriptorExtractor.create(DescriptorExtractor.SURF)
val descriptors = new Mat
extractor.compute(mat, bestKeyPoints, descriptors)
println(s"${descriptors.rows} descriptors were extracted, each with dimension ${descriptors.cols}")
(bestKeyPoints, descriptors)
}
// Load the images from the |resources| directory.
val leftImage = Highgui.imread(getClass.getResource("/img1.png").getPath)
val rightImage = Highgui.imread(getClass.getResource("/img2.png").getPath)
// Detect KeyPoints and extract descriptors.
val (leftKeyPoints, leftDescriptors) = detectAndExtract(leftImage)
val (rightKeyPoints, rightDescriptors) = detectAndExtract(rightImage)
// Match the descriptors.
val matcher = DescriptorMatcher.create(DescriptorMatcher.BRUTEFORCE)
// A special container class for DMatch.
val dmatches = new MatOfDMatch
// The backticks are because "match" is a keyword in Scala.
matcher.`match`(leftDescriptors, rightDescriptors, dmatches)
// Visualize the matches and save the visualization.
val correspondenceImage = new Mat
Features2d.drawMatches(leftImage, leftKeyPoints, rightImage, rightKeyPoints, dmatches, correspondenceImage)
val filename = "scalaCorrespondences.png"
println(s"Writing ${filename}")
assert(Highgui.imwrite(filename, correspondenceImage))
}
}
\ No newline at end of file
import org.opencv.core.Core
import org.opencv.core.MatOfRect
import org.opencv.core.Point
import org.opencv.core.Scalar
import org.opencv.highgui.Highgui
import org.opencv.objdetect.CascadeClassifier
import reflect._
/*
* Detects faces in an image, draws boxes around them, and writes the results
* to "scalaFaceDetection.png".
*/
object ScalaDetectFaceDemo {
def run() {
println(s"\nRunning ${classTag[this.type].toString.replace("$", "")}")
// Create a face detector from the cascade file in the resources directory.
val faceDetector = new CascadeClassifier(getClass.getResource("/lbpcascade_frontalface.xml").getPath)
val image = Highgui.imread(getClass.getResource("/AverageMaleFace.jpg").getPath)
// Detect faces in the image.
// MatOfRect is a special container class for Rect.
val faceDetections = new MatOfRect
faceDetector.detectMultiScale(image, faceDetections)
println(s"Detected ${faceDetections.toArray.size} faces")
// Draw a bounding box around each face.
for (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.
val filename = "scalaFaceDetection.png"
println(s"Writing ${filename}")
assert(Highgui.imwrite(filename, image))
}
}
\ No newline at end of file
Markdown is supported
0% or
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment