Hello! This is a simple tutorial on face detection iin Java. The first step will be to download OpenCV from their website. Their website can easily be accessed from google. First, we need to add a class called Mat2Image. This class simply sets up our video capture device. It can be downloaded here! First we make the class that sets up our video capture device. This, unlike the Mat2Image, creates the capture device, instead of creating the Matrix, or Mat. So, first, we type the following code:
This loads the native libraries. Now, we load the Cascade classifiers. This loads the XML file that will tell opencv how to find points on someone’s face. To do this, we type:
CascadeClassifier face_cascade =new CascadeClassifier(“C:/Users/Squiva/Desktop/openCV/opencv/sources/data/haarcascades/haarcascade_frontalface_alt.xml”);
Now that we have loaded our Cascade classifier, we can instantiate the video capture device.
Mat2Imag m2i = new Mat2Imag();
After this, we have to open our capture device
cap = new VideoCapture();
Ok, now this gets complicated. We have to create a method that returns a BufferedImage. In that method, we type
This will link our video capture device with our Mat, or Matrix. Now, we can read the data fom the video capture device, we must detect the faces. Then, we draw a circle around each face. NOTE: mGrey is a new Mat. This grey-scale Mat will help train our Cascade classifier.
MatOfRect faces = new MatOfRect();
Imgproc.cvtColor(m2i.mat, mGrey, Imgproc.COLOR_BGR2GRAY);
Imgproc.equalizeHist( mGrey, mGrey );
Point center= new Point(rect.x + rect.width*0.5, rect.y + rect.height*0.5 );
Imgproc.ellipse( m2i.mat, center, new Size( rect.width*0.5, rect.height*0.5), 0, 0, 360, new Scalar( 255, 0, 255 ), 4, 8, 0 );
Next, we simply return the Mat.
The rest if fairly simle. We just create a JFrame, instaniate the class where we did everything above in [cap], and type:
g.drawImage(cap.frame(), 0, 0, getWidth() * 3, getHeight() * 3, null);
Next, we call the repaint method, and we are done!