Wednesday 3 March 2021

How to convert to opencv Mat to float based on NCHW in C++?

 void convertToVector(cv::Mat &img, std::vector<float> &values, int count)
{
    std::vector<float> normalize(3, 1);
    normalize = {255, 255, 255};
    std::vector<float> mean(3, 0);
    std::vector<float> std(3, 1);
    bool bgrtorgb = false;
    int size = img.cols * img.rows;
    int channel = img.channels();
    std::cout << size << " " << channel << std::endl;

    //    for (int i = 0; i < steps.size(); i++) {
    //      auto step = steps[i];
    //      if (step == "subtract128") {
    //        mean = {128, 128, 128};
    //        std = {1, 1, 1};
    //        normalize = {1, 1, 1};
    //      } else if (step == "normalize") {
    //        normalize = {255, 255, 255};
    //      } else if (step == "mean") {
    //        mean = {0.406f, 0.456f, 0.485f};
    //      } else if (step == "std") {
    //        std = {0.225f, 0.224f, 0.229f};
    //      } else if (step == "bgrtorgb") {
    //        bgrtorgb = true;
    //      } else {
    //        CAFFE_ENFORCE(
    //            false,
    //            "Unsupported preprocess step. The supported steps are: subtract128, "
    //            "normalize,mean, std, swaprb.");
    //      }
    //    }

    int C = channel ? 3 : 1;
    int total_size = C * size;
    // std::vector<float> values(total_size);
    if (C == 1)
    {
        cv::MatIterator_<float> it, end;
        int idx = 0;
        for (it = img.begin<float>(), end = img.end<float>(); it != end; ++it)
        {
            values[idx++] = (*it / normalize[0]);
        }
    }
    else
    {
        int i = count;
            
        cv::Mat_<cv::Vec3b>::iterator it, end;
        int b = bgrtorgb ? 2 : 0;
        int g = 1;
        int r = bgrtorgb ? 0 : 2;
        for (it = img.begin<cv::Vec3b>(), end = img.end<cv::Vec3b>(); it != end; ++it, i++)
        {
            //std::cout << (int)(*it)[b] << " " << (int)(*it)[g] << " " << (int)(*it)[r] << std::endl;
            values[i] = (((*it)[b] / normalize[0]));
            int offset = size + i;
            values[offset] = (((*it)[g] / normalize[1]));
            offset = size + offset;
            values[offset] = (((*it)[r] / normalize[2]));
        }
    }
}

No comments:

Post a Comment