如何在命令行中运行包含OpenCV代码并使用ant创建的.jar文件?

我试图从Ubuntu控制台运行一个小的java类,它包含这样的OpenCV代码:

import org.opencv.core.Core; import org.opencv.core.Mat; import org.opencv.core.CvType; import org.opencv.core.Scalar; class SimpleSample { static{ System.loadLibrary(Core.NATIVE_LIBRARY_NAME); } public static void main(String[] args) { System.out.println("Welcome to OpenCV " + Core.VERSION); 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()); } } 

我用ant建造了这个; build.xml看起来像这样: –

                                     

当给出命令“ant”时,代码产生以下输出: –

 Buildfile: /opencv-2.4.7/samples/java/ant/build.xml clean: [delete] Deleting directory /opencv-2.4.7/samples/java/ant/build compile: [mkdir] Created dir: /opencv-2.4.7/samples/java/ant/build/classes [javac] Compiling 1 source file to /opencv-2.4.7/samples/java/ant/build/classes jar: [mkdir] Created dir: /opencv-2.4.7/samples/java/ant/build/jar [jar] Building jar: /opencv-2.4.7/samples/java/ant/build/jar/SimpleSample.jar run: [java] Welcome to OpenCV 2.4.7.0 [java] OpenCV Mat: Mat [ 5*10*CV_8UC1, isCont=true, isSubmat=false, nativeObj=0x7fc23c1bbc90, dataAddr=0x7fc23c1bbd50 ] [java] OpenCV Mat data: [java] [0, 0, 0, 0, 0, 5, 0, 0, 0, 0; [java] 1, 1, 1, 1, 1, 5, 1, 1, 1, 1; [java] 0, 0, 0, 0, 0, 5, 0, 0, 0, 0; [java] 0, libdc1394 error: Failed to initialize libdc1394 [java] 0, 0, 0, 0, 5, 0, 0, 0, 0; [java] 0, 0, 0, 0, 0, 5, 0, 0, 0, 0] rebuild-run: BUILD SUCCESSFUL Total time: 3 seconds 

但是当我尝试使用命令java -jar SimpleSample.jar运行上一步中生成的.jar文件时,它会出现以下错误: –

 Exception in thread "main" java.lang.NoClassDefFoundError: org/opencv/core/Core at SimpleSample.(Unknown Source) Caused by: java.lang.ClassNotFoundException: org.opencv.core.Core at java.net.URLClassLoader$1.run(URLClassLoader.java:366) at java.net.URLClassLoader$1.run(URLClassLoader.java:355) at java.security.AccessController.doPrivileged(Native Method) at java.net.URLClassLoader.findClass(URLClassLoader.java:354) at java.lang.ClassLoader.loadClass(ClassLoader.java:424) at sun.misc.Launcher$AppClassLoader.loadClass(Launcher.java:308) at java.lang.ClassLoader.loadClass(ClassLoader.java:357) ... 1 more 

我打算从命令行本身运行SimpleSample.jar文件,没有任何错误。 有人可以告诉我,我需要做些什么才能实现这一目标?

我通过用我构建的jar包装OpenCV库jar来解决它。 在build.xml“jar”目标中,我添加了一个像这样归属的“zipgroupfileset” : –

       

问题是您没有正确指定类路径,因此可能没有正确捆绑您的依赖项。

您必须更改build.xml文件。 将以下内容添加到build.xml中

                   

希望这有效。