In this tutorial I’m going to explain how to write a simple
java program for face detection using JavaCV.
Prerequisites
- Install NetBeans IDE with the appropriate JDK (7 or above) from here.
- Install OpenCV from here.
- Download and extract JavaCV from here.
Steps
- Run NetBeans and create a new java project.
- Then add relevant JavaCV libraries in to your project. (i.e. compatible to your platform, etc)
- As this is for a simple demonstration you can add a new JFrame form in to your project and add a button in to the form.
- Go to the source view of the form and add following imports in to your program. import static org.bytedeco.javacpp.opencv_core.*;
- Inside the button action event add following java code (Refer the comments inline to better understand the code)
import static org.bytedeco.javacpp.opencv_highgui.*;
import org.bytedeco.javacpp.opencv_objdetect.CvHaarClassifierCascade;
import static org.bytedeco.javacpp.opencv_objdetect.*;
//adding the path to the referring video
CvCapture capture=cvCreateFileCapture("src//Video.mp4");
IplImage frame = null;
for(;;)
{
frame=cvQueryFrame(capture);
//adding the path to haarcascade_frontalface_alt.xml file CvHaarClassifierCascade cascade = new CvHaarClassifierCascade(cvLoad(<<path>>\\opencv\\sources\\data\\haarcascades\\haarcascade_frontalface_alt.xml"));
CvMemStorage storage = cvCreateMemStorage(0);
CvSeq sign = cvHaarDetectObjects(frame, cascade, storage, 1.5, 3, CV_HAAR_SCALE_IMAGE);
int total_Faces = sign.total(); //showing the detected faces inside a RED colored rectangle
for(int i = 0; i < total_Faces; i++){
CvRect r = new CvRect(cvGetSeqElem(sign, i));
cvRectangle (frame,cvPoint(r.x(), r.y()), cvPoint(r.width() + r.x(),
r.height() + r.y()), CvScalar.RED, 2, CV_AA, 0);
}
cvClearMemStorage(storage);
//Show the video with the detected faces
cvShowImage("Video",frame);
char
c=(char)cvWaitKey(30);
if(c==27)break;
}
cvDestroyWindow("Image");cvReleaseCapture(capture); |