Hello there,
I am using OpenCV in NodeJS.
I want to crop a certain part of image and for that i need to find a landmark in the image.
This is the code i wrote:
function installDOM() {
const dom = new JSDOM();
global.document = dom.window.document;
global.Image = Image;
global.HTMLCanvasElement = Canvas;
global.ImageData = ImageData;
global.HTMLImageElement = Image;
}
function loadOpenCV() {
return new Promise(resolve => {
installDOM();
global.Module = {
onRuntimeInitialized: resolve
};
global.cv = require("./opencv");
});
}
function cropImage(PDF) {
PDFToImage(PDF).then((buffer) => {
/**
* Converted PDF to JPEG Image
* Now Use the Image Buffer as input for sharp and trim to content
*/
sharp(buffer).trim().toBuffer()
.then(async (buffer) => {
/**
* Removed White Space
* Now find the location of dashed line part with openCV
*/
let trimImage = sharp(buffer);
let img1 = await loadImage(buffer);
let img2 = await loadImage("./find.jpeg");
img1 = cv.imread(img1);
img2 = cv.imread(img2);
let canIn = createCanvas();
cv.imshow(canIn, img1);
let canFi = createCanvas();
cv.imshow(canFi, img2);
const src = cv.imread(canIn);
const temp = cv.imread(canFi);
let dest = new cv.Mat();
let mask = new cv.Mat();
cv.matchTemplate(src, temp, dest, cv.TM_CCOEFF_NORMED, mask);
let result = cv.minMaxLoc(dest, mask);
let maxPoint = result.maxLoc;
src.delete(); dest.delete(); mask.delete();
// Position from top where the dashed line was found
let cvTop = maxPoint.y + 8;
trimImage.metadata().then((meta) => {
/**
* Get width and height of image using the metadata
*/
let { width, height } = meta;
trimImage
.extract({ top: cvTop, left: 0, width: width, height: (height - cvTop) })
.toFile("./croppedFinal.jpeg");
});
})
})
};
loadOpenCV().then(() => {
let name = "SHAS2002_OCT2019.pdf"
cropImage("./pdfs/" + name);
})
The code is created while following the tutorial in the docs.
The Problem i am facing is that on some images the code is working fine but on some images it is throwing errors:
abort(6626128). Build with -s ASSERTIONS=1 for more info.
Thrown at:
at C:\Users\mss2015\Desktop\debugPDFs\opencv.js:30:1693
at emit (events.js:315:20)
at internal/process/execution.js:156:25
please see this stackoveflow question for refferance about the question.
This is the template image
I removed the scissorss from the template as the scissors can be at left or right side.
This is throwing errors mostly. And always when there is a slight change in the background color. Most of the time the background color is white but in some cases the background color is a bit greenish.
I haven’t built the openCV i am using the javascript file from here
https://docs.opencv.org/4.5.1/opencv.js
How can i make it work ? and speed it up if possible as i will be using it in cloud functions. Currently i am testing it on my pc.