package com.yida.data.user.util;

import cn.hutool.core.io.FileUtil;
import nu.pattern.OpenCV;
import org.opencv.core.Mat;
import org.opencv.core.MatOfRect;
import org.opencv.core.Rect;
import org.opencv.imgcodecs.Imgcodecs;
import org.opencv.imgproc.Imgproc;
import org.opencv.objdetect.CascadeClassifier;

import java.io.InputStream;

public class FaceUtil {

    static CascadeClassifier faceDetector = null;

    static {
        OpenCV.loadLocally();
        InputStream stream = FaceUtil.class.getClassLoader().getResourceAsStream("opencv/face.xml");
        faceDetector = new CascadeClassifier(FileUtil.writeFromStream(stream,
                com.yida.data.common.core.utils.FileUtil.getRandomPath("xml")).getPath());
    }

    /**
     * 判断图片是否包含人脸
     *
     * @param path
     * @return
     */
    public static Boolean containsFace(String path) {

        Mat image = Imgcodecs.imread(path);
        Mat rgb = new Mat();
        // 灰度化
        Imgproc.cvtColor(image, rgb, Imgproc.COLOR_BGR2RGB);
        MatOfRect faceDetections = new MatOfRect();
        faceDetector.detectMultiScale(image, faceDetections);
        Rect[] rects = faceDetections.toArray();
        return rects.length > 0;
    }
}
