-
Notifications
You must be signed in to change notification settings - Fork 1.1k
/
DetectMotionExample.java
95 lines (72 loc) · 2.16 KB
/
DetectMotionExample.java
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
package com.github.sarxos.webcam;
import java.awt.Dimension;
import java.awt.FlowLayout;
import java.io.IOException;
import javax.imageio.ImageIO;
import javax.swing.Icon;
import javax.swing.ImageIcon;
import javax.swing.JFrame;
import javax.swing.JLabel;
/**
* Detect motion.
*
* @author Bartosz Firyn (SarXos)
*/
public class DetectMotionExample extends JFrame implements Runnable {
private static final long serialVersionUID = -585739158170333370L;
private static final int INTERVAL = 100; // ms
private ImageIcon motion = null;
private ImageIcon nothing = null;
private JLabel label = null;
private Webcam webcam = Webcam.getDefault();
private int threshold = WebcamMotionDetector.DEFAULT_THREASHOLD;
private int inertia = 1000; // how long motion is valid
public DetectMotionExample() {
try {
motion = new ImageIcon(ImageIO.read(getClass().getResourceAsStream("/me-gusta.png")));
nothing = new ImageIcon(ImageIO.read(getClass().getResourceAsStream("/forever-alone.png")));
} catch (IOException e) {
e.printStackTrace();
}
label = new JLabel(nothing);
Thread updater = new Thread(this, "updater-thread");
updater.setDaemon(true);
updater.start();
setTitle("Rage Motion Detector");
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setLayout(new FlowLayout());
webcam.setViewSize(new Dimension(320, 240));
WebcamPanel panel = new WebcamPanel(webcam);
panel.setFPS(4);
add(panel);
add(label);
pack();
setVisible(true);
}
public static void main(String[] args) throws InterruptedException {
new DetectMotionExample();
}
@Override
public void run() {
WebcamMotionDetector detector = new WebcamMotionDetector(webcam, threshold, inertia);
detector.setInterval(INTERVAL);
detector.start();
while (true) {
Icon icon = label.getIcon();
if (detector.isMotion()) {
if (icon != motion) {
label.setIcon(motion);
}
} else {
if (icon != nothing) {
label.setIcon(nothing);
}
}
try {
Thread.sleep(INTERVAL * 2);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
}