用Java加载Mathematica做面部识别

版本信息: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的官方文档。

结果如下:


  • 0
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 1
    评论
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值