How can I continuously capture images from a webcam?
I want to experiment with object recognition (by maybe using java media framework).
I was thinking of creating two threads
one thread:
other thread:
Some time ago I've created generic Java library which can be used to take pictures with a PC webcam. The API is very simple, not overfeatured, can work standalone, but also supports additional webcam drivers like OpenIMAJ, JMF, FMJ, LTI-CIVIL, etc, and some IP cameras.
Link to the project is https://github.com/sarxos/webcam-capture
Example code (take picture and save in test.jpg):
Webcam webcam = Webcam.getDefault(); webcam.open(); BufferedImage image = webcam.getImage(); ImageIO.write(image, "JPG", new File("test.jpg"));
It is also available in Maven Central Repository or as a separate ZIP which includes all required dependencies and 3rd party JARs.
This JavaCV implementation works fine.
Code:
import org.bytedeco.javacv.*; import org.bytedeco.opencv.opencv_core.IplImage; import java.io.File; import static org.bytedeco.opencv.global.opencv_core.cvFlip; import static org.bytedeco.opencv.helper.opencv_imgcodecs.cvSaveImage; public class Test implements Runnable { final int INTERVAL = 100;///you may use interval CanvasFrame canvas = new CanvasFrame("Web Cam"); public Test() { canvas.setDefaultCloseOperation(javax.swing.JFrame.EXIT_ON_CLOSE); } public void run() { new File("images").mkdir(); FrameGrabber grabber = new OpenCVFrameGrabber(0); // 1 for next camera OpenCVFrameConverter.ToIplImage converter = new OpenCVFrameConverter.ToIplImage(); IplImage img; int i = 0; try { grabber.start(); while (true) { Frame frame = grabber.grab(); img = converter.convert(frame); //the grabbed frame will be flipped, re-flip to make it right cvFlip(img, img, 1);// l-r = 90_degrees_steps_anti_clockwise //save cvSaveImage("images" + File.separator + (i++) + "-aa.jpg", img); canvas.showImage(converter.convert(img)); Thread.sleep(INTERVAL); } } catch (Exception e) { e.printStackTrace(); } } public static void main(String[] args) { Test gs = new Test(); Thread th = new Thread(gs); th.start(); } }
There is also post on configuration for JavaCV
You can modify the codes and be able to save the images in regular interval and do rest of the processing you want.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With