Java基于OpenCV检测实现人脸头像居中裁剪

实现思路:利用OpenCV检测图片中人脸的位置;根据人脸图像在图片的位置,实现居中裁剪。

一、OpenCV下载

下载网站:https://opencv.org/releases/

官网下载比较慢,可以使用IDM工具:

IDM工具下载链接:https://pan.baidu.com/s/1sAEJowbEfqwuV5mNtyVGDg  提取码:p4lv 

本文下载windows版本库。

下载安装后点击安装文件,进行安装。

如:

二、Java集成OpenCV

安装后,可以在opencv安装目录找到对应文件,引入java工程。

1.引入dll库

dll文件目录:opencv\build\java\x64\opencv_java412.dll

2.jar包

jar目录:opencv\build\java\opencv-412.jar

3.训练好的分类器文件

分类器文件目录:opencv\build\etc\haarcascades\haarcascade_frontalface_alt.xml

引入到java工程的目录可参考:

在工程的路径不是固定的,确保在代码中能加载到即可。

三、检测人脸位置步骤

步骤1.引入opencv 库 Window引入dll 绝对路径
步骤2.引入训练好的XML格式的分类器文件
步骤3.读取待处理的图片
步骤4.进行人脸检测。

主要代码:

        // 1.引入opencv 库 Window引入dll 绝对路径
        System.load(OPENCV_DLL_PATH);

        // 2.引入训练好的XML格式的分类器文件
        CascadeClassifier faceDetector = new CascadeClassifier(OPENCV_XML_PATH);
        if (faceDetector.empty()) {
            System.err.println("please import cascade classifier file");
            return null;
        }

        // 3.读取待处理的图片
        File imgFile = new File(imageFilePath);
        Mat image = Imgcodecs.imread(imgFile.getPath());


        // 4.进行人脸检测
        MatOfRect faceDetections = new MatOfRect();
        faceDetector.detectMultiScale(image, faceDetections);

四、人脸头像居中裁剪

思路:以检测的人脸框为中心Rect(x,y,w,h)放大。其中:x为裁剪矩形的x坐标,y为裁剪矩形的y坐标,w为裁剪矩形的宽,h为裁剪矩形的高。

记:原图的宽为W 高为H,宽度单侧增加:△W,则等比例放大后,单侧高度增加:△W * h / w

因为放大的图像边界不能超过原图的四个边界,所以:

向左:△W <= x  ;

向上:△W * h / w <=y ; 

向右:x+w+ △W<= W; 

向下:y+h+△W * h / w <=H

由上述四个条件,可以得到△W最大值为:x  ; W-x-w;  y*w/h;(H-h-y)*w/h 中的最小者。

故居中裁剪的矩形框为:Rect(x-△W,y-△W * h / w,w+2*△W,h+2*△W * h / w)。

代码:

/**
     * 计算居中裁剪框
     * 在原图边界范围内,以检测的人脸框为中心,向四周等比例放大,最大的裁剪框可保证人脸居中
     *
     * @param srcWidth  原始图像宽度
     * @param srcHeight 原始图像高度
     * @param rect      人脸框位置
     * @return 居中裁剪框
     */
    private static Rect estimateCenterCropBox(int srcWidth, int srcHeight, Rect rect) {
        System.out.println("estimateCenterCropBox ... ");
        int w0 = rect.x;
        int w1 = srcWidth - rect.x - rect.width;
        int w2 = (srcHeight - rect.y - rect.height) * rect.width / rect.height;
        int w3 = rect.width * rect.y / rect.height;

        if (w0 < 0 || w1 < 0 || w2 < 0 || w3 < 0) {
            return null;
        }
        int ret = w0;
        if (ret > w1) {
            ret = w1;
        }
        if (ret > w2) {
            ret = w2;
        }
        if (ret > w3) {
            ret = w3;
        }
        Rect centerRect = new Rect(rect.x - ret, rect.y - ret * rect.height / rect.width,
                rect.width + 2 * ret, rect.height + 2 * ret * rect.height / rect.width);

        return centerRect;
    }

五、完整代码

package com.yx.test.image;

import org.opencv.core.Mat;
import org.opencv.core.MatOfRect;
import org.opencv.core.Rect;
import org.opencv.core.Size;
import org.opencv.imgcodecs.Imgcodecs;
import org.opencv.imgproc.Imgproc;
import org.opencv.objdetect.CascadeClassifier;

import java.io.File;
import java.io.IOException;
import java.util.Iterator;

import javax.imageio.ImageIO;
import javax.imageio.stream.ImageInputStream;

/**
 * ImageUtil
 *
 * @author yx
 * @date 2019/12/11 21:14
 */
public class ImageUtil {
    /**
     * dll库路径,绝对路径,否则会提示报错:Exception in thread "main" java.lang.UnsatisfiedLinkError: Expecting an absolute path of the library: libs\opencv_java412.dll
     */
    private static final String OPENCV_DLL_PATH =
            "libs\\opencv_java412.dll";
    /**
     * xml训练文件
     */
    private static final String OPENCV_XML_PATH = "file/haarcascade_frontalface_alt.xml";

    public static void main(String[] args) throws IOException {
        detectFaceImage("file/333.jpg", "file/");
    }

    /**
     * @param imageFilePath 待处理图片路径
     * @param destDir       提前人脸后居中裁剪后的图片存储目录
     * @return 居中裁剪的图片路径
     */
    private static String[] detectFaceImage(String imageFilePath, String destDir) {
        if (!isPicture(imageFilePath)) {
            System.err.println("imageFilePath: " + imageFilePath + " is not a image!");
            return null;
        }
        File dir = new File(destDir);
        if (!dir.exists()) {
            if (!dir.mkdirs()) {
                System.err.println("mkdir " + destDir + " failed");
                return null;
            }
        } else {
            if (dir.isFile()) {
                System.err.println("destDir is not dir");
                return null;
            }
        }

        System.out.println("start face detecting ...");
        // 1.引入opencv 库 Window引入dll 绝对路径
        System.out.println("load dll file ...");
        System.load(OPENCV_DLL_PATH);

        // 2.引入训练好的XML格式的分类器文件
        System.out.println("load xml file ...");
        CascadeClassifier faceDetector = new CascadeClassifier(OPENCV_XML_PATH);
        if (faceDetector.empty()) {
            System.err.println("please import cascade classifier file");
            return null;
        }

        // 3.读取待处理的图片
        File imgFile = new File(imageFilePath);
        Mat image = Imgcodecs.imread(imgFile.getPath());

        int srcWidth = image.width();
        int srcHeight = image.height();

        // 4.进行人脸检测
        MatOfRect faceDetections = new MatOfRect();
        faceDetector.detectMultiScale(image, faceDetections);
        Rect[] rectFace = faceDetections.toArray();
        System.out.println(String.format("face detected count: %s", rectFace.length));

        String[] targetFiles = new String[rectFace.length];
        // 5.裁剪检测到的人脸图片
        for (int i = 0; i < rectFace.length; i++) {
            Rect rect = rectFace[i];
            System.out.println(
                    "rect[" + i + "]=[" + rect.x + "," + rect.y + "," + rect.width + "," +
                            rect.height + "]");
            // 计算居中裁剪框
            Rect centerCropBox = estimateCenterCropBox(srcWidth, srcHeight, rect);
            // 裁剪框
            System.out.println(
                    "rect[" + i + "]=[" + centerCropBox.x + "," +
                            centerCropBox.y + "," +
                            centerCropBox.width + "," +
                            centerCropBox.height + "]");
            targetFiles[i] = destDir + File.separator + i + getImageType(imgFile);
            // 裁剪
            cutCenterImage(imgFile.getPath(), targetFiles[i], centerCropBox);
        }
        return targetFiles;
    }

    /**
     * @param filePath 文件路径
     * @return 是否是图片
     */
    public static boolean isPicture(String filePath) {
        File file = new File(filePath);
        if (file.exists() && file.isFile()) {
            ImageInputStream iis = null;
            try {
                iis = ImageIO.createImageInputStream(file);
            } catch (IOException e) {
                return false;
            }
            Iterator iter = ImageIO.getImageReaders(iis);
            if (iter.hasNext()) {
                return true;
            }
        }
        return false;
    }

    /**
     * 获取文件后缀不带.
     *
     * @param file 文件后缀名
     * @return
     */
    private static String getImageType(File file) {
        if (file != null && file.exists() && file.isFile()) {
            String fileName = file.getName();
            int index = fileName.lastIndexOf(".");
            if (index != -1 && index < fileName.length() - 1) {
                return fileName.substring(index);
            }
        }
        return null;
    }

    /**
     * 计算居中裁剪框
     * 在原图边界范围内,以检测的人脸框为中心,向四周等比例放大,最大的裁剪框可保证人脸居中
     *
     * @param srcWidth  原始图像宽度
     * @param srcHeight 原始图像高度
     * @param rect      人脸框位置
     * @return 居中裁剪框
     */
    private static Rect estimateCenterCropBox(int srcWidth, int srcHeight, Rect rect) {
        System.out.println("estimateCenterCropBox ... ");
        int w0 = rect.x;
        int w1 = srcWidth - rect.x - rect.width;
        int w2 = (srcHeight - rect.y - rect.height) * rect.width / rect.height;
        int w3 = rect.width * rect.y / rect.height;

        if (w0 < 0 || w1 < 0 || w2 < 0 || w3 < 0) {
            return null;
        }
        int ret = w0;
        if (ret > w1) {
            ret = w1;
        }
        if (ret > w2) {
            ret = w2;
        }
        if (ret > w3) {
            ret = w3;
        }

        return new Rect(rect.x - ret, rect.y - ret * rect.height / rect.width,
                rect.width + 2 * ret, rect.height + 2 * ret * rect.height / rect.width);
    }

    /**
     * @param oriImg  原始图像
     * @param outFile 裁剪的图像输出路径
     * @param rect    剪辑矩形区域
     */
    private static void cutCenterImage(String oriImg, String outFile, Rect rect) {
        System.out.println("cutCenterImage ...");
        // 原始图像
        Mat image = Imgcodecs.imread(oriImg);
        // Mat sub = new Mat(image,rect);
        Mat sub = image.submat(rect);
        Mat mat = new Mat();
        Size size = new Size(rect.width, rect.height);
        // 将人脸进行截图
        Imgproc.resize(sub, mat, size);
        // 截图保存到outFile
        Imgcodecs.imwrite(outFile, mat);
        System.out.println(String.format("cutCenterImage done! outPutFile: %s", outFile));
    }

}

六.运行效果

原图:

人脸居中裁剪:

实现了将原图中在中上位置的人脸裁剪到图片中间。

ps:目前程序只支持图片中有且仅有一个人脸的图片,对于图片中有多个人脸或者没有人脸的情况会存在一些问题。

评论 4
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

IT_熊

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值