Skip to content

Instantly share code, notes, and snippets.

@pirosuke
Created January 19, 2019 17:15
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save pirosuke/5ffcddef15cd308aeb31ffa27495f3fe to your computer and use it in GitHub Desktop.
Save pirosuke/5ffcddef15cd308aeb31ffa27495f3fe to your computer and use it in GitHub Desktop.
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