版本信息:JDK8 + Mathematica 10.0
比较简单。Java加载Jlink库,调用Math Kernel的FindFaces函数。具体如下:
1. JLink.jar加入classpath中;
2. JVM运行参数中,加入-Djava.library.path="D:\Program Files\Wolfram Research\Mathematica\10.0\SystemFiles\Links\JLink\SystemFiles\Libraries\Windows-x86-64" 这样JLink能找到JNI的库。
3. 写代码,比较简单
import com.wolfram.jlink.*;
import java.io.File;
import java.io.FileOutputStream;
/**
* Created by LFF-PC on 2015/4/27.
*/
public class TestMathematica1 {
static KernelLink ml = null;
public static void main(String[] argu) {
String ma = "d:\\Program Files\\Wolfram Research\\Mathematica\\10.0\\mathkernel.exe";
String file = "e:/dcs/2.jpg";
String out = "e:/dcs/out2.jpg";
connect(ma);
try {
ml.discardAnswer();
ml.evaluate("Sqrt[25]");
ml.waitForAnswer();
int result = ml.getInteger();
System.out.println("sqrt[25] = " + result);
System.out.println("start to find faces");
// ml.evaluateToOutputForm("$DefaultImageFormat = \"JPEG\"", 0);
byte[] gifData = ml.evaluateToTypeset("i = Interpreter[\"Image\"][Import[\"" + file + "\", \"String\"]];\n" +
"boxes = FindFaces[i];\n" +
"HighlightImage[i, \n" +
" Graphics[{EdgeForm[{Red, Thick}], Opacity[0], Rectangle @@@ boxes}]]"
,0, false);
try {
FileOutputStream s = new FileOutputStream(new File(out));
s.write(gifData);
s.close();
} catch (Exception e) {}
// ALWAYS execute CloseFrontEnd[] before killing the kernel if you used
// evaluateToTypeset(), or evaluateToImage() with the useFE parameter
// set to true:
ml.evaluateToOutputForm("CloseFrontEnd[]", 0);
ml.close();
} catch (MathLinkException e) {
e.printStackTrace();
}
ml.close();
}
private static void connect(String mathematica) {
try {
ml = MathLinkFactory.createKernelLink("-linkmode launch -linkname '" +
mathematica + "'");
} catch (MathLinkException e) {
System.out.println("Link could not be created: " + e.getMessage());
return; // Or whatever is appropriate.
}
}
}
基本上都是参考JLink的官方文档。
结果如下: