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 ...

Single LindedList in C. Program to create, insert, delete, traverse in Single Linked List.

For creating the LinkedList program I have used Linux(ubuntu 12.04) machine. When I was in my college days, I would use the Tourbo C compiler which was easy to use in Windows Type the following command to install the build-essential which create our environment and C  compiler to build and run C programs. This will be enough for our purpose to create C programs. $ sudo apt−get install build−essential SinglyLinkedList.c ----------------------- #include <stdio.h> #include <stdlib.h> /* Linded List is having an element and a pointer which points to the same type of structure. I have type defined a NODE type and given alias as "node". */ typedef struct NODE { int info; struct NODE *next; }node; /* I have created a boolean type which returns 0, 1 and 2 which returns false, true and done respectively. This is basically for return type to be used in the program to return boolean values. */ typedef enum {false, true, done}boolean; /* Now crea...

N-Queens Problem

N-Queens Problem N- queen problem states that if no of queens are placed on a chessboard, then no two queens can attack each other. The following program states the same: package com.backtracking.test; public class QueenProblem { private int[][] chessTable; private int numOfQueens; public QueenProblem(int numOfQueens) { this.chessTable = new int[numOfQueens][numOfQueens]; this.numOfQueens = numOfQueens; } public void solve() { if (setQueens(0)) { printQueens(); } else { System.out.println("There is no solution.."); } } private boolean setQueens(int colIndex) { if (colIndex == numOfQueens) { return true; } for (int rowIndex = 0; rowIndex < numOfQueens; ++rowIndex) { if (isPlaceValid(rowIndex, colIndex)) { chessTable[rowIndex][colIndex] = 1; // Queeen is placed if (setQueens(colIndex + 1)) { return true; } // BACKTRACKING chessTable[rowIndex][colI...