Capture webcam images every 1 second using Javacv

Asked

Viewed 218 times

1

A particular programmer is doing a project where the standard webcam takes photos every 1 second using Javacv.

For now ,in this code, at the click of the capture button it captures a photo and saves in the program folder. It is asked that the program save the photos in a certain folder selected by the user and that the webcam capture photos every 1 second.

import com.googlecode.javacv.CanvasFrame;    
import com.googlecode.javacv.OpenCVFrameGrabber;    
import com.googlecode.javacv.cpp.opencv_core.IplImage;    
import com.googlecode.javacv.cpp.opencv_highgui;    
import com.googlecode.javacv.cpp.opencv_highgui.CvCapture;    
import static com.googlecode.javacv.cpp.opencv_highgui.cvSaveImage;    
import java.awt.event.KeyEvent;    
import javax.swing.JOptionPane;

OpenCVFrameGrabber grabber = new OpenCVFrameGrabber(0);

JOptionPane.showMessageDialog(null, "Aperte a tecla P para parar a gravação");
        while(KeyEvent.VK_P){

try{
            grabber.start();

IplImage img = grabber.grab();

            if(img!=null){
                cvSaveImage("image1.jpg", img);
            }
        }
        catch(Exception e){
         e.printStackTrace();
        }
        setFocusable(true);
        setVisible(true);

        }

1 answer

1

You can use the class Timer for that reason.

Just create a Timer, and set a TimerTask that does what you need within the method run(), for example:

Timer timer;

public void criarTimer(int segundos) {
    TimerTask timerTask = new TimerTask() {
        public void run() {
            System.out.println("Time's up!");
        }
    };
    int segundosParaComecar = 0;
    int segundosParaCapturar = segundos*1000;
    timer = new Timer();
    timer.schedule(timerTask, segundosParaComecar, segundosParaCapturar);
}

See it working on Ideone.

And another thing. If you need to cancel the timer, I advise you to leave a global variable, and make a condition within the run() of TimerTask, so you can give a timer.cancel() whenever you want.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.