一、功能描述:
人物头像识别,识别图片中的是否含有人物头像。
二、准备工作:
- 创建需要识别的图片目录 ,如F:/img,链接中files\img中为示例图片。
- 导入所需jar包,见files\jar。
- 新建依赖文件haarcascade_frontalface_default.xml,见files\haarcascade_frontalface_default.xml
- 链接:https://pan.baidu.com/s/1ql363GCpwtIx6N1BPetrzQ 提取码:fhew
三、代码:
package com.test.face;import java.awt.Rectangle;
import java.awt.image.BufferedImage;
import java.io.File;
import java.util.List;import javax.imageio.ImageIO;import detection.Detector;/** * 功能: 人物头像识别* */
public class FaceRecognition {public static void main(String[] args) {try {findFaces();} catch (Exception e) {e.printStackTrace();}
}public static void findFaces() throws Exception { String fileName1="F:/img/1.jpg"; String fileName2="F:/img/2.jpg"; String fileName3="F:/img/3.jpg"; String fileName4="F:/img/4.jpg"; Detector detector= Detector.create("src/haarcascade_frontalface_default.xml"); BufferedImage bi1=ImageIO.read(new File(fileName1)); BufferedImage bi2=ImageIO.read(new File(fileName2)); BufferedImage bi3=ImageIO.read(new File(fileName3)); BufferedImage bi4=ImageIO.read(new File(fileName4));List<Rectangle> res1=detector.getFaces(bi1, 2, 1.25f, 0.1f,3,true); System.out.println(res1); List<Rectangle> res2=detector.getFaces(bi2, 2, 1.25f, 0.1f,3,true); System.out.println(res2); List<Rectangle> res3=detector.getFaces(bi3, 2, 1.25f, 0.1f,3,true); System.out.println(res3); List<Rectangle> res4=detector.getFaces(bi4, 2, 1.25f, 0.1f,3,true); System.out.println(res4); }
}
返回结果说明:
List:为图片中头像出现的区域,包括起始坐标(x,y)以及对应的宽和高。可见console中第1、3张图片包含人物头像。
如果想要标记所识别的区域,代码如下:
/** * 这里是遍历图片的像素,因为要处理图片的背色,所以要把指定像素上的颜色换成目标颜色 * 这里 是一个二层循环,遍历长和宽上的每个像素 */for (int i = res1.get(0).x; i < res1.get(0).width; i++){for (int j = res1.get(0).y; j < res1.get(0).height; j++){bi1.setRGB(i, j, 0xffffff);}}FileOutputStream ops = new FileOutputStream(new File("F:/img/new_1.jpg"));ImageIO.write(bi1, "jpg", ops);ops.flush();ops.close();
四、测试:
执行main方法,结果见console。
如果加入标记所识别的区域的代码,F:/img下会生成新的以new_开头的标记后的图片。