Skip to content

Instantly share code, notes, and snippets.

@Zebiano
Last active August 4, 2021 08:04
Show Gist options
  • Save Zebiano/172c952e6d7fa563a33dcaaac106a01e to your computer and use it in GitHub Desktop.
Save Zebiano/172c952e6d7fa563a33dcaaac106a01e to your computer and use it in GitHub Desktop.
`matchTemplate()` with transparency and opencv4nodejs
// Gist made mainly for https://stackoverflow.com/questions/15459090/how-to-find-a-template-in-an-image-using-a-mask-or-transparency-with-opencv-an
// It's also where I've gotten the images from
// Require: Packages
const openCv = require('opencv4nodejs')
// Variables
const image = openCv.imread('stop_leaves.png')
// const image = openCv.imread('stop_moon.png')
// const image = openCv.imread('stop_mountain.png')
const template = openCv.imread('stop.png')
// Match with template as both template and mask parameter
// As of writing this file, opencv4nodejs only supports method 0 and 3 with a mask. I've had more success with 3
const minMax = image.matchTemplate(template, 3, template).minMaxLoc()
// Uncomment if you want to see the difference in probability without the mask
// const minMax = image.matchTemplate(template, 3).minMaxLoc()
// Log info
console.log(`Probability: ${minMax.maxVal}`)
// Draw a rectangle around found image
image.drawRectangle(
new openCv.Rect(minMax.maxLoc.x, minMax.maxLoc.y, template.cols, template.rows),
new openCv.Vec(0, 255, 0),
2,
openCv.LINE_8
)
// Show image in new window
openCv.imshow('Template matching with transparency', image)
openCv.waitKey()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment