From 27c56f32621d1a3808d8a1b32eb398bc331efa1e Mon Sep 17 00:00:00 2001 From: Bartosz Firyn Date: Fri, 8 Aug 2014 19:49:24 +0200 Subject: [PATCH] Bug in the motion detector cause false positives, fixes #250 --- .../sarxos/webcam/WebcamMotionDetector.java | 25 +++++++++++++------ 1 file changed, 17 insertions(+), 8 deletions(-) diff --git a/webcam-capture/src/main/java/com/github/sarxos/webcam/WebcamMotionDetector.java b/webcam-capture/src/main/java/com/github/sarxos/webcam/WebcamMotionDetector.java index ca5cbec3..f8367458 100644 --- a/webcam-capture/src/main/java/com/github/sarxos/webcam/WebcamMotionDetector.java +++ b/webcam-capture/src/main/java/com/github/sarxos/webcam/WebcamMotionDetector.java @@ -45,9 +45,9 @@ public class WebcamMotionDetector { public static final int DEFAULT_PIXEL_THREASHOLD = 25; /** - * Default check interval (in milliseconds, set to 1 second). + * Default check interval, in milliseconds, set to 500 ms. */ - public static final int DEFAULT_INTERVAL = 1000; + public static final int DEFAULT_INTERVAL = 500; /** * Default percentage image area fraction threshold (set to 0.2%). @@ -120,7 +120,7 @@ public void run() { delay = inertia != -1 ? inertia : 2 * interval; if (lastMotionTimestamp + delay < System.currentTimeMillis()) { - motion.set(false); + motion = false; } } } @@ -144,7 +144,7 @@ public void run() { /** * Is motion? */ - private final AtomicBoolean motion = new AtomicBoolean(false); + private volatile boolean motion = false; /** * Previously captured image. @@ -272,8 +272,18 @@ public void stop() { protected void detect() { + if (!webcam.isOpen()) { + motion = false; + return; + } + BufferedImage current = webcam.getImage(); + if (current == null) { + motion = false; + return; + } + current = blur.filter(current, null); current = gray.filter(current, null); @@ -308,9 +318,8 @@ protected void detect() { cog = new Point(cogX / p, cogY / p); - if (motion.compareAndSet(false, true)) { - lastMotionTimestamp = System.currentTimeMillis(); - } + motion = true; + lastMotionTimestamp = System.currentTimeMillis(); notifyMotionListeners(); @@ -457,7 +466,7 @@ public boolean isMotion() { if (!running.get()) { LOG.warn("Motion cannot be detected when detector is not running!"); } - return motion.get(); + return motion; } /**