Missing module functions with manually built OpenCV
Hi there,
I am currently working on a Lambda layer for object detection trying to use this module. Unfortunately I am having some issues after installing it.
My build process of OpenCV:
curl -L https://github.com/opencv/opencv/archive/refs/tags/4.10.0.tar.gz | tar zx && \ cd opencv-4.10.0 && mkdir -p build && cd build && cmake \ -DCMAKE_INSTALL_PREFIX=/opt \ -DBUILD_LIST=dnn,objdetect,imgcodecs \ -DBUILD_TESTS=OFF \ -DBUILD_PERF_TESTS=OFF \ .. && cmake --build . --target install
I am setting the needed environment variables accordingly and then install the module via npm without issues. After installation I run some code to verify the installation:
import cv from '@u4/opencv4nodejs';
console.log(cv);
const image = cv.imread('image.jpg');
Which errors:
const image = cv.imread('image.jpg');
^
TypeError: cv.imread is not a function
at Object.<anonymous> (/var/task/test.cjs:4:18)
at Module._compile (node:internal/modules/cjs/loader:1369:14)
at Module._extensions..js (node:internal/modules/cjs/loader:1427:10)
at Module.load (node:internal/modules/cjs/loader:1206:32)
at Module._load (node:internal/modules/cjs/loader:1022:12)
at Function.executeUserEntryPoint [as runMain] (node:internal/modules/run_main:135:12)
at node:internal/main/run_main_module:28:49
Node.js v20.12.0
Logging the cv object I can see there are many functions, e.g. from dnn available...but not from imgcodecs.
Having a look into the lib64 directory of OpenCV I can see that imgcodecs lib is present.
Any leads on what is missing would be appreciated. Thanks.
Doing the same thing. Exact same issue. Find any solution?
I've been debugging and found that imgcodecs module is missing when imported from node. I verified that it's present in my opencv, but no matter what I set for opencv4nodejs, that module doesn't get included.
I found an alternative. Since only imgcodecs was missing, I just couldn't use imread or imwrite. But since I was already using Sharp & have a layer for it, I'm using it to convert the image instead.
# replace imread
async function loadImageWithSharpToMat(imagePath) {
const { data, info } = await sharp(imagePath)
.raw()
.ensureAlpha()
.toBuffer({ resolveWithObject: true });
// RGBA → Mat
const matRGBA = new cv.Mat(data, info.height, info.width, cv.CV_8UC4);
// Convert to BGR (OpenCV default)
const matBGR = matRGBA.cvtColor(cv.COLOR_RGBA2BGR);
return matBGR;
}
function matToSharpBuffer(mat): Buffer {
const matRGBA = mat.cvtColor(cv.COLOR_BGR2RGBA);
return Buffer.from(matRGBA.getData());
}
# replace imwrite
async function saveMatAsImageSharp(imagePath: string, mat) {
const buffer = matToSharpBuffer(mat);
await sharp(buffer, {
raw: {
width: mat.cols,
height: mat.rows,
channels: 4, // RGBA
}
}).toFile(imagePath);
}