DZone
Thanks for visiting DZone today,
Edit Profile
  • Manage Email Subscriptions
  • How to Post to DZone
  • Article Submission Guidelines
Sign Out View Profile
  • Post an Article
  • Manage My Drafts
Over 2 million developers have joined DZone.
Log In / Join
Please enter at least three characters to search
Refcards Trend Reports
Events Video Library
Refcards
Trend Reports

Events

View Events Video Library

Zones

Culture and Methodologies Agile Career Development Methodologies Team Management
Data Engineering AI/ML Big Data Data Databases IoT
Software Design and Architecture Cloud Architecture Containers Integration Microservices Performance Security
Coding Frameworks Java JavaScript Languages Tools
Testing, Deployment, and Maintenance Deployment DevOps and CI/CD Maintenance Monitoring and Observability Testing, Tools, and Frameworks
Culture and Methodologies
Agile Career Development Methodologies Team Management
Data Engineering
AI/ML Big Data Data Databases IoT
Software Design and Architecture
Cloud Architecture Containers Integration Microservices Performance Security
Coding
Frameworks Java JavaScript Languages Tools
Testing, Deployment, and Maintenance
Deployment DevOps and CI/CD Maintenance Monitoring and Observability Testing, Tools, and Frameworks

The software you build is only as secure as the code that powers it. Learn how malicious code creeps into your software supply chain.

Apache Cassandra combines the benefits of major NoSQL databases to support data management needs not covered by traditional RDBMS vendors.

Generative AI has transformed nearly every industry. How can you leverage GenAI to improve your productivity and efficiency?

Modernize your data layer. Learn how to design cloud-native database architectures to meet the evolving demands of AI and GenAI workloads.

Related

  • How to Introduce a New API Quickly Using Micronaut
  • Introducing Graph Concepts in Java With Eclipse JNoSQL
  • Using Java Stream Gatherers To Improve Stateful Operations
  • How to Merge HTML Documents in Java

Trending

  • How to Merge HTML Documents in Java
  • Developers Beware: Slopsquatting and Vibe Coding Can Increase Risk of AI-Powered Attacks
  • Event Driven Architecture (EDA) - Optimizer or Complicator
  • Using Python Libraries in Java
  1. DZone
  2. Coding
  3. Java
  4. Facial Recognition Using Java

Facial Recognition Using Java

Learn how to use the Sarxos library and the Openimaj library in order to perform facial recognition on images from a webcam.

By 
Anurag Jain user avatar
Anurag Jain
·
Aug. 01, 17 · Tutorial
Likes (4)
Comment
Save
Tweet
Share
47.6K Views

Join the DZone community and get the full member experience.

Join For Free

In this post, we will learn how to extract faces out of an image from a webcam. We will make use of two libraries: Sarxos and Openimaj.

  • Language used: Java

  • Program used: FaceDetector.java  

  • Git repo: Link

  • Website: Link

Here's our POM dependency: 

<dependency>
	<groupId>org.openimaj</groupId>
	<artifactId>image-feature-extraction</artifactId>
	<version>1.3.5</version>
</dependency>
<dependency>
	<artifactId>faces</artifactId>
	<groupId>org.openimaj</groupId>
	<version>1.3.5</version>
	<scope>compile</scope>
</dependency>
<dependency>
	<groupId>com.github.sarxos</groupId>
	<artifactId>webcam-capture</artifactId>
	<version>0.3.11</version>
	<scope>test</scope>
</dependency>  

These are our variables:

      private static final long serialVersionUID = 1L;  
      private static final HaarCascadeDetector detector = new HaarCascadeDetector();  
      private Webcam webcam = null;  
      private BufferedImage img= null;  
      private List<DetectedFace> faces = null;  

Main method:

 public static void main(String[] args) throws IOException {
  new FaceDetector().detectFace();
 }

Using the Sarxos Library

We create an object with the FaceDetector class, which classes the default constructor. Then, we call the detectFace method of this class.

FaceDetector constructor:

      public FaceDetector() throws IOException {
       webcam = Webcam.getDefault();
       webcam.setViewSize(WebcamResolution.VGA.getSize());
       webcam.open(true);
       img = webcam.getImage();
       webcam.close();
       ImagePanel panel = new ImagePanel(img);
       panel.setPreferredSize(WebcamResolution.VGA.getSize());
       add(panel);
       setTitle("Face Recognizer");
       setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
       pack();
       setLocationRelativeTo(null);
       setVisible(true);
      }

How it works:

  1. Use the Sarxos library for webcam here.

  2. Create a webcam object and set the viewsize.

  3. Open the webcam using the open method.

  4. Take the image from the webcam and store it in a BufferedImage object named img.

  5. Close the webcam and pass the image obtained in the ImagePanel class, which will then be added to Frame.

  6. Show the frame to the user with the webcam image that will be processed.

Using the Openimaj Library

detectFace method:

      public void detectFace() {
       JFrame fr = new JFrame("Discovered Faces");
       faces = detector.detectFaces(ImageUtilities.createFImage(img));
       if (faces == null) {
        System.out.println("No faces found in the captured image");
        return;
       }
       Iterator < DetectedFace > dfi = faces.iterator();
       while (dfi.hasNext()) {
        DetectedFace face = dfi.next();
        FImage image1 = face.getFacePatch();
        ImagePanel p = new ImagePanel(ImageUtilities.createBufferedImage(image1));
        fr.add(p);
       }
       fr.setLayout(new FlowLayout(0));
       fr.setSize(500, 500);
       fr.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
       fr.setVisible(true);
      }

How it works:

  1. Use the Ppenimaj library for face detection.

  2. Create a new Frame that will show the results.

  3. Use the detectFaces method of the HaarCascadeDetector class object detector, passing the image to be processed. ImageUtilities is used to create FImage out of BufferedImage.

  4. If no face is found in the image, an error message is returned.

  5. Otherwise, iterate through each face and retrieve the faces using the getFacePatch method.

  6. Use the createBufferedImage method of ImageUtilities class again — this time, to get a BufferedImage out of FImage.

  7. Add all the faces to the resulting frame.

ImagePanel Class:

 package com.cooltrickshome;
 import java.awt.Dimension;
 import java.awt.Graphics;
 import java.awt.Image;
 import javax.swing.ImageIcon;
 import javax.swing.JPanel;
 class ImagePanel
 extends JPanel {
  private Image img;
  public ImagePanel(String img) {
   this(new ImageIcon(img).getImage());
  }
  public ImagePanel(Image img) {
   this.img = img;
   Dimension size = new Dimension(img.getWidth(null), img.getHeight(null));
   setPreferredSize(size);
   setMinimumSize(size);
   setMaximumSize(size);
   setSize(size);
   setLayout(null);
  }
  public void paintComponent(Graphics g) {
   g.drawImage(this.img, 0, 0, null);
  }
 }

How it works:

  1. This is used to show the image on a panel.

Output:

Full Program

FaceDetector.java:

 package com.cooltrickshome;
 /**  
  * Reference:  
  * https://github.com/sarxos/webcam-capture/tree/master/webcam-capture-examples/webcam-capture-detect-face  
  * http://openimaj.org/  
  */
 import java.awt.FlowLayout;
 import java.awt.image.BufferedImage;
 import java.io.IOException;
 import java.util.Iterator;
 import java.util.List;
 import javax.swing.JFrame;
 import org.openimaj.image.FImage;
 import org.openimaj.image.ImageUtilities;
 import org.openimaj.image.processing.face.detection.DetectedFace;
 import org.openimaj.image.processing.face.detection.HaarCascadeDetector;
 import com.github.sarxos.webcam.Webcam;
 import com.github.sarxos.webcam.WebcamResolution;
 public class FaceDetector extends JFrame {
  private static final long serialVersionUID = 1 L;
  private static final HaarCascadeDetector detector = new HaarCascadeDetector();
  private Webcam webcam = null;
  private BufferedImage img = null;
  private List < DetectedFace > faces = null;
  public FaceDetector() throws IOException {
   webcam = Webcam.getDefault();
   webcam.setViewSize(WebcamResolution.VGA.getSize());
   webcam.open(true);
   img = webcam.getImage();
   webcam.close();
   ImagePanel panel = new ImagePanel(img);
   panel.setPreferredSize(WebcamResolution.VGA.getSize());
   add(panel);
   setTitle("Face Recognizer");
   setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
   pack();
   setLocationRelativeTo(null);
   setVisible(true);
  }
  public void detectFace() {
   JFrame fr = new JFrame("Discovered Faces");
   faces = detector.detectFaces(ImageUtilities.createFImage(img));
   if (faces == null) {
    System.out.println("No faces found in the captured image");
    return;
   }
   Iterator < DetectedFace > dfi = faces.iterator();
   while (dfi.hasNext()) {
    DetectedFace face = dfi.next();
    FImage image1 = face.getFacePatch();
    ImagePanel p = new ImagePanel(ImageUtilities.createBufferedImage(image1));
    fr.add(p);
   }
   fr.setLayout(new FlowLayout(0));
   fr.setSize(500, 500);
   fr.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
   fr.setVisible(true);
  }
  public static void main(String[] args) throws IOException {
   new FaceDetector().detectFace();
  }
 }

ImagePanel.java:

 package com.cooltrickshome;
 import java.awt.Dimension;
 import java.awt.Graphics;
 import java.awt.Image;
 import javax.swing.ImageIcon;
 import javax.swing.JPanel;
 class ImagePanel
 extends JPanel {
  private Image img;
  public ImagePanel(String img) {
   this(new ImageIcon(img).getImage());
  }
  public ImagePanel(Image img) {
   this.img = img;
   Dimension size = new Dimension(img.getWidth(null), img.getHeight(null));
   setPreferredSize(size);
   setMinimumSize(size);
   setMaximumSize(size);
   setSize(size);
   setLayout(null);
  }
  public void paintComponent(Graphics g) {
   g.drawImage(this.img, 0, 0, null);
  }
 }

I hope this helps!

References

  • Tutorial on taking a snapshot from a webcam in Java

  • Openimaj website

Java (programming language)

Published at DZone with permission of Anurag Jain, DZone MVB. See the original article here.

Opinions expressed by DZone contributors are their own.

Related

  • How to Introduce a New API Quickly Using Micronaut
  • Introducing Graph Concepts in Java With Eclipse JNoSQL
  • Using Java Stream Gatherers To Improve Stateful Operations
  • How to Merge HTML Documents in Java

Partner Resources

×

Comments
Oops! Something Went Wrong

The likes didn't load as expected. Please refresh the page and try again.

ABOUT US

  • About DZone
  • Support and feedback
  • Community research
  • Sitemap

ADVERTISE

  • Advertise with DZone

CONTRIBUTE ON DZONE

  • Article Submission Guidelines
  • Become a Contributor
  • Core Program
  • Visit the Writers' Zone

LEGAL

  • Terms of Service
  • Privacy Policy

CONTACT US

  • 3343 Perimeter Hill Drive
  • Suite 100
  • Nashville, TN 37211
  • support@dzone.com

Let's be friends:

Likes
There are no likes...yet! 👀
Be the first to like this post!
It looks like you're not logged in.
Sign in to see who liked this post!