OPENCV

package com.ljq.demo.springboot.opencv.common.util;

import cn.smartjavaai.face.config.FaceModelConfig;
import cn.smartjavaai.face.enums.FaceModelEnum;
import cn.smartjavaai.face.factory.FaceModelFactory;
import cn.smartjavaai.face.model.facerec.FaceModel;
import lombok.extern.slf4j.Slf4j;
import nu.pattern.OpenCV;
import org.opencv.core.*;
import org.opencv.core.Rect;
import org.opencv.imgcodecs.Imgcodecs;
import org.opencv.imgproc.CLAHE;
import org.opencv.imgproc.Imgproc;
import org.opencv.objdetect.CascadeClassifier;
import org.opencv.objdetect.HOGDescriptor;
import org.springframework.util.ResourceUtils;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.Objects;


@Slf4j
public class FaceRecognitionUtil {
    private static CascadeClassifier faceDetector;
    private static final Size FACE_SIZE = new Size(92, 112); // 统一的人脸图片大小
    /**
     * 初始化 opencv
     *
     * @param isDebug
     * @return
     */
    public static CascadeClassifier init(boolean isDebug) {
        if (Objects.isNull(faceDetector) || faceDetector.empty()) {
            synchronized (FaceDetectUtil.class) {
                if (Objects.isNull(faceDetector) || faceDetector.empty()) {
                    try {
                        // 加载 openCV 函数库
                        OpenCV.loadShared();
                        log.info("opencv 函数库加载成功");
                        // 初始化人脸探测器
                        faceDetector = new CascadeClassifier();
                        String xmlFilePath =  "opencv" + File.separator + "haarcascade_frontalface_default.xml";
                        boolean detectorInitResult = false;
                        if (isDebug) {
                            File xmlFile = ResourceUtils.getFile("classpath:" + xmlFilePath);
                            detectorInitResult = faceDetector.load(xmlFile.getAbsolutePath());
                        } else {
                            detectorInitResult = faceDetector.load(System.getProperty("user.dir") + File.separator + xmlFilePath);
                        }
                        log.info("opencv 人脸检测工具加载结果: {}", detectorInitResult);
                    } catch (Exception e) {
                        log.error("opencv face check init error", e);
                    }
                }
            }
        }
        return faceDetector;
    }


    /**
     * 从图片中检测并提取人脸
     * @param image 原始图片
     * @return 提取到的人脸图片列表
     */
    public static List<Mat> detectAndExtractFaces(Mat image) {
        init(true);
        List<Mat> faces = new ArrayList<>();
        MatOfRect faceDetections = new MatOfRect();
        faceDetector.detectMultiScale(image, faceDetections,1.05,6,0,new Size(30,30),new Size(300,300));

        for (Rect rect : faceDetections.toArray()) {
            Mat face = new Mat(image, rect);
            // 调整人脸图片大小为统一尺寸
            Mat resizedFace = new Mat();
            Imgproc.resize(face, resizedFace, FACE_SIZE);

            // 转换为灰度图
            Imgproc.cvtColor(resizedFace, resizedFace, Imgproc.COLOR_BGR2GRAY);

            // 人脸对齐
            Mat alignedFace = alignFace(resizedFace);

            // 光照归一化
            Mat normalizedFace = normalizeIllumination(alignedFace);

            // 直方图均衡化
            Imgproc.equalizeHist(normalizedFace, normalizedFace);

            // 添加高斯模糊去噪
            Imgproc.GaussianBlur(normalizedFace, normalizedFace, new Size(3, 3), 0);

            // 添加自适应直方图均衡化
            Imgproc.createCLAHE(2.0, new Size(8,8)).apply(normalizedFace, normalizedFace);

            faces.add(normalizedFace);
        }
        return faces;
    }

    /**
     * 人脸对齐
     * @param face 输入的人脸图像
     * @return 对齐后的人脸图像
     */
    private static Mat alignFace(Mat face) {
        // 创建眼睛检测器
        CascadeClassifier eyeDetector = new CascadeClassifier();
        String eyeCascadePath = "opencv" + File.separator + "haarcascade_eye.xml";
        try {
            File eyeXmlFile = ResourceUtils.getFile("classpath:" + eyeCascadePath);
            eyeDetector.load(eyeXmlFile.getAbsolutePath());
        } catch (Exception e) {
            log.error("加载眼睛检测器失败", e);
            return face;
        }

        // 检测眼睛
        MatOfRect eyeDetections = new MatOfRect();
        eyeDetector.detectMultiScale(face, eyeDetections);

        if (eyeDetections.toArray().length < 2) {
            return face;
        }

        // 获取两个眼睛的位置
        Rect[] eyes = eyeDetections.toArray();
        Point leftEye = new Point(eyes[0].x + eyes[0].width/2, eyes[0].y + eyes[0].height/2);
        Point rightEye = new Point(eyes[1].x + eyes[1].width/2, eyes[1].y + eyes[1].height/2);

        // 确保左眼在左边
        if (leftEye.x > rightEye.x) {
            Point temp = leftEye;
            leftEye = rightEye;
            rightEye = temp;
        }

        // 计算旋转角度
        double angle = Math.atan2(rightEye.y - leftEye.y, rightEye.x - leftEye.x) * 180 / Math.PI;

        // 获取图像中心点
        Point center = new Point(face.cols() / 2, face.rows() / 2);

        // 创建旋转矩阵
        Mat rotationMatrix = Imgproc.getRotationMatrix2D(center, angle, 1.0);

        // 执行旋转
        Mat alignedFace = new Mat();
        Imgproc.warpAffine(face, alignedFace, rotationMatrix, face.size());

        return alignedFace;
    }

    /**
     * 光照归一化
     * @param face 输入的人脸图像
     * @return 归一化后的人脸图像
     */
    private static Mat normalizeIllumination(Mat face) {
        Mat normalized = new Mat();

        // 创建CLAHE对象
        CLAHE clahe = Imgproc.createCLAHE();
        clahe.setClipLimit(2.0);
        clahe.setTilesGridSize(new Size(8, 8));

        // 应用CLAHE
        clahe.apply(face, normalized);

        // 应用高斯滤波去除噪点
        Imgproc.GaussianBlur(normalized, normalized, new Size(3, 3), 0);

        // 应用双边滤波保持边缘
        // 修改参数:d=5, sigmaColor=75, sigmaSpace=75
        // 确保输入图像是8位单通道或3通道图像
        Mat bilateralResult = new Mat();
        Imgproc.bilateralFilter(normalized, bilateralResult, 5, 75, 75);
        bilateralResult.copyTo(normalized);

        return normalized;
    }

    /**
     * 比较两张人脸图片的相似度-直方图
     * @param face1 第一张人脸图片
     * @param face2 第二张人脸图片
     * @return 相似度得分(0-100,越高越相似)
     */
    public static double compareFaces(Mat face1, Mat face2) {
        // 确保两张图片大小相同
        if (face1.size() != face2.size()) {
            Imgproc.resize(face2, face2, face1.size());
        }

        // 将图片分成3x3的网格
        int rows = face1.rows();
        int cols = face1.cols();
        int cellRows = rows / 3;
        int cellCols = cols / 3;

        double totalSimilarity = 0;
        int validCells = 0;

        // 对每个网格计算直方图相似度
        for (int i = 0; i < 3; i++) {
            for (int j = 0; j < 3; j++) {
                // 提取当前网格
                Mat cell1 = face1.submat(
                    i * cellRows, (i + 1) * cellRows,
                    j * cellCols, (j + 1) * cellCols
                );
                Mat cell2 = face2.submat(
                    i * cellRows, (i + 1) * cellRows,
                    j * cellCols, (j + 1) * cellCols
                );

                // 计算当前网格的直方图
                Mat hist1 = new Mat();
                Mat hist2 = new Mat();
                MatOfFloat ranges = new MatOfFloat(0f, 256f);
                MatOfInt histSize = new MatOfInt(64); // 使用更少的bin数量

                List<Mat> images1 = Arrays.asList(cell1);
                List<Mat> images2 = Arrays.asList(cell2);

                Imgproc.calcHist(images1, new MatOfInt(0), new Mat(), hist1, histSize, ranges);
                Imgproc.calcHist(images2, new MatOfInt(0), new Mat(), hist2, histSize, ranges);

                // 归一化直方图
                Core.normalize(hist1, hist1, 0, 1, Core.NORM_MINMAX);
                Core.normalize(hist2, hist2, 0, 1, Core.NORM_MINMAX);

                // 计算直方图相似度
                double similarity = Imgproc.compareHist(hist1, hist2, Imgproc.HISTCMP_CORREL);

                // 只考虑相似度大于0的部分
                if (similarity > 0) {
                    totalSimilarity += similarity;
                    validCells++;
                }
            }
        }

        // 计算平均相似度
        double avgSimilarity = validCells > 0 ? totalSimilarity / validCells : 0;

        // 使用更严格的转换函数
        double score;
        if (avgSimilarity < 0) {
            score = 0;
        } else {
            // 使用更严格的非线性映射
            score = Math.min(Math.pow(avgSimilarity, 1.6) * 200,100);
        }

        return score;
    }

    /**
     * 计算两张图片的模板匹配相似度
     * @param face1 第一张人脸图片
     * @param face2 第二张人脸图片
     * @return 相似度得分(0-100,越高越相似)
     */
    public static double compareFacesTemplate(Mat face1, Mat face2) {
        // 确保两张图片大小相同
        if (face1.size() != face2.size()) {
            Imgproc.resize(face2, face2, face1.size());
        }

        // 创建结果矩阵
        Mat result = new Mat();

        // 执行模板匹配
        Imgproc.matchTemplate(face1, face2, result, Imgproc.TM_CCOEFF_NORMED);

        // 获取最佳匹配位置
        Core.MinMaxLocResult mmr = Core.minMaxLoc(result);
        double similarity = mmr.maxVal;

        // 将相似度转换为0-100的分数
        return Math.max(0, Math.min(100, similarity * 200));
    }

//    /** 精度不够
//     * 使用LBP特征比较人脸相似度
//     * @param face1 第一张人脸图片
//     * @param face2 第二张人脸图片
//     * @return 相似度得分(0-100,越高越相似)
//     */
//    private static double compareFacesLBP(Mat face1, Mat face2) {
//        // 确保两张图片大小相同
//        if (face1.size() != face2.size()) {
//            Imgproc.resize(face2, face2, face1.size());
//        }
//
//        // 计算LBP特征
//        Mat lbp1 = new Mat(face1.size(), CvType.CV_8UC1);
//        Mat lbp2 = new Mat(face2.size(), CvType.CV_8UC1);
//
//        // 计算LBP特征图
//        for (int i = 1; i < face1.rows() - 1; i++) {
//            for (int j = 1; j < face1.cols() - 1; j++) {
//                double center = face1.get(i, j)[0];
//                byte lbp = 0;
//                // 3x3邻域
//                if (face1.get(i-1, j-1)[0] > center) lbp |= 1;
//                if (face1.get(i-1, j)[0] > center) lbp |= 2;
//                if (face1.get(i-1, j+1)[0] > center) lbp |= 4;
//                if (face1.get(i, j+1)[0] > center) lbp |= 8;
//                if (face1.get(i+1, j+1)[0] > center) lbp |= 16;
//                if (face1.get(i+1, j)[0] > center) lbp |= 32;
//                if (face1.get(i+1, j-1)[0] > center) lbp |= 64;
//                if (face1.get(i, j-1)[0] > center) lbp |= 128;
//                lbp1.put(i, j, lbp);
//            }
//        }
//
//        for (int i = 1; i < face2.rows() - 1; i++) {
//            for (int j = 1; j < face2.cols() - 1; j++) {
//                double center = face2.get(i, j)[0];
//                byte lbp = 0;
//                if (face2.get(i-1, j-1)[0] > center) lbp |= 1;
//                if (face2.get(i-1, j)[0] > center) lbp |= 2;
//                if (face2.get(i-1, j+1)[0] > center) lbp |= 4;
//                if (face2.get(i, j+1)[0] > center) lbp |= 8;
//                if (face2.get(i+1, j+1)[0] > center) lbp |= 16;
//                if (face2.get(i+1, j)[0] > center) lbp |= 32;
//                if (face2.get(i+1, j-1)[0] > center) lbp |= 64;
//                if (face2.get(i, j-1)[0] > center) lbp |= 128;
//                lbp2.put(i, j, lbp);
//            }
//        }
//
//        // 计算LBP直方图
//        Mat hist1 = new Mat();
//        Mat hist2 = new Mat();
//        MatOfFloat ranges = new MatOfFloat(0f, 256f);
//        MatOfInt histSize = new MatOfInt(256);
//
//        List<Mat> images1 = Arrays.asList(lbp1);
//        List<Mat> images2 = Arrays.asList(lbp2);
//
//        Imgproc.calcHist(images1, new MatOfInt(0), new Mat(), hist1, histSize, ranges);
//        Imgproc.calcHist(images2, new MatOfInt(0), new Mat(), hist2, histSize, ranges);
//
//        // 归一化直方图
//        Core.normalize(hist1, hist1, 0, 1, Core.NORM_MINMAX);
//        Core.normalize(hist2, hist2, 0, 1, Core.NORM_MINMAX);
//
//        // 计算直方图相似度
//        double similarity = Imgproc.compareHist(hist1, hist2, Imgproc.HISTCMP_CORREL);
//
//        // 计算LBP特征图的差异
//        Mat diff = new Mat();
//        Core.absdiff(lbp1, lbp2, diff);
//        double totalPixels = lbp1.rows() * lbp1.cols();
//        double differentPixels = Core.countNonZero(diff);
//        double pixelDiffRatio = differentPixels / totalPixels;
//
//        // 结合直方图相似度和像素差异
//        double combinedSimilarity = similarity * (1 - pixelDiffRatio);
//
//        // 将相似度转换为0-100的分数
//        return Math.max(0, Math.min(100, (combinedSimilarity + 1) * 50));
//    }
//

    /**
     * 综合比较两张人脸图片的相似度
     * @param face1 第一张人脸图片
     * @param face2 第二张人脸图片
     * @return 相似度得分(0-100,越高越相似)
     */
    public static boolean compareFacesComprehensive(Mat face1, Mat face2) {
        // 计算直方图相似度
        double histSimilarity = compareFaces(face1, face2);

        // 计算模板匹配相似度
        double templateSimilarity = compareFacesTemplate(face1, face2);

        // 计算LBP特征相似度
        // double lbpSimilarity = compareFacesLBP(face1, face2);

        // 使用人脸关键点检测器比较人脸相似度
        //double facialLandmarksSimilarity = compareFacialLandmarks(face1, face2);

        // 大幅调整权重分配,主要依赖模板匹配
        double similarity = (histSimilarity * 0.3 +
                            templateSimilarity * 0.7);
        log.info("总体:"+similarity+"直方图:" + histSimilarity +
                "  模板匹配:" + templateSimilarity);

        // 使用更严格的非线性变换
        return checkSameFace(similarity);
    }

    /**
     * HOG(精准度不够,暂不使用)
     * @param point
     * @return
     */
//    private static double compareHOG(Mat face1, Mat face2) {
//        // 确保输入图像大小一致
//        if (face1.size() != face2.size()) {
//            Imgproc.resize(face2, face2, face1.size());
//        }
//
//        // 创建HOG描述符
//        HOGDescriptor hog = new HOGDescriptor(
//            new Size(48, 48),    // 更小的窗口大小
//            new Size(16, 16),    // blockSize
//            new Size(8, 8),      // blockStride
//            new Size(8, 8),      // cellSize
//            9                    // nbins
//        );
//
//        // 计算HOG特征
//        MatOfFloat descriptors1 = new MatOfFloat();
//        MatOfFloat descriptors2 = new MatOfFloat();
//
//        // 添加图像预处理
//        Mat preprocessed1 = new Mat();
//        Mat preprocessed2 = new Mat();
//
//        // 确保输入是灰度图
//        if (face1.channels() > 1) {
//            Imgproc.cvtColor(face1, preprocessed1, Imgproc.COLOR_BGR2GRAY);
//        } else {
//            face1.copyTo(preprocessed1);
//        }
//
//        if (face2.channels() > 1) {
//            Imgproc.cvtColor(face2, preprocessed2, Imgproc.COLOR_BGR2GRAY);
//        } else {
//            face2.copyTo(preprocessed2);
//        }
//
//        // 应用高斯模糊去噪
//        Imgproc.GaussianBlur(preprocessed1, preprocessed1, new Size(3, 3), 0);
//        Imgproc.GaussianBlur(preprocessed2, preprocessed2, new Size(3, 3), 0);
//
//        // 应用直方图均衡化增强对比度
//        Imgproc.equalizeHist(preprocessed1, preprocessed1);
//        Imgproc.equalizeHist(preprocessed2, preprocessed2);
//
//        hog.compute(preprocessed1, descriptors1);
//        hog.compute(preprocessed2, descriptors2);
//
//        // 将特征向量转换为Mat
//        Mat features1 = descriptors1.reshape(1, 1);
//        Mat features2 = descriptors2.reshape(1, 1);
//
//        // 特征归一化
//        Core.normalize(features1, features1, 0, 1, Core.NORM_MINMAX);
//        Core.normalize(features2, features2, 0, 1, Core.NORM_MINMAX);
//
//        // 计算多种相似度度量
//        double cosineSimilarity = calculateCosineSimilarity(features1, features2);
//        double euclideanDistance = Core.norm(features1, features2, Core.NORM_L2);
//        double euclideanSimilarity = 1.0 / (1.0 + euclideanDistance); // 转换为相似度
//
//        // 综合多种相似度度量
//        double combinedSimilarity = (cosineSimilarity * 0.6 + euclideanSimilarity * 0.4) * 100;
//
//        return combinedSimilarity;
//    }

//    private static double calculateCosineSimilarity(Mat features1, Mat features2) {
//        // 计算点积
//        double dotProduct = features1.dot(features2);
//
//        // 计算范数
//        double norm1 = Core.norm(features1, Core.NORM_L2);
//        double norm2 = Core.norm(features2, Core.NORM_L2);
//
//        // 计算余弦相似度
//        double similarity = dotProduct / (norm1 * norm2);
//
//        // 将相似度归一化到0-1范围
//        return (similarity + 1) / 2;
//    }
    static boolean checkSameFace(double point){
        if (point>50){
            return true;
        }
        return false;
    }



    public static void compareBySeetaface6(byte[] face1, byte[] face2) {
        String modelPath = "D:\\zjlWork\\faceRecognition\\demo-opencv\\models\\retinaface.pt";

    }
}

 虹软SDK

    /**
     * 调用虹软SDK进行人脸识别
     * @param file1
     * @param file2
     * @return
     */
    public static float faceCompare(File file1,File file2) throws FileNotFoundException {
        //从官网获取
        String appId = "填入你的appId";
        String sdkKey = "填入你的sdkKey";

        // 获取resources下libs目录的路径
        File libDir = ResourceUtils.getFile("classpath:libs");
        String libPath = libDir.getAbsolutePath();

        FaceEngine faceEngine = new FaceEngine(libPath);
        //激活引擎
        int errorCode = faceEngine.activeOnline(appId, sdkKey);

        if (errorCode != ErrorInfo.MOK.getValue() && errorCode != ErrorInfo.MERR_ASF_ALREADY_ACTIVATED.getValue()) {
            System.out.println("引擎激活失败");
        }


        ActiveFileInfo activeFileInfo=new ActiveFileInfo();
        errorCode = faceEngine.getActiveFileInfo(activeFileInfo);
        if (errorCode != ErrorInfo.MOK.getValue() && errorCode != ErrorInfo.MERR_ASF_ALREADY_ACTIVATED.getValue()) {
            System.out.println("获取激活文件信息失败");
        }

        //引擎配置
        EngineConfiguration engineConfiguration = new EngineConfiguration();
        engineConfiguration.setDetectMode(DetectMode.ASF_DETECT_MODE_IMAGE);
        engineConfiguration.setDetectFaceOrientPriority(DetectOrient.ASF_OP_ALL_OUT);
        engineConfiguration.setDetectFaceMaxNum(10);
        engineConfiguration.setDetectFaceScaleVal(16);
        //功能配置
        FunctionConfiguration functionConfiguration = new FunctionConfiguration();
        functionConfiguration.setSupportAge(true);
        functionConfiguration.setSupportFace3dAngle(true);
        functionConfiguration.setSupportFaceDetect(true);
        functionConfiguration.setSupportFaceRecognition(true);
        functionConfiguration.setSupportGender(true);
        functionConfiguration.setSupportLiveness(true);
        functionConfiguration.setSupportIRLiveness(true);
        engineConfiguration.setFunctionConfiguration(functionConfiguration);


        //初始化引擎
        errorCode = faceEngine.init(engineConfiguration);

        if (errorCode != ErrorInfo.MOK.getValue()) {
            System.out.println("初始化引擎失败");
        }


        //人脸检测
        ImageInfo imageInfo = getRGBData(file1);
        List<FaceInfo> faceInfoList = new ArrayList<FaceInfo>();
        errorCode = faceEngine.detectFaces(imageInfo.getImageData(), imageInfo.getWidth(), imageInfo.getHeight(), imageInfo.getImageFormat(), faceInfoList);
        System.out.println(faceInfoList);

        //特征提取
        FaceFeature faceFeature = new FaceFeature();
        errorCode = faceEngine.extractFaceFeature(imageInfo.getImageData(), imageInfo.getWidth(), imageInfo.getHeight(), imageInfo.getImageFormat(), faceInfoList.get(0), faceFeature);
        System.out.println("特征值大小:" + faceFeature.getFeatureData().length);

        //人脸检测2
        ImageInfo imageInfo2 = getRGBData(file2);
        List<FaceInfo> faceInfoList2 = new ArrayList<FaceInfo>();
        errorCode = faceEngine.detectFaces(imageInfo2.getImageData(), imageInfo2.getWidth(), imageInfo2.getHeight(),imageInfo2.getImageFormat(), faceInfoList2);
        System.out.println(faceInfoList2);

        //特征提取2
        FaceFeature faceFeature2 = new FaceFeature();
        errorCode = faceEngine.extractFaceFeature(imageInfo2.getImageData(), imageInfo2.getWidth(), imageInfo2.getHeight(), imageInfo2.getImageFormat(), faceInfoList2.get(0), faceFeature2);
        System.out.println("特征值大小:" + faceFeature2.getFeatureData().length);

        //特征比对
        FaceFeature targetFaceFeature = new FaceFeature();
        targetFaceFeature.setFeatureData(faceFeature.getFeatureData());
        FaceFeature sourceFaceFeature = new FaceFeature();
        sourceFaceFeature.setFeatureData(faceFeature2.getFeatureData());
        FaceSimilar faceSimilar = new FaceSimilar();

        errorCode = faceEngine.compareFaceFeature(targetFaceFeature, sourceFaceFeature, faceSimilar);

        System.out.println("相似度:" + faceSimilar.getScore());

        //设置活体测试
        errorCode = faceEngine.setLivenessParam(0.5f, 0.7f);
        //人脸属性检测
        FunctionConfiguration configuration = new FunctionConfiguration();
        configuration.setSupportAge(true);
        configuration.setSupportFace3dAngle(true);
        configuration.setSupportGender(true);
        configuration.setSupportLiveness(true);
        errorCode = faceEngine.process(imageInfo.getImageData(), imageInfo.getWidth(), imageInfo.getHeight(), imageInfo.getImageFormat(), faceInfoList, configuration);

//
//        //性别检测
//        List<GenderInfo> genderInfoList = new ArrayList<GenderInfo>();
//        errorCode = faceEngine.getGender(genderInfoList);
//        System.out.println("性别:" + genderInfoList.get(0).getGender());
//
//        //年龄检测
//        List<AgeInfo> ageInfoList = new ArrayList<AgeInfo>();
//        errorCode = faceEngine.getAge(ageInfoList);
//        System.out.println("年龄:" + ageInfoList.get(0).getAge());
//
//        //3D信息检测
//        List<Face3DAngle> face3DAngleList = new ArrayList<Face3DAngle>();
//        errorCode = faceEngine.getFace3DAngle(face3DAngleList);
//        System.out.println("3D角度:" + face3DAngleList.get(0).getPitch() + "," + face3DAngleList.get(0).getRoll() + "," + face3DAngleList.get(0).getYaw());
//
        //活体检测
        List<LivenessInfo> livenessInfoList = new ArrayList<LivenessInfo>();
        errorCode = faceEngine.getLiveness(livenessInfoList);
        System.out.println("活体:" + livenessInfoList.get(0).getLiveness());

//
//        //IR属性处理
//        ImageInfo imageInfoGray = getGrayData(new File("d:\\IR_480p.jpg"));
//        List<FaceInfo> faceInfoListGray = new ArrayList<FaceInfo>();
//        errorCode = faceEngine.detectFaces(imageInfoGray.getImageData(), imageInfoGray.getWidth(), imageInfoGray.getHeight(), imageInfoGray.getImageFormat(), faceInfoListGray);
//
//        FunctionConfiguration configuration2 = new FunctionConfiguration();
//        configuration2.setSupportIRLiveness(true);
//        errorCode = faceEngine.processIr(imageInfoGray.getImageData(), imageInfoGray.getWidth(), imageInfoGray.getHeight(), imageInfoGray.getImageFormat(), faceInfoListGray, configuration2);
//        //IR活体检测
//        List<IrLivenessInfo> irLivenessInfo = new ArrayList<>();
//        errorCode = faceEngine.getLivenessIr(irLivenessInfo);
//        System.out.println("IR活体:" + irLivenessInfo.get(0).getLiveness());
//
//        ImageInfoEx imageInfoEx = new ImageInfoEx();
//        imageInfoEx.setHeight(imageInfo.getHeight());
//        imageInfoEx.setWidth(imageInfo.getWidth());
//        imageInfoEx.setImageFormat(imageInfo.getImageFormat());
//        imageInfoEx.setImageDataPlanes(new byte[][]{imageInfo.getImageData()});
//        imageInfoEx.setImageStrides(new int[]{imageInfo.getWidth() * 3});
//        List<FaceInfo> faceInfoList1 = new ArrayList<>();
//        errorCode = faceEngine.detectFaces(imageInfoEx, DetectModel.ASF_DETECT_MODEL_RGB, faceInfoList1);
//
//        FunctionConfiguration fun = new FunctionConfiguration();
//        fun.setSupportAge(true);
//        errorCode = faceEngine.process(imageInfoEx, faceInfoList1, functionConfiguration);
//        List<AgeInfo> ageInfoList1 = new ArrayList<>();
//        int age = faceEngine.getAge(ageInfoList1);
//        System.out.println("年龄:" + ageInfoList1.get(0).getAge());
//
//        FaceFeature feature = new FaceFeature();
//        errorCode = faceEngine.extractFaceFeature(imageInfoEx, faceInfoList1.get(0), feature);


        //引擎卸载
        errorCode = faceEngine.unInit();

        return faceSimilar.getScore();
    }

Logo

DAMO开发者矩阵,由阿里巴巴达摩院和中国互联网协会联合发起,致力于探讨最前沿的技术趋势与应用成果,搭建高质量的交流与分享平台,推动技术创新与产业应用链接,围绕“人工智能与新型计算”构建开放共享的开发者生态。

更多推荐