如何在 nodejs 插件中返回 cv::Mat [英] How to return cv::Mat in nodejs addon

查看:31
本文介绍了如何在 nodejs 插件中返回 cv::Mat的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我使用 V8 编写了 nodejs 插件.我被困在我试图返回 Mat 的地方,但我得到的只是大小为 2mb 的损坏图像(对于特定图像).难道我做错了什么?我如何使用 V8 做到这一点?

I've written nodejs addon using V8. I'm stuck at a point where I'm trying to return Mat but all I'm getting is corrupted image with size of 2mb (for particular image). Am I doing something wrong? How can I do this using V8?

CPP 代码片段

cv::Mat image = ...
std::string my_cv_mat(image.begin<unsigned char>(), image.end<unsigned char>());
args.GetReturnValue().Set(v8::String::NewFromUtf8(isolate, my_cv_mat.c_str()).ToLocalChecked());

Nodejs 代码片段

Nodejs code snippet

// body is express req.body
let bodyBuffer = new Buffer.from(body, "binary");
let detectedFaces = faceDetect.detect(bodyBuffer)  //here I'm reading above Mat image into char string
const out_file = path.basename("output.png")
fs.writeFileSync(out_file, new Buffer.from(detectedFaces, "binary"))

--- 更新 ---

我已经更新了代码,但输出图像仍然不是图像,它的大小现在是 23mb 而应该是 700kb.

I've made update in the code but output image is still not image and its size is now 23mb while it should be 700kb.

CPP 更新的代码片段

CPP updated code snippet

  unsigned int img_size = image.total() * image.elemSize();
  char* image_char = reinterpret_cast<char*>(image.data);
  Nan::MaybeLocal<v8::Object> imageBuffer = Nan::CopyBuffer(image_char, img_size);
  // args.GetReturnValue().Set(v8::String::NewFromUtf8(isolate, my_cv_mat.c_str()).ToLocalChecked());
  args.GetReturnValue().Set(imageBuffer.ToLocalChecked());

nodejs 代码片段

nodejs code snippet

    let detectedFaces = faceDetect.detect(bodyBuffer)
    const out_file = path.basename("output.png")
    fs.writeFileSync(out_file, new Buffer.from(detectedFaces, "binary"))

推荐答案

我不认为是 UTF-8 编码的字符串(或者,更准确地说:从您告诉 String 构造函数的原始图像数据构造 JavaScript 字符串将其视为 UTF-8 并进行相应解码)是完成这项工作的正确工具.

I don't think a UTF-8 encoded string (or, more accurately: constructing a JavaScript string from raw image data that you're telling the String constructor to treat as UTF-8 and decode accordingly) is the right tool for the job.

尝试直接在您的插件中创建一个缓冲区,并将其作为调用结果返回(而不是 v8::String).

Try creating a Buffer directly in your addon, and returning that as the call's result (instead of a v8::String).

这篇关于如何在 nodejs 插件中返回 cv::Mat的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆