Accessing Webcam through Java - COMPUTER VISION

Hello All,
This post is all about how to access Webcam through java .Accessing Webcam is a part of COMPUTER VISION where coder access webcam and use it to capture Real World frame by frame and use the real world information for further processing .

Here we will be using a very basic library freely available to use , that is LTI CIVIL .Lets start with code as Said coding wins over all arguments.The whole java code goes here.

First of all , integrate lti civil libraries to your code (like using ADD JAR facility in NETBEANS). The library files can be downloaded from here http://sourceforge.net/projects/lti-civil/

Next the files to be imported :
package viano; // any package name you want 

import com.lti.civil.CaptureDeviceInfo;
import com.lti.civil.CaptureException;
import com.lti.civil.CaptureObserver;
import com.lti.civil.CaptureStream;
import com.lti.civil.CaptureSystem;
import com.lti.civil.CaptureSystemFactory;
import com.lti.civil.DefaultCaptureSystemFactorySingleton;
import com.lti.civil.Image;
import com.lti.civil.awt.AWTImageConverter;
import com.sun.image.codec.jpeg.JPEGCodec;
import com.sun.image.codec.jpeg.JPEGImageEncoder;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.image.BufferedImage;
import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.Calendar;
import java.util.List;
import javax.imageio.ImageIO;
import javax.swing.*;
import java.awt.Color;
import java.awt.Graphics;
import java.awt.Graphics2D;
import java.awt.Polygon;
import java.awt.event.WindowAdapter;
import java.awt.event.WindowEvent;
import java.awt.image.BufferedImage;
import java.util.List;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.SwingUtilities;
import javax.swing.WindowConstants;
import com.lti.civil.CaptureDeviceInfo;
import com.lti.civil.CaptureException;
import com.lti.civil.CaptureObserver;
import com.lti.civil.CaptureStream;
import com.lti.civil.CaptureSystem;
import com.lti.civil.CaptureSystemFactory;
import com.lti.civil.DefaultCaptureSystemFactorySingleton;
import com.lti.civil.Image;
import com.lti.civil.VideoFormat;
import com.lti.civil.awt.AWTImageConverter;
import java.awt.Dimension;
import java.awt.Graphics;
import java.util.logging.Level;
import java.util.logging.Logger;

import javax.swing.ImageIcon;
import javax.swing.JFrame;
import javax.swing.JPanel;

public class Viano implements CaptureObserver {

    /**
     * @param args the command line arguments
     */
    JButton start = null;
    JButton shot = null;
    JButton stop = null;
    JButton close = null;
    JLabel info = null;
    JLabel wait = null;
    CaptureStream captureStream = null;
    boolean takeShot = false;
    private Image img;
    public boolean chk;
    public int imagenumber = 0;

    public Viano() {



        CaptureSystemFactory factory = DefaultCaptureSystemFactorySingleton.instance();
        CaptureSystem system;

        try {

            system = factory.createCaptureSystem();
            system.init();
            List list = system.getCaptureDeviceInfoList();
            int i = 0;
            if (i < list.size()) {
                CaptureDeviceInfo info = (CaptureDeviceInfo) list.get(2);
                System.out.println((new StringBuilder()).append("Device ID ").append(i).append(": ").append(info.getDeviceID()).toString());
                System.out.println((new StringBuilder()).append("Description ").append(i).append(": ").append(info.getDescription()).toString());
                captureStream = system.openCaptureDeviceStream(info.getDeviceID());
                captureStream.setObserver(Viano.this);
            }
        } catch (CaptureException ex) {
            ex.printStackTrace();
        }

        JFrame frame = new JFrame();
        frame.setSize(700, 700);
        frame.setName("Viano");

        JPanel panel = new JPanel();
        frame.setContentPane(panel);
        frame.setVisible(true);
        frame.setTitle("Viano");
        frame.setLocationRelativeTo(null);
        frame.setResizable(false);
        frame.setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);

        frame.setBackground(Color.blue);
        start = new JButton("Start Webcam");
        stop = new JButton("Project Viano : Virtual Piano ");
        shot = new JButton("Image appears here !! Click here to take image manually");
        close = new JButton("Exit");
        info = new JLabel("Welcome to Viano");
        wait = new JLabel("Please  wait ...Accessing and starting webcam ...");

        panel.add(wait);

        panel.revalidate();
        try {
            chk = true;

            captureStream.start();
            panel.remove(wait);
            try {
                Thread.sleep(1000);
            } catch (InterruptedException ex6) {
                Logger.getLogger(Viano.class.getName()).log(Level.SEVERE, null, ex6);
            }
            panel.add(info);
            panel.add(shot);
            panel.add(stop);
            panel.revalidate();

            while (true) {
                takeShot = true;



            }




        } catch (CaptureException ex) {
            Logger.getLogger(Viano.class.getName()).log(Level.SEVERE, null, ex);
        }
        start.addActionListener(new ActionListener() {

            public void actionPerformed(ActionEvent e) {
                try {
                    captureStream.start();
                    takeShot = true;
                } catch (CaptureException ex) {
                    ex.printStackTrace();

                }
            }
        });
        stop.addActionListener(new ActionListener() {

            public void actionPerformed(ActionEvent e) {
                try {
                    //takeShot=false;
                    captureStream.stop();
                } catch (CaptureException ex) {
                    ex.printStackTrace();
                }
            }
        });
        shot.addActionListener(new ActionListener() {

            public void actionPerformed(ActionEvent e) {
                takeShot = true;
            }
        });

        close.addActionListener(new ActionListener() {

            public void actionPerformed(ActionEvent e) {
                chk = false;
            }
        });

    }

    public void onNewImage(CaptureStream stream, Image image) {

        if (!takeShot) {
            return;
        }
        takeShot = false;
        System.out.println("Image Shot " + (++imagenumber));
        byte bytes[] = null;
        try {
            if (image == null) {
                bytes = null;
                return;
            }
            try {

                ByteArrayOutputStream os = new ByteArrayOutputStream();
                JPEGImageEncoder jpeg = JPEGCodec.createJPEGEncoder(os);
                jpeg.encode(AWTImageConverter.toBufferedImage(image));
                os.close();
                bytes = os.toByteArray();
            } catch (IOException e) {
                e.printStackTrace();
                bytes = null;
            } catch (Throwable t) {
                t.printStackTrace();
                bytes = null;
            }
            if (bytes == null) {
                return;
            }



            ByteArrayInputStream is = new ByteArrayInputStream(bytes);
            File file = new File("f:/viano/imagesCaptured/" + "VianoImageCaptured" +/*
                     * Calendar.getInstance().getTimeInMillis() +
                     */ ".jpg");
            FileOutputStream fos = new FileOutputStream(file);
            fos.write(bytes);
            fos.close();
            BufferedImage myImage = ImageIO.read(file);

            shot.setText("");
            shot.setIcon(new ImageIcon(myImage));
            shot.revalidate();
        } catch (IOException ex) {
            ex.printStackTrace();
        }
        try {
            Thread.sleep(200);
        } catch (InterruptedException ex) {
            Logger.getLogger(Viano.class.getName()).log(Level.SEVERE, null, ex);
        }
        

    }

    public void onError(CaptureStream arg0, CaptureException arg1) {
        throw new UnsupportedOperationException("Error is coming ");

    }

    public static void main(String args[])
            throws Exception {


        System.out.println("Viano Started\nImage Capturing Started");

        Viano test = new Viano();
        System.out.println("Image Capturing Stops\nViano Rests");


    }
}


Made in Jframe , this code captures each shot of real world frame by frame and saves it as an image .at a particular location .
takeShot=true;  this line captures the image .
ANY DOUBTS POST IT AS  COMMENT..

Comments

Kishan said…
when i try to run it , it just says "Please wait ...Accessing and starting webcam ...". I dont think it is able to access the webcam. Please suggest
Unknown said…
Change "2" in this line CaptureDeviceInfo info = (CaptureDeviceInfo) list.get(2);

change it to 1 or 0 according to webcam devices available on ur machine..or simply put that "i" variable of loop accordingly .. and it will work :)

Popular posts from this blog

How to Install CCSM ( compizconfig settings manager ) in UBUNTU

Connecting JSP page with MS Access :: JDBC ODBC Connectivity

Adding TTS ( Text to Speech ) to your website