How to detect face in java using OpenCV

Hello everyone! Learn how to detect a face in an image using OpenCV in Java. Firstly, you need to download the open-source OpenCV library. Then you have to add the libraries to your code. Follow certain steps to link your code with external libraries.

  1. Open your source code.
  2. Right-click on your source file.
  3. Click on the build path option.
  4. Select the configure build path option.
  5. Click on the Libraries option.
  6. Then select add external library jar’s.
  7. Build Native library path.

Learn how to detect a face in Java using OpenCV

package jyothi;
import org.opencv.core.Core; 
import org.opencv.core.Mat; 
import org.opencv.core.MatOfRect; 
import org.opencv.core.Point; 
import org.opencv.core.Rect; 
import org.opencv.core.Scalar; 
import org.opencv.imgcodecs.Imgcodecs; 
import org.opencv.imgproc.Imgproc; 
import org.opencv.objdetect.CascadeClassifier;
public class open {

  public static void main(String[] args) {  
          System.loadLibrary( Core.NATIVE_LIBRARY_NAME ); 
              CascadeClassifier fd = new CascadeClassifier(); 
            fd.load("/jyothi/images/i1.xml");  
            Mat img = Imgcodecs.imread("/jyothi/images/i.jpg"); 
            MatOfRect Detect = new MatOfRect(); 
            fd.detectMultiScale(img,faceDetect);  
            for (Rect rect : faceDetect.toArray()) 
            { 
                Imgproc.rectangle(img, new Point(rect.x, rect.y), 
                 new Point(rect.x + rect.width, rect.y + rect.height), 
                                               new Scalar(0, 255, 0)); 
            } 
            String f = "i.jpg"; 
            Imgcodecs.imwrite("/jyothi/images/i.jpg", img);		 
            }     
    

  }


Firstly, import all the required packages into the source code.
Then copy the XML file and image to the directory in which your source code is present.
Create a Mat object and read the image that is stored in the image file. And using the MatOfRect class object, use the method detectMultiscale method and pass the image object.
And when the faces are detected set the rectangles by defining the dimensions.
Finally, write back the image to the image file bypassing the file path. The code will generate an image with faces detected and representing them in rectangles boxes with the dimensions that are set by us.

I hope the explanation is clear and the code is clear. It can be done within few steps.

Also, read:

How to show image in Java using OpenCV

Leave a Reply

Your email address will not be published. Required fields are marked *