1

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 code snippet

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 code snippet

// body is express's 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"))

--- UPDATE ---

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

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(imageBuffer.ToLocalChecked());

nodejs code snippet

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

1 Answer 1

1

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.

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

Sign up to request clarification or add additional context in comments.

6 Comments

Can you please show me an example. I didn't see anything related to returning buffer directly.
I've updated the question. I did the same as saw in the example but still no luck.
What is the data format that's stored in your cv::Mat? Is it plain bitmap data, or some other format? It sounds like it's not in PNG format yet, so encoding it as (compressed?) .png would be a separate conversion step. "How to encode raw image data as PNG?" would be a separate and different question though (unrelated to Node.js, Node Addons, or V8). A node::Buffer transports the data you have, with the size that it has.
Yes, I'm [passing jpeg image as input. I'll try the way you said. @jmrk
|

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.