Java|在Java中使用OpenCV (maven,ant,eclipse)

Java中使用OpenCV 从2.4.4开始,OpenCV支持Java.
参考链接: http://docs.opencv.org/doc/tutorials/introduction/desktopjava/javadev_intro.html
获取OpenCV 从SourceForge可以获得依赖的文件。当然Windows用户最简单的方式是下载.exe文件安装。
对Window用户,在opencv/build/java/文件夹下有所需的jar文件。对于其他用户,需要使用源文件进行编译。
Java Sample With eclipse 在eclipse中使用Opencv,最简单的方式是在eclipse中建立一个用户Library。每次在使用opencv时,引入该Library。
来源:http://docs.opencv.org/doc/tutorials/introduction/javaeclipse/javaeclipse.html#java-eclipse
步骤:
1,Launch Eclipse and select Window –> Preferences from the menu.
2,Navigate under Java –> Build Path –> User Libraries and click New....
3,Enter a name, e.g. OpenCV-2.4.6, for your new library.
4,Now select your new user library and click Add External JARs....
5,Browse through C:\OpenCV-2.4.6\build\java\ and select opencv-246.jar. After adding the jar, extend the opencv-246.jar and selectNative library location and press Edit....
6,Select External Folder... and browse to select the folder C:\OpenCV-2.4.6\build\java\x64. If you have a 32-bit system you need to select the x86 folder instead of x64.
7,Now start creating a new Java project.On the Java Settings step, under Libraries tab, select Add Library... and select OpenCV-2.4.6, then clickFinish.
Demo

public class SampleCV {public static void main(String[] args) {System.loadLibrary( Core.NATIVE_LIBRARY_NAME ); //读取图像,不改变图像的原始信息 Mat m = Highgui.imread("c:\\1.png",Highgui.CV_LOAD_IMAGE_COLOR); //将图片转换成灰度图片 Mat gray = new Mat(m.size(),CvType.CV_8UC1); Imgproc.cvtColor(m,gray,Imgproc.COLOR_RGB2GRAY); //计算灰度直方图 List images = new ArrayList(); images.add(gray); MatOfInt channels= new MatOfInt(0); MatOfInt histSize = new MatOfInt(256); MatOfFloat ranges= new MatOfFloat(0,256); Mat hist = new Mat(); Imgproc.calcHist(images, channels, new Mat(), hist, histSize, ranges); //mat求和 System.out.println(Core.sumElems(hist)); //保存转换的图片 Highgui.imwrite("c:\\2.png",gray); } }

Java Sample with Maven 在pom.xml中添加opencv的依赖如下:
org.opencv opencv 2.4.9 C:/opencv/build/java/opencv-249.jar system

然后在加载动态链接库时,不使用System.loadLibrary(xxx); 。 而是使用 绝对路径加载:System.load(xxx);
Demo中的System.loadLibrary(xxx); 用如下的两句话替换,其他无需改变:
String path = "C:\\opencv\\build\\java\\x64\\opencv_java249.dll"; System.load(path);

Java Sample with Ant 建立下面的build.xml,执行ant命令:
ant -DocvJarDir=X:\opencv-2.4.4\bin -DocvLibDir=X:\opencv-2.4.4\bin\Release、

或者直接将DocvJarDir,DocvLibDir硬编码到build.xml。
【Java|在Java中使用OpenCV (maven,ant,eclipse)】 build.xml文件:

    推荐阅读