Skip to main content

Capture the webcam video in Java with OpenCV

I am going to capture the video from webcam of the computer/laptop in our Java program. I am using OpenCV for this. For this first obtain a fresh release of OpenCV and extract it under some location like C:\opencv\. I am using version 3.0.0.


Now, we will define OpenCV as a user library in Eclipse, so we can reuse the configuration for any project. Launch Eclipse and select Window –> Preferences from the menu.


Navigate under Java –> Build Path –> User Libraries and click New....



Enter a name, e.g. OPENCV-3.0.0 for new library.



Now select your new user library and click Add External JARs....


Browse through C:\opencv\build\java and select opencv-300.jar. After adding the jar, extend the opencv-300.jar and select Native library location and press Edit....



Select External Folder... and browse to select the folder C:\opencv\build\java\x64. If you have a 32-bit system you need to select thex86 folder instead of x64.

My user library configuration should look like this:




Testing the configuration



Now start creating a new Java project.



On the Java Settings step, under Libraries tab, select Add Library... and select OpenCV-3.0.0, then click Finish.



Libraries should look like this:





Now once our setup is done, we are gonna write our Java Program using Swing, having a Frame, a Pane, and two button for 'Start' and 'Pause'. The pane is used to capture the webcam video.


CaptureCamVideo.java

package com.rohan.opencvtest;

import java.awt.EventQueue;
import java.awt.Graphics;
import java.awt.Image;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.image.BufferedImage;
import java.io.ByteArrayInputStream;

import javax.imageio.ImageIO;
import javax.swing.GroupLayout;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.LayoutStyle;
import javax.swing.WindowConstants;

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

@SuppressWarnings("serial")
public class CaptureCamVideo extends JFrame {

// definitions
private DaemonThread myThread = null;
int count = 0;
VideoCapture webSource = null;
Mat frame = new Mat();
MatOfByte mem = new MatOfByte();

// class of thread
class DaemonThread implements Runnable {
protected volatile boolean runnable = false;

@Override
public void run() {
synchronized (this) {
while (runnable) {
if (webSource.grab()) {
try {
webSource.retrieve(frame);
Imgcodecs.imencode(".bmp", frame, mem);
Image im = ImageIO.read(new ByteArrayInputStream(mem.toArray()));

BufferedImage buff = (BufferedImage) im;
// Image jPanel1;
Graphics g = jPanel1.getGraphics();

if (g.drawImage(buff, 0, 0, getWidth(),
getHeight() - 150, 0, 0, buff.getWidth(),
buff.getHeight(), null))

if (runnable == false) {
System.out.println("Going to wait()");
this.wait();
}
} catch (Exception ex) {
System.out.println("Error");
}
}
}
}
}
}

public CaptureCamVideo() {
initComponents();
}

private void initComponents() {

        jPanel1 = new JPanel();
        jButton1 = new JButton();
        jButton2 = new JButton();

        setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);

        GroupLayout jPanel1Layout = new GroupLayout(jPanel1);
        jPanel1.setLayout(jPanel1Layout);
        jPanel1Layout.setHorizontalGroup(
            jPanel1Layout.createParallelGroup(GroupLayout.Alignment.LEADING)
            .addGap(0, 383, Short.MAX_VALUE)
        );
        jPanel1Layout.setVerticalGroup(
            jPanel1Layout.createParallelGroup(GroupLayout.Alignment.LEADING)
            .addGap(0, 276, Short.MAX_VALUE)
        );

        jButton1.setText("Start");
        jButton1.addActionListener(new ActionListener() {
            public void actionPerformed(ActionEvent evt) {
                jButton1ActionPerformed(evt);
            }
        });

        jButton2.setText("Stop");
        jButton2.addActionListener(new ActionListener() {
            public void actionPerformed(ActionEvent evt) {
                jButton2ActionPerformed(evt);
            }
        });

        GroupLayout layout = new GroupLayout(getContentPane());
        getContentPane().setLayout(layout);
        layout.setHorizontalGroup(
            layout.createParallelGroup(GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addGroup(layout.createParallelGroup(GroupLayout.Alignment.LEADING)
                    .addGroup(layout.createSequentialGroup()
                        .addGap(136, 136, 136)
                        .addComponent(jPanel1, GroupLayout.PREFERRED_SIZE, GroupLayout.DEFAULT_SIZE, GroupLayout.PREFERRED_SIZE))
                    .addGroup(layout.createSequentialGroup()
                        .addGap(179, 179, 179)
                        .addComponent(jButton1)
                        .addGap(165, 165, 165)
                        .addComponent(jButton2)))
                .addContainerGap(225, Short.MAX_VALUE))
        );
        layout.setVerticalGroup(
            layout.createParallelGroup(GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addContainerGap()
                .addComponent(jPanel1, GroupLayout.PREFERRED_SIZE, GroupLayout.DEFAULT_SIZE, GroupLayout.PREFERRED_SIZE)
                .addPreferredGap(LayoutStyle.ComponentPlacement.UNRELATED)
                .addGroup(layout.createParallelGroup(GroupLayout.Alignment.LEADING)
                    .addComponent(jButton2)
                    .addComponent(jButton1))
                .addContainerGap(169, Short.MAX_VALUE))
        );
        pack();
    }

private void jButton1ActionPerformed(java.awt.event.ActionEvent evt) {
webSource = new VideoCapture(0);
myThread = new DaemonThread();
Thread t = new Thread(myThread);
t.setDaemon(true);
myThread.runnable = true;
t.start();
jButton1.setEnabled(false); // start button
jButton2.setEnabled(true); // stop button
}

private void jButton2ActionPerformed(java.awt.event.ActionEvent evt) {
myThread.runnable = false;
jButton2.setEnabled(false);
jButton1.setEnabled(true);

webSource.release();
}

public static void main(String[] args) {
System.loadLibrary(Core.NATIVE_LIBRARY_NAME); // load native library of opencv
EventQueue.invokeLater(new Runnable() {
@Override
public void run() {
CaptureCamVideo javaCam = new CaptureCamVideo();
javaCam.setVisible(true);
}
});
}

JButton jButton1;
JButton jButton2;
JPanel jPanel1;
}

Now, its time to run the program,

Run it and you will get the below screen:


Click on the Start button to view the live video capture by your webcam.

References:
http://docs.opencv.org/2.4/doc/tutorials/introduction/java_eclipse/java_eclipse.html
http://sourceforge.net/projects/opencvlibrary/?source=typ_redirect



Comments

Popular posts from this blog

Struts2 and Hibernate Example using Annotation

Hi Guys, Today we are going to create an example using Struts2 and Hibernate using Annotation. For the database, we are going to use MySQL. This example will register a record for a user in the mysql database, which later will be used to login to the application. First of all we need to create our database table in MySQL. Log into your mysql database and type the following command to create a database in the mysql prompt. create database mydb; Use the above created database to create table. use mydb; Now we need to create a database table named "users". create table users( uid int primary key auto_increment, uname char(15), password char(20), email char(20), phone long, city char(15)); Now to create this application, we are going to use eclipse. Open your eclipse and create a dynamic web project. Put the following jars related to Struts2 and Hibernate in the WEB-INF/lib folder Now create the following packages in the src folder for the ...

Java program to create staircase

Observe that its base and height are both equal to  , and the image is drawn using  #  symbols and spaces.  The last line is not preceded by any spaces. Write a program that prints a staircase of size  . Input Format A single integer,  , denoting the size of the staircase. Output Format Print a staircase of size   using  #  symbols and spaces. Note : The last line must have   spaces in it. package com.rohan.test; import java.util.Scanner; public class StaircaseTest {     public static void main(String[] args) {         Scanner in = new Scanner(System.in);         int n = in.nextInt();                  for(int i = 0; i< n; i++) {         for(int k = 0; k < n; k++) {         if(k < n-i-1)         System.out.p...

Java program to print the maximum hourglass value of the matrix

Context   Given a    2D Array ,  : 1 1 1 0 0 0 0 1 0 0 0 0 1 1 1 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 We define an hourglass in   to be a subset of values with indices falling in this pattern in  's graphical representation: a b c d e f g There are   hourglasses in  , and an  hourglass sum  is the sum of an hourglass' values. Task   Calculate the hourglass sum for every hourglass in  , then print the  maximum  hourglass sum. Note:  If you have already solved the Java domain's  Java 2D Array  challenge, you may wish to skip this challenge. Input Format There are   lines of input, where each line contains   space-separated integers describing  2D Array   ; every value in   will be in the inclusive range of   to  . Constraints Output Format Print the largest (maximum) hourglass sum f...