Java调用Python人脸识别脚本

Java调用Python人脸识别脚本

点我进入原文链接♥

没有屁话,全是干货!

一、python 人脸识别脚本

# -*- coding: utf-8 -*-
"""
@Time : 2022/4/14 1:07
@Auth : BalalaEnergy
@File :face.py
@IDE :PyCharm

"""
import sys
import face_recognition


def face_check(target_face_path, check_face_path):
    """
    :param target_face_path: 源人脸图片地址
    :param check_face_path: 待检测人脸图片地址
    :return: A list of True/False values indicating which known_face_encodings match the face encoding to check
    """
    # 将base64图片转为转码
    target_image = face_recognition.load_image_file(target_face_path)
    # 计算已知图片对应的编码
    target_face_encoding = face_recognition.face_encodings(target_image)[0]
    target_encodings = [
        target_face_encoding
    ]
    # 加载一张未知面孔的图片
    image_to_check = face_recognition.load_image_file(check_face_path)
    # 计算图片对应的编码
    check_face_encoding = face_recognition.face_encodings(image_to_check)[0]
    # 返回识别结果
    return face_recognition.compare_faces(target_encodings, check_face_encoding)


if __name__ == '__main__':
    for i in range(len(sys.argv)):
        print(sys.argv[i])
    target_path = sys.argv[1]
    check_path = sys.argv[2]
    result = face_check(target_path, check_path)[0]
    print(result)

注意:这里使用的本地图片的方式,如果是网络连接,可以先保存到本地,然后再已路径的方式传递脚本

二、Java调用Python脚本并获取脚本返回值

注意:

​ Java调用Python脚本大致有两种方式:

  • 通过Java编写的解释器;jpython;、

    优点

    • 调用简单,只需要引入jar依赖包

    缺点:

    • 基于Python2开发,不能使用Python3的语法

    • 依赖不一定能安装上

  • 调用本地Python解释器

    优点

    • 不局限与JPython版本
    • 支持任意版本Python解释器

    缺点:

    • 参数传递会有局限性(不能传过长的参数,应该是命令行最大字符限制:2048)
package com.balalaenergy.utils;

import com.balalaenergy.utils.entity.FaceCheckReq;
import com.balalaenergy.utils.entity.FaceCheckRsp;
import lombok.extern.slf4j.Slf4j;
import sun.misc.BASE64Decoder;

import java.io.*;
import java.util.Base64;

/**
 * @author :BalalaEnergy
 * @date :Created in 2022/4/14 20:19
 * @description: 人脸识别工具类
 * @modified By:
 */
@Slf4j
public class FaceCheckUtil {
    /**
     * 人脸识别工具类
     *
     * @param faceCheckReq
     */
    public static FaceCheckRsp checkFaceCheck(FaceCheckReq faceCheckReq) {
        Process proc;
        boolean result;
        try {
            //指定命令、路径、传递的参数
            String[] arguments = new String[]{faceCheckReq.getPythonExePath(), faceCheckReq.getTargetPythonFile(), faceCheckReq.getTargetFace(), faceCheckReq.getCheckFace()};
            proc = Runtime.getRuntime().exec(arguments);
            BufferedReader in = new BufferedReader(new InputStreamReader(proc.getInputStream()));
            String line;

            while ((line = in.readLine()) != null) {
                System.out.println("接收到python脚本打印信息:" + line);
                try {
                    result = Boolean.parseBoolean(line);
                    if (result) {
                        return new FaceCheckRsp(Boolean.TRUE);
                    }
                } catch (Exception e) {
                    log.error("人脸识别异常", e);
                    return new FaceCheckRsp(Boolean.FALSE);
                }
            }
            in.close();
            proc.waitFor();
        } catch (IOException | InterruptedException e) {
            e.printStackTrace();
            return new FaceCheckRsp(Boolean.FALSE);
        }
        return new FaceCheckRsp(false);
    }

    public static void main(String[] args) {
        String target = getImageStr("target.jpg");
        String source = getImageStr("source.jpg");
        FaceCheckReq faceCheckReq = new FaceCheckReq();
        faceCheckReq.setPythonExePath("python解释器本地安装路径");
        String targetPythonDir = "需要执行的python 脚本路径";
        String targetPicPath = targetPythonDir + "target.jpg";
        String checkPicPath = targetPythonDir + "check.jpg";
        GenerateImage(targetPicPath, target);
        GenerateImage(checkPicPath, source);
        faceCheckReq.setTargetPythonFile(targetPythonDir + "face_check.py");
        faceCheckReq.setTargetFace(targetPicPath);
        faceCheckReq.setCheckFace(checkPicPath);
        FaceCheckRsp faceCheckRsp = checkFaceCheck(faceCheckReq);
        System.out.println("人脸检测:" + (faceCheckRsp.getIsCheck() ? "成功" : "失败"));
    }

    public static String getImageStr(String imgFile) {
        InputStream inputStream;
        byte[] data = null;
        try {
            inputStream = new FileInputStream(imgFile);
            data = new byte[inputStream.available()];
            inputStream.read(data);
            inputStream.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
        // 加密
        return Base64.getEncoder().encodeToString(data);
    }

    /**
     * 对字节数组字符串进行Base64解码并生成图片
     *
     * @param imgStr
     * @return
     */
    public static boolean GenerateImage(String path, String imgStr) {
        if (imgStr == null) {
            // 图像数据为空
            return false;
        }
        BASE64Decoder decoder = new BASE64Decoder();
        try {
            // Base64解码
            byte[] b = decoder.decodeBuffer(imgStr);
            for (int i = 0; i < b.length; ++i) {
                // 调整异常数据
                if (b[i] < 0) {
                    b[i] += 256;
                }
            }
            // 生成jpeg图片
            // 新生成的图片
            OutputStream out = new FileOutputStream(path);
            out.write(b);
            out.flush();
            out.close();
            return true;
        } catch (Exception e) {
            return false;
        }
    }
}


/**
 * @author :BalalaEnergy
 * @date :Created in 2022/4/14 20:27
 * @description:
 * @modified By:
 */
@Data
public class FaceCheckReq {
    /**
     * python exe路径
     */
    private String pythonExePath;
    /**
     * 要执行的python文件
     */
    private String targetPythonFile;
    /**
     * 目标人脸数据,已保存
     */
    private String targetFace;
    /**
     * 要检测的人脸数据,待检测
     */
    private String checkFace;
}

你可能感兴趣的:(Java,Python,人脸识别,python,java,pycharm)