به صورت زیر:
namespace nlohmann
{
template<>
struct adl_serializer<cv::Mat>
{
static inline void to_json(json& j, const cv::Mat& image)
{
if (image.depth() == CV_32F) {
std::vector<float> data;
data.assign((float*)image.data, (float*)image.data + image.total() * image.channels());
j =
nlohmann::json
{
{"width", image.cols},
{"height", image.rows},
{"depth", image.depth()},
{"channels", image.channels()},
{"data", data}
};
}
else if (image.depth() == CV_8U) {
std::vector<uchar> data;
data.assign((uchar*)image.data, (uchar*)image.data + image.total() * image.channels());
j =
nlohmann::json
{
{"width", image.cols},
{"height", image.rows},
{"depth", image.depth()},
{"channels", image.channels()},
{"data", data}
};
}
}
static inline void from_json(const json& j, cv::Mat& image)
{
int width, height, channels, depth;
j.at("width").get_to(width);
j.at("height").get_to(height);
j.at("channels").get_to(channels);
j.at("depth").get_to(depth);
if (depth == CV_32F) {
std::vector<float> data;
j.at("data").get_to(data);
image = cv::Mat(height, width, CV_MAKETYPE(depth, channels),data.data());
}
else if (depth == CV_8U) {
std::vector<uchar> data;
j.at("data").get_to(data);
cv::Mat img = cv::Mat(height,width, CV_MAKETYPE(depth, channels), data.data(),width*channels);
image = img.clone();
}
}
};
}