How to open webcam in Java using OpenCV

Hello everyone! learn how to open webcam on your laptops using OpenCV in Java. For this, you need to follow certain steps.

  1. Open the source code.
  2.  Right-click on your source file.
  3.  Select the build path option.
  4.  Click on the configure build option.
  5.  Select libraries option.
  6. click on add external Jars option.
  7. Select the OpenCV library.
  8.  Set the native build path.

Learn how to open webcam in Java using OpenCV

package jyothi;
import java.awt.image.BufferedImage;
import java.io.ByteArrayInputStream;
import java.io.InputStream;

import javax.imageio.ImageIO;
import javax.swing.ImageIcon;
import javax.swing.JFrame;
import javax.swing.JLabel;

import org.opencv.core.Core;
import org.opencv.core.Mat;
import org.opencv.core.MatOfByte;
import org.opencv.core.Size;
import org.opencv.imgcodecs.Imgcodecs;
import org.opencv.imgproc.Imgproc;
import org.opencv.videoio.VideoCapture;

public class close {

  public static void main(String[] args) {
    // TODO Auto-generated method stub
    System.loadLibrary(Core.NATIVE_LIBRARY_NAME);

    VideoCapture video = new VideoCapture(0);
    Mat f = new Mat();

    while (true){
        video.read(f);
        showResult(f);
    }
    } 

    public static void showResult(Mat img) {
    Imgproc.resize(img, img, new Size(640, 480));
    MatOfByte m = new MatOfByte();
    Imgcodecs.imencode(".jpg", img, m);	
    byte[] byteArray = m.toArray();
    BufferedImage bufImage = null;
    try {
        InputStream in = new ByteArrayInputStream(byteArray);
        bufImage = ImageIO.read(in);
        JFrame frame = new JFrame();
        frame.getContentPane().add(new JLabel(new ImageIcon(bufImage)));
        frame.pack();
        frame.setVisible(true);
    }

                 catch (Exception e) {
        e.printStackTrace();
            }
       }
}
  

output:

How to open webcam in Java using OpenCV

Firstly, import all the required packages. And then follow the code. And at the end when you execute this code, your laptop webcam starts blinking and in the java frame, you will be able to notice the images captured the webcam.

Firstly, we should initialize the videoCapture class and then create a Mat object. We check whether the picture is captured or not by setting a loop and until the webcam is running continuously the picture read and then the picture is reflected in a window by creating a JFrame.I hope the explanation is clear and the code is easy to implement. And most important, don’t forget to import external libraries.

Also read: How to detect face in java using OpenCV

Leave a Reply

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