Webcam Capture

Generic Webcam Java Utility

Webcam Capture

The goal of this project is to provide really simple webcam API allowing you to use your build-in, external (USB-connected) webcams or IP / network cameras directly from Java code. It provides basic webcam interface and a set of additional drivers which can be used to replace default build-in drivers to extend and/or replace default functionality.

Continous Integration build status (Travis CI):

Build Status

Requirements

Core Features

Contribute

If you have spare time, knownledge or even some small money amount to spent, you can help developing awesome Webcam Capture API and make it even better! Several kinds of contributions are very welcome:

How To Start

Webcam Capture is avilable in Maven Central, so if you can add its dependency to your project if you are using one of the dependency manager:

Maven

<dependency>
    <groupId>com.github.sarxos</groupId>
    <artifactId>webcam-capture</artifactId>
    <version>0.3.9</version>
</dependency>

No Dependency Manager?

Download ZIP file containing complete API reference, required JARs, sources and examples (link is visible at the right top corner of this page), uncompress, and add webcam-capture-[version].jar and all JARs under libs directory to your project's classpath:

Additional Drivers

Currently Webcam Capture supports the following drivers:

IP / Network Camera Driver

This is IP camera driver for Webcam Capture project. It allows Webcam Capture to handle pictures from IP cameras supporting JPEG and MJPEG (Motion JPEG) compression. For more information about supported models, how to extend, examples, use-cases, please follow to the Github project available here.

This driver is available in Maven Central.

JMF / FMJ Driver

This is driver containing video grabber for Webcam Capture project. It utilizes JMF capabilities to access PC webcam (those USB-connected too) and can be used as a replacement for default build-in driver. Its advantage is the fact it's pretty fast, but unformtunately, from the other hand, it requires JMF to be installed on your PC.

If you do not want to use JMF (due to e.g. licensing issues), you can choose FMJ, which is a freeware replacement for JMF.

NOTE! Be aware of the fact that both JMF and FMJ are not being maintained any more!

This driver is available in Maven Central.

OpenIMAJ Driver

This is driver containing video grabber for Webcam Capture project. It utilizes OpenIMAJ framework capabilities to access PC webcam and can be used as a replacement for default build-in driver. Its advantage is the fact it's pretty fast, supports multiple platforms, but disadventage is the size of required 3rd party JARs (around ~20MB). Default build-in driver uses OpenIMAJ natives to support video grabbing, but id does not require all those additional JARs.

This driver is NOT available in Maven Central, but it can be used in Maven build. In such a case user has to add those repositories to project's POM:

<repositories>
    <repository>
        <id>OpenIMAJ maven repository</id>
        <url>http://maven.openimaj.org/</url>
    </repository>
    <repository>
        <id>Octopussy thirdparty maven repository</id>
        <url>http://octopussy.ecs.soton.ac.uk/m2/thirdparty/</url>
    </repository>
    <repository>
        <id>OpenIMAJ Snapshots maven repository</id>
        <url>http://octopussy.ecs.soton.ac.uk/m2/snapshots/</url>
    </repository>
</repositories>

LTI-CIVIL Driver

This is driver containing video grabber for Webcam Capture project. It utilizes LTI-CIVIL project capabilities to access PC webcam and can be used as a replacement for default build-in driver. LTI-CIVIL supports Windows, Linux and MAC OS platforms. For Mac OS it utilizes QTJ framework capabilities. For other ones it uses precompiled natives.

This driver is NOT available in Maven Central, but it can be used in Maven build. In such a case user has to add those repositories to project's POM:

<repositories>
    <repository>
        <id>sarxos-repo</id>
        <url>http://repo.sarxos.pl/maven2</url>
    </repository>
</repositories>

NOTE! Be aware of the fact that LTI-CIVIL not being maintained any more by its owner!

OpenCV Driver

EXPERIMENTAL STUFF!

This is driver containing video grabber for Webcam Capture project. It utilizes JavaCV Java wrapper for OpenCV project capabilities to access PC webcam and can be used as a replacement for default build-in driver. Its advantage is quite stable interface, but unfortunately it requires quite huge (around ~100MB) pre-installed OpenCV bundle.

This driver is NOT available in Maven Central, but it can be used in Maven build. In such a case user has to add those repositories to project's POM:

<repositories>
    <repository>
        <id>javacv</id>
        <url>http://maven2.javacv.googlecode.com/git</url>
    </repository>
    <repository>
        <id>kevoree</id>
        <url>http://maven.kevoree.org/release</url>
    </repository>
</repositories>

VLCj Driver

EXPERIMENTAL STUFF!

This is driver containing video grabber for Webcam Capture project. It utilizes VLCj Java wrapper for Videolan VLC project capabilities to access PC webcam and can be used as a replacement for default build-in driver. Unfortunately it require VLC media player to be pre-installed on the system where driver will be used.

This driver is NOT available in Maven Central, but it can be used in Maven build. In such a case user has to add those repositories to project's POM:

<repositories>
    <repository>
        <id>caprica</id>
        <url>http://www.capricasoftware.co.uk/repo</url>
    </repository>
</repositories>

Examples

Confirmed to be perfectly running on the following systems (please report at the project page if you tested it on other system, just create new issue for that purpose):

Problems detected on those configurations:

Capture Image

To capture single image and save it to disk:

Webcam webcam = Webcam.getDefault();
webcam.open();
BufferedImage image = webcam.getImage();
ImageIO.write(image, "PNG", new File("test.png"));

If you have more then one webcam connected to your computer:

Webcam laptop = Webcam.getWebcams().get(0);
Webcam kitchen = Webcam.getWebcams().get(1);
Webcam roof = Webcam.getWebcams().get(2);

Detect Motion

To detect motion with your webcam - loop solution:

WebcamMotionDetector detector = new WebcamMotionDetector(Webcam.getDefault());
detector.setInterval(100); // one check per 100 ms (10 FPS)
detector.start();

while (true) {
    if (detector.isMotion()) {
        System.out.println("Detected motion I, alarm turn on you have");
    }
    Thread.sleep(500);
}

To detect motion with webcam - listener solution:

public class DetectMotionExample implements WebcamMotionListener {

    WebcamMotionDetector detector = new WebcamMotionDetector(Webcam.getDefault());

    public DetectMotionExample() {
        detector.setInterval(100); // one check per 100 ms (10 FPS)
        detector.addMotionListener(this);
        detector.start();
    }

    @Override
    public void motionDetected(WebcamMotionEvent wme) {
        System.out.println("Detected motion I, alarm turn on you have");
    }

    public static void main(String[] args) throws IOException {
        new DetectMotionExample();
        System.in.read(); // keeps your program open
    }
}

Swing Support

You can display image from webcam in Swing JPanel. There is a special component designed for this.

JFrame window = new JFrame("Test Webcam Panel");
window.add(new WebcamPanel(Webcam.getDefault()));
window.pack();
window.setVisible(true);
window.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

Display Image From IP / Network Camera

To use Webcam Capture together with IP or network camera you have to add IP / network camera driver to your Webcam Capture project.

IpCamDevice ipcam = new B7210("B7210", "114.32.216.24");
ipcam.setAuth(new IpCamAuth("demo", "demo"));
ipcam.setSize(B7210.SIZE_QVGA);

IpCamDriver driver = new IpCamDriver();
driver.register(ipcam);

Webcam.setDriver(driver);

WebcamPanel panel = new WebcamPanel(Webcam.getDefault());
panel.setFPS(0.5); // 1 frame per 2 seconds

JFrame f = new JFrame("Night Tree Somewhere");
f.add(panel);
f.pack();
f.setVisible(true);
f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

More IP / network camera examples are available in Github project's page.

Development Troubleshooting

In the development phase you will probably kill running application many time (by stop button in Eclipse, Netbeans or other IDE), or by calling kill -TERM <pid> command from CLI. You have to be aware that killing running application when Webcam Capture is already running can have unwanted side-effects, such as:

All those issues arose from the same root cause - memory has not been properly deallocated in the native layer. That's because you killed application instead of closing it gracefully.

However, there is a solution for this problem. For such purpose special TERM signal handler has been implemented, and you can enable it before you actually start using Webcam Capture API. This can be done by calling this code (please make sure to call it before you use any other method!):

Webcam.setTermSignalHandler(true);

IMPORTANT NOTE! This is development setting and shall not be used in production code!!! It modified the way of how JVM terminates its process, so depending on the system there can be some unknown side-effects. Also features used in this handler are undocumented and can be removed in further Java releases without prior notification.

Logging

Logging has been implemented via SLF4J API, so all you need to do is to add specific implementation and create configuration file.

Logging Example With Logback Library

This paragraph describes in short how to use Logback to enable logs from Webcam Capture API.

Go to Logback home page and download ZIP files containing all required JARs. Extract ZIP and add those files into your classpath:

NOTE! The [version] is current Logback release signature (e.g. 1.0.9).

Create logback.xml file and put this content inside:

<configuration scan="true" scanPeriod="30 seconds">
	<appender name="STDOUT" class="ch.qos.logback.core.ConsoleAppender">
		<layout class="ch.qos.logback.classic.PatternLayout">
			<Pattern>%d{HH:mm:ss.SSS} [%thread] %-5level %logger{36} - %msg%n</Pattern>
		</layout>
	</appender>
	<root level="debug">
		<appender-ref ref="STDOUT" />
	</root>
</configuration>

When you include this file in your classpath, it will be discovered automatically, but you can also load it manually by calling:

WebcamLogConfigurator.configure("path/to/logback.xml");

More Examples?

There are more examples available in src/example, don't forget to check them - please follow to the Github Project's Page where Webcam Capture source code is stored! Here are the examples links:

License

Copyright (C) 2012 - 2013 Bartosz Firyn

Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions:

The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.

THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.