-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathcctv.js
79 lines (74 loc) · 2.17 KB
/
cctv.js
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
const cv = require("opencv");
const sleep = require("sleep");
const fs = require("fs");
class CCTV {
constructor(width, height, snapshotInterval, onMotionDetectCb) {
this.camera = new cv.VideoCapture(0);
this.width = width;
this.height = height;
this.snapshotInterval = snapshotInterval;
this.onMotionDetectCb = onMotionDetectCb;
this.wasMotionDetected = false;
this.firstFrame = null;
}
async start() {
sleep.sleep(2);
this.camera.setWidth(this.width);
this.camera.setHeight(this.height);
await this.setFirstFrame();
while (true) {
await this.getCameraSnapShot();
sleep.msleep(500);
}
}
setFirstFrame() {
return new Promise((resolve, _) => {
this.camera.read((err, frame) => {
this.firstFrame = frame;
this.firstFrame.cvtColor("CV_BGR2GRAY");
this.firstFrame.gaussianBlur([21, 21]);
resolve(true);
});
});
}
updateFirstImage() {
return new Promise((resolve, _) => {
this.camera.read(async (err, frame) => {
frame.save("motion.jpg");
this.firstFrame = frame;
this.firstFrame.cvtColor("CV_BGR2GRAY");
this.firstFrame.gaussianBlur([21, 21]);
await this.onMotionDetectCb(fs.readFileSync("motion.jpg"));
resolve(true);
});
});
}
getCameraSnapShot() {
return new Promise((resolve, _) => {
this.camera.read(
async function(err, frame) {
this.wasMotionDetected = false;
let gray = frame.copy();
gray.cvtColor("CV_BGR2GRAY");
gray.gaussianBlur([21, 21]);
let frameDelta = new cv.Matrix();
frameDelta.absDiff(this.firstFrame, gray);
let thresh = frameDelta.threshold(25, 255);
thresh.dilate(2);
let cnts = thresh.findContours();
for (let i = 0; i < cnts.size(); i++) {
if (cnts.area(i) < 500) {
continue;
}
this.wasMotionDetected = true;
}
if (this.wasMotionDetected) {
await this.updateFirstImage.bind(this)();
}
resolve(true);
}.bind(this)
);
});
}
}
module.exports.CCTV = CCTV;