1

I want to transfer image data on websocket by using boost library.

How should I resolve below error?

At first, I confirmed to be able to transfer and receive text data by referring following URL. https://www.boost.org/doc/libs/1_68_0/libs/beast/doc/html/beast/quick_start.html

And next, although I tried to transfer image, I got following error message.

 websocket_client.cpp:563:38: error: no matching function for call to 'buffer(cv::Mat&)'

 ws.write(boost::asio::buffer(img));

What I did are below.

  1. read image file as 'img' by using opencv.

  2. Change the code for transfer data

    // Send the message
    
    // ws.write(boost::asio::buffer(std::string(text)));
    
    ws.write(boost::asio::buffer(img));
    
sehe
  • 374,641
  • 47
  • 450
  • 633
haru
  • 11
  • 3
  • https://www.boost.org/doc/libs/1_66_0/doc/html/boost_asio/reference/buffer.html You need to cast it to an appropriate format which is supported by boost buffer. There is no matching overload which takes 'Mat&' – Build Succeeded Jan 28 '21 at 04:17

1 Answers1

0

cv::Mat is not a buffer type or adaptable as such. If you have POD data, then you can "cast" it like the commenter says:

 // don't do this:
 buffer(&img, sizeof(img));

However, that's not safe:

static_assert(std::is_standard_layout_v<cv::Mat>);
static_assert(std::is_trivial_v<cv::Mat>);

The type is actually not bitwise copyable. But since there's a matrix, there is likely a contiguous region of data that is:

ws.write(net::buffer(img.data, img.total() * img.elemSize()));

This uses total() and elemSize(), links to the documentation.

Now, this will be enough if the receiving end already knows the dimensions. If not, send them first, e.g.:

uint32_t dimensions[] { htonl(image_witdh), htonl(image_height) };

std::vector<net::const_buffer> buffers {
    net::buffer(dimensions),
    net::buffer(img.data, img.total() * img.elemSize())
};
ws.write(buffers);
sehe
  • 374,641
  • 47
  • 450
  • 633
  • I succeed to transfer image to server as binary. But I can't show image. How could I do this? Error message img = np.frombuffer(message, dtype=np.uint8) #NG TypeError: a bytes-like object is required, not 'str' – haru Jan 29 '21 at 03:23
  • I'm afraid you're in [X/Y problem](https://en.wikipedia.org/wiki/XY_problem#:~:text=The%20XY%20problem%20is%20a,them%20to%20resolve%20issue%20X.). If you had asked "how do I display an image received over websockets" you will get entirely different answers. https://stackoverflow.com/questions/9292133/receiving-image-through-websocket – sehe Jan 29 '21 at 16:27