java 人脸检测_Java+opencv实现人脸检测

importjava.awt.Graphics;importjava.awt.image.BufferedImage;importjavax.swing.JFrame;importjavax.swing.JPanel;importorg.opencv.core.Mat;importorg.opencv.core.MatOfDouble;importorg.opencv.core.MatOfRect;importorg.opencv.core.Point;importorg.opencv.core.Rect;importorg.opencv.core.Scalar;importorg.opencv.imgproc.Imgproc;importorg.opencv.objdetect.CascadeClassifier;importorg.opencv.objdetect.HOGDescriptor;importorg.opencv.videoio.VideoCapture;importorg.opencv.videoio.Videoio;public class FaceDetection extendsJPanel {privateBufferedImage mImg;private staticJFrame jFrame;//Mat转成image

privateBufferedImage matToImage(Mat mat){int dataSize =(int) (mat.total()*mat.channels());byte[] data=new byte[dataSize];

mat.get(0, 0,data);int type=mat.channels()==1?BufferedImage.TYPE_BYTE_GRAY:BufferedImage.TYPE_3BYTE_BGR;if(type==BufferedImage.TYPE_3BYTE_BGR){for(int i=0;i

data[i+0]=data[i+2];

data[i+2]=blue;

}

}//创建空的image

BufferedImage image=newBufferedImage(mat.cols(),mat.rows(),type);//帧数据拷贝

image.getRaster().setDataElements(0, 0, mat.cols(), mat.rows(), data);returnimage;

}/*** Jpanel调用repaint的时候会自动调用该绘图方法*/

public voidpaintComponent(Graphics g){if(mImg!=null){

g.drawImage(mImg,0, 0, mImg.getWidth(),mImg.getHeight(),this);

}

}static{

//System.loadLibrary(Core.NATIVE_LIBRARY_NAME);

System.load("D:/opencv/build/java/x64/opencv_java320.dll");

}public static void creatFrame(JPanel jPanel,int width,intheight){

jFrame= new JFrame("camera");

jFrame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

jFrame.setVisible(true);//将内容添加到JFrame

jFrame.setSize(width,height);

jFrame.setContentPane(jPanel);

}public static void main(String[] args) throwsException {//开启摄像头

VideoCapture capture=new VideoCapture(0);

FaceDetection jPanel=newFaceDetection();

creatFrame(jPanel,(int)capture.get(Videoio.CAP_PROP_FRAME_WIDTH),(int)capture.get(Videoio.CAP_PROP_FRAME_HEIGHT));

Mat mat=newMat();while(true){if(!capture.isOpened()){

System.out.println("camera is not open");

System.exit(0);

}

capture.read(mat);

jPanel.mImg=jPanel.matToImage(detectFace(mat));

jPanel.repaint();

}

}/*** opencv实现人脸识别

*@paramimg*/

public static Mat detectFace(Mat mat) throwsException

{//从配置文件lbpcascade_frontalface.xml中创建一个人脸识别器,该文件位于opencv安装目录中

CascadeClassifier faceDetector = new CascadeClassifier("D:/opencv/sources/data/haarcascades/haarcascade_frontalface_alt.xml");//在图片中检测人脸

MatOfRect faceDetections = newMatOfRect();

faceDetector.detectMultiScale(mat, faceDetections);

Rect[] rects=faceDetections.toArray();for(Rect rect : rects) {//标出脸

Imgproc.rectangle(mat,new Point(rect.x, rect.y), //标记框的左下点坐标

new Point(rect.x + rect.width, rect.y + rect.height), //标记框的右上点坐标

new Scalar(0, 255, 0), //颜色

2); //粗细

}returnmat;

}}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值