Friday, September 05, 2014

Webcam CaptureでWebカメラで撮影している内容に動きがあった時にファイル保存する

Webcam CaptureでWebカメラで撮影している内容に動きがあった時にファイル保存するには、以下のコードを実行します。

// 0.3.10-RC以上が必要
// https://github.com/sarxos/webcam-capture/issues/34
//@Grab(group='com.github.sarxos', module='webcam-capture', version='0.3.9')
import java.awt.*
import java.awt.image.*
import javax.imageio.*
import com.github.sarxos.webcam.*

def webcam = Webcam.getDefault()
if( webcam == null )return

println "Webcam: " + webcam.getName()
webcam.setViewSize(new Dimension(640, 480))
def detector = new WebcamMotionDetector(webcam)
detector.setInterval(500) // 500ms
detector.start()

while(true){
  if( detector.isMotion() ){
    println "detected motion..."
    BufferedImage image = webcam.getImage()
    ImageIO.write(image, "PNG", new File("motion.png"))
    return
  }
  Thread.sleep(500)
}