Ask Your Question

Revision history [back]

Asking about a good way to swapbytes for a cv::Mat

Hi everyone,

I need to swap bytes for depth images with OpenCV. I just found a hack way to swap bytes order for a cv::Mat, I wonder if there is a better solution. Actually I cannot find swapbyte method for opencv online.

Anyway, here is my implementation:

void swapbytes(cv::Mat& img)
{
           int len_byte = img.elemSize();
   //      typedef char tmp_data_t[len_byte];
           {
            //the way to hack the opencv image data into the format we want
            cv::Mat toswap(img.rows, img.cols, CV_8UC(len_byte), img.data);
            int dtype = img.type();
            cv::Mat merged;
            std::vector<cv::Mat> channels(len_byte);
            cv::split(toswap, channels);
            std::reverse(channels.begin(), channels.end());
            cv::merge(&channels[0], len_byte, merged);
            merged.addref();
            img = cv::Mat(toswap.rows, toswap.cols, dtype, merged.data);
            std::cout << "here we do a small byte swap " << img.channels() << std::endl;
          }
 }