本来以为,修改了rpath之后,问题就解决了。结果依然说库找不到(库在同目录下)。具体来说:
Exception in thread "main" java.lang.UnsatisfiedLinkError: /home/wuxi/eclipse-workspace/FontTest/lib-native/libopencv_java455.so: libopencv_ml.so.405: 无法打开共享对象文件: 没有那个文件或目录 at java.lang.ClassLoader$NativeLibrary.load(Native Method) at java.lang.ClassLoader.loadLibrary0(ClassLoader.java:1934) at java.lang.ClassLoader.loadLibrary(ClassLoader.java:1817) at java.lang.Runtime.load0(Runtime.java:810) at java.lang.System.load(System.java:1088) at taishan.OpenCVTest.<clinit>(OpenCVTest.java:49)
吾反复实验都不对,就是说找不到。怎么办?干脆吾自己加载吧。别说,错误马上不一样了。考虑到通用性,使用了一个技巧,通过双层双重循环来处理。终于成功。代码如下:
package taishan; import java.io.File; import java.util.LinkedList; import java.util.List; import org.opencv.core.Core; import org.opencv.core.CvType; import org.opencv.core.Mat; public class OpenCVTest { private final static String NATIVE_DIR="/home/wuxi/eclipse-workspace/FontTest/lib-native"; private final static String LIB_PREFIX = "libopencv_"; private final static String LIB_SUFFIX_LINUX = "so"; private final static String LIB_SUFFIX_MAC = "dylib"; private static boolean isOpenCVLoaded = false;; private static List<File> getOpenCVFiles(final String dirName) { if (dirName == null) { return null; } File dir = new File(dirName); if (!dir.exists() || !dir.isDirectory()) { return null; } File[] files = dir.listFiles(); List<File> fileList = new LinkedList<File>(); for (File file : files) { String name = file.getName(); if (name.startsWith(LIB_PREFIX) && name.endsWith(LIB_SUFFIX_LINUX)) { fileList.add(file); } } return fileList; } private static void loadNativeOpenCV(final String dirName) { if (isOpenCVLoaded) { return; } List<File> fileList = getOpenCVFiles(dirName); if (fileList == null || fileList.size() == 0) { return; } while (fileList.size() > 0) { int left = fileList.size(); for (int i=0; i<fileList.size(); i++) { File file = fileList.get(i); try { System.load(file.getAbsolutePath()); } catch (java.lang.Throwable e) { continue; } fileList.remove(i); i--; } System.out.println(left+" ? "+fileList.size()); //如果这次循环后,剩余个数跟上次一样,说明依赖库有问题,中断。 if (left == fileList.size()) { fileList.clear(); return; } } //如果libopencv_java.so在另外目录,需要单独加载 //System.load(Dir+"/"+"lib"+Core.Core.NATIVE_LIBRARY_NAME+"."+LIB_SUFFIX_LINUX); isOpenCVLoaded = true; } public static void main(String[] args) { loadNativeOpenCV(NATIVE_DIR); Mat mat = Mat.eye(3, 3, CvType.CV_8UC1); System.out.println("mat = "+mat.dump()); } }