cv::Mat与std::string互转

一、cv::Mat转std::string

没找到更好的办法,只能通过vector进行中转。但memcpy效率还是挺高的

cv::Mat mat = cv::imread("d:\\1.jpg");
std::string str;
std::vector<unsigned char> buff;
cv::imencode(".jpg", mat, buff);
str.resize(buff.size());
memcpy(&str[0], buff.data(), buff.size());

二、std::string转cv::Mat

把std::string当做1行N列的数据,通过引用数据指针的方式来得到mat2。此时没有发生内存拷贝,效率较高。

cv::Mat mat2(1, str.size(), CV_8U, (char*)str.data());
cv::Mat dst = cv::imdecode(mat2, CV_LOAD_IMAGE_COLOR);

三、场景
thrift里binary类型用的std::string,项目里把cv::Mat定义为binary,就用到了这种办法。

猜你喜欢

转载自blog.csdn.net/qq_42953366/article/details/81627167