سریالایز کردن cv::Mat با nlohmann::json - هفت خط کد انجمن پرسش و پاسخ برنامه نویسی

سریالایز کردن cv::Mat با nlohmann::json

0 امتیاز
سلام.

همانطوری که از عنوان سوال مشخصه قصد دارم cv::Mat را سریالالیز کنم از دوستان کسی تجربه ای داره راهنمایی کنه
سوال شده آبان 22, 1400  بوسیله ی Oscar (امتیاز 127)   8 25 29

1 پاسخ

0 امتیاز
 
بهترین پاسخ

به صورت زیر:

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();
                

            }
            
        }
    };
}

 

پاسخ داده شده آبان 22, 1400 بوسیله ی farnoosh (امتیاز 8,362)   20 44 59
انتخاب شد بهمن 6, 1401 بوسیله ی مصطفی ساتکی
...