任务要求:
客户端把图片转成opencv的mat类型,封装进json,发给服务端,服务收到后解析json,再把mat把存成图片;用C++实现
解决方案:
发送和接收就不写了,这里只展示下如何封装以及如何解析。
用到的头文件:1.nlohmann::json的json.hpp;2.csdn上找的用于base64编码的base64.h
1)读取并封装
json j;
Mat image = imread("D:\\4.jpg"); //存放自己图像的路径
//imshow("显示图像", image);
std::vector<unsigned char> data_encode;
int res = imencode(".jpg", image, data_encode);
std::string str_encode(data_encode.begin(), data_encode.end());
const char* c = str_encode.c_str();
j["mat"] = base64_encode(c, str_encode.size());
代码是参考(c++ opencv imencode imdecode string转换)自己的改动尝试出来,这里有个疑问,按照这个代码str_encode就是一个string类型的变量,但是直接赋给json就会报错(异常: nlohmann::detail::type_error,位于内存位置 0x0000009DA751D568 处),这是为什么??所以又进行了一次base64编码(不知道有没有其他办法),因为base64_encode这个函数的第一个参数要求是const char*,所以做了一下类型转换,因为对C++数据类型的不了解,这几天一直被char*、const char*、unsigned char。。。。这些类型折磨
2)解析并保存
for (json::iterator it = j.begin(); it != j.end(); ++it) {
//std::cout << it.key() << " : " << it.value() << "\n";
if (it.key() == "mat")
{
Mat img_decode;
std::string str_tmp = base64_decode(it.value());
std::vector<uchar> data(str_tmp.begin(), str_tmp.end());
img_decode = imdecode(data, CV_LOAD_IMAGE_COLOR);
imwrite( "D:\\i.jpg", img_decode);
imshow("pic", img_decode);
waitKey(10);
}
}