utils.js
2.2 KB
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
const path = require('path');
const cv = require('opencv4nodejs');
exports.cv = cv;
const dataPath = path.resolve(__dirname, './data');
exports.dataPath = dataPath;
exports.getDataFilePath = fileName => {
let targetPath = path.resolve(dataPath, fileName);
return targetPath;
}
const grabFrames = (videoFile, delay, onFrame) => {
const cap = new cv.VideoCapture(videoFile);
let done = false;
const intvl = setInterval(() => {
let frame = cap.read();
// loop back to start on end of stream reached
if (frame.empty) {
cap.reset();
frame = cap.read();
}
onFrame(frame);
const key = cv.waitKey(delay);
done = key !== -1 && key !== 255;
if (done) {
clearInterval(intvl);
console.log('Key pressed, exiting.');
}
}, 0);
};
exports.grabFrames = grabFrames;
exports.runVideoDetection = (src, detect) => {
grabFrames(src, 1, frame => {
detect(frame);
});
};
exports.drawRectAroundBlobs = (binaryImg, dstImg, minPxSize, fixedRectWidth) => {
const {
centroids,
stats
} = binaryImg.connectedComponentsWithStats();
// pretend label 0 is background
for (let label = 1; label < centroids.rows; label += 1) {
const [x1, y1] = [stats.at(label, cv.CC_STAT_LEFT), stats.at(label, cv.CC_STAT_TOP)];
const [x2, y2] = [
x1 + (fixedRectWidth || stats.at(label, cv.CC_STAT_WIDTH)),
y1 + (fixedRectWidth || stats.at(label, cv.CC_STAT_HEIGHT))
];
const size = stats.at(label, cv.CC_STAT_AREA);
const blue = new cv.Vec(255, 0, 0);
if (minPxSize < size) {
dstImg.drawRectangle(
new cv.Point(x1, y1),
new cv.Point(x2, y2),
{ color: blue, thickness: 2 }
);
}
}
};
const drawRect = (image, rect, color, opts = { thickness: 2 }) =>
image.drawRectangle(
rect,
color,
opts.thickness,
cv.LINE_8
);
exports.drawRect = drawRect;
exports.drawBlueRect = (image, rect, opts = { thickness: 2 }) =>
drawRect(image, rect, new cv.Vec(255, 0, 0), opts);
exports.drawGreenRect = (image, rect, opts = { thickness: 2 }) =>
drawRect(image, rect, new cv.Vec(0, 255, 0), opts);
exports.drawRedRect = (image, rect, opts = { thickness: 2 }) =>
drawRect(image, rect, new cv.Vec(0, 0, 255), opts);