Java-OpenCV人脸检测

Java-OpenCV人脸检测,基于haarCascade

依赖:Eclipse-win32,JRE1.8-x86(为了对应OpenCV版本,1.7版本过低),OpenCV-342-java-x86

模型:haarcascade_frontalface_alt2.xml

第一部分 库配置

1.1 Eclipse添加OpenCV库

Window -> Preferences -> Java -> Build Path -> User Libraries -> New... -> OpenCV-342 -> Add External JARS... -> OpenCV-342-java_path-opencv-342.jar -> Native library location -> Edit... -> OpenCV-342-java_dll_path-x86-opencv_java342.dll -> Done!

1.2 Java Projects配置OpenCV库

右键项目 -> Build Path -> Configure Build Path... -> Libraries -> Add Library -> User Library -> Next -> OpenCV-342 -> Done!

第二部分 代码展示

package com.OpencvTest;

import org.opencv.core.Core;
import org.opencv.core.Mat;
import org.opencv.core.MatOfRect;
import org.opencv.core.Rect;
import org.opencv.videoio.VideoCapture;
import org.opencv.highgui.HighGui;
import org.opencv.imgproc.Imgproc;
import org.opencv.objdetect.CascadeClassifier;
import org.opencv.core.Scalar;

public class OpencvTest {
	public static void main(String[] args) {
		//load OpenCV library
		System.loadLibrary(Core.NATIVE_LIBRARY_NAME);
		
		//load haarCascade model
		CascadeClassifier cascade = new CascadeClassifier();
		cascade.load("haarcascade_frontalface_alt2.xml");
		Scalar scalar = new Scalar(0, 255, 0);
		//initial faceRect
		MatOfRect faces = new MatOfRect();
		
		//initial video capture
		VideoCapture cap = new VideoCapture(0);
		if(!cap.isOpened()){
			System.out.println("can not open cam");
			return;
		}
		Mat frame = new Mat();
		Mat gray = new Mat();
		
		while(true) {
			cap.read(frame);
			if(frame.empty()){
				System.out.println("can not read image");
				break;
			}
			
			//convert BGR to GRAY
			Imgproc.cvtColor(frame, gray, Imgproc.COLOR_BGR2GRAY);
			
			//face detection
			cascade.detectMultiScale(gray, faces);
			
			//faceRect to array
			Rect[] facesArray = faces.toArray();
			
			//draw and show
			for(int i = 0;i<facesArray.length;i++){
				Imgproc.rectangle(frame, facesArray[i].tl(), facesArray[i].br(), scalar, 2);
			}
			HighGui.imshow("test", frame);
			HighGui.waitKey(1);
			
		}
		//release
		faces.release();
		cap.release();
		frame.release();
		gray.release();
		
		return;
	}
}

第三部分 结果展示

第四部分 参考

http://opencv.org

 

任何问题请加唯一QQ2258205918(名称samylee)!

唯一VX:samylee_csdn

 

©️2020 CSDN 皮肤主题: 编程工作室 设计师:CSDN官方博客 返回首页