Skip to content

Commit

Permalink
feat: ability to mask images before processing #79
Browse files Browse the repository at this point in the history
  • Loading branch information
jakowenko committed Aug 27, 2021
1 parent b6478ce commit decb245
Show file tree
Hide file tree
Showing 2 changed files with 47 additions and 0 deletions.
43 changes: 43 additions & 0 deletions api/src/util/mask.image.util.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,43 @@
const { promisify } = require('util');
const { createCanvas, loadImage } = require('canvas');
const sizeOf = promisify(require('image-size'));

const { MASKS } = require('../constants');

module.exports = async (event, tmp) => {
const masks = MASKS
? MASKS.filter(({ CAMERA }) => CAMERA === event.camera).map(({ MASK }) => MASK)
: [];
const coordinates = [];
masks.forEach((mask) => {
coordinates.push([]);
mask.split(',').forEach((value, i) => {
if (i % 2 === 0) {
coordinates[coordinates.length - 1].push({ x: value });
} else {
const objectLength = coordinates[coordinates.length - 1].length - 1;
coordinates[coordinates.length - 1][objectLength].y = value;
}
});
});

if (!coordinates.length) return false;

const { width, height } = await sizeOf(tmp);
const canvas = createCanvas(width, height);
const ctx = canvas.getContext('2d');
const image = await loadImage(tmp);
ctx.fillStyle = '#000';
ctx.drawImage(image, 0, 0);
coordinates.forEach((coordinate) => {
ctx.beginPath();
coordinate.forEach(({ x, y }, i) => {
if (i === 0) ctx.moveTo(x, y);
else ctx.lineTo(x, y);
});
ctx.closePath();
ctx.fill();
});

return canvas.toBuffer('image/jpeg');
};
4 changes: 4 additions & 0 deletions api/src/util/process.util.js
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,7 @@ const perf = require('execution-time')();
const { v4: uuidv4 } = require('uuid');
const filesystem = require('./fs.util');
const database = require('./db.util');
const mask = require('./mask.image.util');
const { recognize, normalize } = require('./detectors/actions');
const { STORAGE, SAVE } = require('../constants');
const DETECTORS = require('../constants/config').detectors();
Expand All @@ -30,6 +31,9 @@ module.exports.polling = async (event, { retries, id, type, url, breakMatch, MAT
const promises = [];
filesystem.writer(tmp, stream);

const maskBuffer = await mask(event, tmp);
if (maskBuffer) filesystem.writer(tmp, maskBuffer);

for (const detector of DETECTORS) {
promises.push(this.process({ attempt: attempts, detector, tmp }));
}
Expand Down

0 comments on commit decb245

Please sign in to comment.