I tried to use template matching in opencv.js (node.js environment)
test.js
const { matchTemplate } = require('./matchTemplate.js')
matchTemplate()
matchTemplate()
matchTemplate()
matchTemplate()
matchTemplate()
matchTemplate.js
const sharp = require('sharp')
function loadOpenCV() {
return new Promise((resolve) => {
global.Module = {
onRuntimeInitialized: resolve
}
global.cv = require('./opencv.js')
})
}
async function matchTemplate() {
await loadOpenCV()
const src = await readImageSharp('./images/fullscreen/000.PNG')
const templ = await readImageSharp('./images/tiles/16.PNG')
const dst = new cv.Mat()
const mask = new cv.Mat()
cv.matchTemplate(src, templ, dst, cv.TM_CCOEFF_NORMED, mask)
const result = cv.minMaxLoc(dst, mask).maxVal
for (const x of [src, templ, dst, mask]) {
x.delete()
}
console.log(result)
async function readImageSharp(input) {
const { data, info } = await sharp(input)
.ensureAlpha()
.raw()
.toBuffer({ resolveWithObject: true })
const { width, height } = info
return cv.matFromImageData({ data, width, height })
}
}
module.exports = { matchTemplate }
when I run in command line
PS R:\mahjong\FYP22070> node test.js
1
PS R:\mahjong\FYP22070>
The function matchTemplate() is executed once only.
My question is, how can I export function matchTemplate(), so that I can execute in other JavaScript files for multiple times?