socket 接收cv::mat
时间: 2023-07-23 12:37:33 浏览: 91
C++实现Socket传输json封装的Mat
可以通过将 `cv::Mat` 转换为 `std::string`,然后发送这个字符串,接收方再将字符串解析为 `cv::Mat。具体实现可以参考以下代码:
发送端:
```cpp
cv::Mat image = cv::imread("test.jpg");
cv::Size size = image.size();
int rows = size.height;
int cols = size.width;
int type = image.type();
std::string header = std::to_string(rows) + " " + std::to_string(cols) + " " + std::to_string(type) + " ";
std::string data;
cv::imencode(".jpg", image, data);
std::string message = header + data;
send(socket, message.c_str(), message.size(), 0);
```
接收端:
```cpp
std::string header;
char buffer[1024];
int recv_size = recv(socket, buffer, 1024, 0);
header.append(buffer, recv_size);
std::istringstream iss(header);
int rows, cols, type;
iss >> rows >> cols >> type;
std::string data;
int data_size = rows * cols * image.elemSize();
while (data.size() < data_size) {
recv_size = recv(socket, buffer, 1024, 0);
data.append(buffer, recv_size);
}
cv::Mat image = cv::imdecode(cv::Mat(1, data_size, CV_8UC1, data.data()), cv::IMREAD_COLOR);
image = image.reshape(0, rows);
```
阅读全文