Skip to content

Instantly share code, notes, and snippets.

@zhylmzr
Last active January 5, 2024 04:04
Show Gist options
  • Save zhylmzr/1af1ee009daa1506f5156dd7d55114e3 to your computer and use it in GitHub Desktop.
Save zhylmzr/1af1ee009daa1506f5156dd7d55114e3 to your computer and use it in GitHub Desktop.
use opencv in node.js with typescript
  1. download precompile's opencv.js to src/opencv.js
  2. download Lenna png to Lenna.png
  3. save index.ts and global.d.ts in src/ directory
  4. npm run build && npm run cp
  5. npm run run

full directory tree:

.
├── Lenna.png
├── README.md
├── output.png
├── package.json
├── src
│   ├── global.d.ts
│   ├── index.ts
│   └── opencv.js
└── tsconfig.json
declare global {
/** opencv's export variable */
var Module: Object
}
export {}
import Jimp from 'jimp'
async function onRuntimeInitialized() {
// load local image file with jimp. It supports jpg, png, bmp, tiff and gif:
var jimpSrc = await Jimp.read('./Lenna.png')
// `jimpImage.bitmap` property has the decoded ImageData that we can use to create a cv:Mat
var src = cv.matFromImageData(jimpSrc.bitmap)
// following lines is copy&paste of opencv.js dilate tutorial:
let dst = new cv.Mat()
let M = cv.Mat.ones(50, 50, cv.CV_8U)
let anchor = new cv.Point(-1, -1)
cv.dilate(src, dst, M, anchor, 1, cv.BORDER_CONSTANT, cv.morphologyDefaultBorderValue())
// Now that we are finish, we want to write `dst` to file `output.png`. For this we create a `Jimp`
// image which accepts the image data as a [`Buffer`](https://nodejs.org/docs/latest-v10.x/api/buffer.html).
// `write('output.png')` will write it to disk and Jimp infers the output format from given file name:
new Jimp({
width: dst.cols,
height: dst.rows,
data: Buffer.from(dst.data),
}).write('output.png')
src.delete()
dst.delete()
}
// Finally, load the open.js as before. The function `onRuntimeInitialized` contains our program.
globalThis.Module = {
onRuntimeInitialized,
}
const cv: typeof import('mirada') = require('./opencv')
{
"name": "cv-hello",
"module": "index.ts",
"scripts": {
"build": "esbuild src/index.ts --outdir=dist --minify --platform=node --format=cjs",
"cp": "cp src/opencv.js ./dist",
"run": "node dist/index.js"
},
"devDependencies": {
"esbuild": "^0.19.2",
"mirada": "^0.0.15"
},
"dependencies": {
"jimp": "^0.22.10"
}
}
{
"compilerOptions": {
"lib": ["ESNext"],
"module": "esnext",
"target": "esnext",
"strict": true,
"allowJs": true,
"noEmit": true,
"noImplicitAny": false,
},
"include": [
"src/**/*.ts"
]
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment