Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
Convert Image Files To Line Drawings With OpenCV And Node.js
const path = require('path');
const fs = require('fs');
const cv = require('opencv4nodejs');
function convertImageToLineDrawing(img) {
const kernel = new cv.Mat([
[1, 1, 1, 1, 1],
[1, 1, 1, 1, 1],
[1, 1, 1, 1, 1],
[1, 1, 1, 1, 1],
[1, 1, 1, 1, 1],
], cv.CV_8U);
const imgGray = img.cvtColor(cv.COLOR_RGBA2GRAY);
const imgDilated = imgGray.dilate(kernel, new cv.Point2(-1, 1), 1);
const imgDiff = imgDilated.absdiff(imgGray);
const contour = imgDiff.bitwiseNot();
return contour;
}
function convertImagesToLineDrawing(srcDirPath, destDirPath) {
const srcFileList = fs.readdirSync(srcDirPath);
for (const srcFileName of srcFileList) {
if (!srcFileName.endsWith('.JPG')) {
continue;
}
console.log('Processing ', srcFileName, '...');
const imgMat = cv.imread(path.join(srcDirPath, srcFileName));
const imgMatConverted = convertImageToLineDrawing(imgMat);
cv.imwrite(path.join(destDirPath, srcFileName), imgMatConverted);
}
}
function main() {
const srcDirPath = 'SOURCE_DIRECTORY_PATH';
const destDirPath = 'DEST_DIRECTORY_PATH';
convertImagesToLineDrawing(srcDirPath, destDirPath);
}
main();
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
You can’t perform that action at this time.