Capture webcam images every 1 second using JavaCV

1

A particular programmer is doing a project where the default webcam takes pictures every 1 second using JavaCV.

For now, in this code, at the click of the capture button it captures a photo and saves it in the program folder. It asks the program to save the photos to a certain folder selected by the user and the webcam to 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);

        }
    
asked by anonymous 04.11.2016 / 13:47

1 answer

1

You can use the Timer class for this.

Just create a Timer , and set a TimerTask to do what you need within the run() method, 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 working at IdeOne.

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

    
04.11.2016 / 14:24