OpenCv 从连续数据数组创建 3 通道 Mat

OpenCv create 3 channel Mat from continuous data array

我想使用分配在每个通道的像素在一起的其他地方的数据创建一个 OpenCV 3 通道垫,这与来自不同通道的数据交错的 OpenCV 垫的数据不同。

Mat outputMat = Mat(dimY, dimX, CV_8UC3, rawData); 
// This works only if rawData interleaves channel data like an OpenCv Mat

有没有一种方法可以创建 OpenCV Mat 而不必求助于以下从临时 Mat 中拆分通道并将正确的通道数据复制到相应位置的解决方案?

void createMat(unsigned char *rawData, unsigned int dimX, unsigned int dimY)
{
    Mat outputMat = Mat(dimY, dimX, CV_8UC3);

    // use outputMat to draw some stuff

    Mat channelR = Mat(dimY, dimX, CV_8UC1, rawData);
    Mat channelG = Mat(dimY, dimX, CV_8UC1, rawData + dimX * dimY);
    Mat channelB = Mat(dimY, dimX, CV_8UC1, rawData + 2 * dimX * dimY);

    std::vector<Mat> channels(3);
    split(outputMat, channels);

    channels[2].copyTo(channelR);
    channels[1].copyTo(channelG);
    channels[0].copyTo(channelB);
}

我需要经常做这个操作,所以我想知道是否有解决方案,不需要每次都调用split()copyTo()函数。

谢谢!

您可以直接使用merge来避免splitcopyTo

Mat createMat(unsigned char *rawData, unsigned int dimX, unsigned int dimY)
{
    // No need to allocate outputMat here
    Mat outputMat;

    // Build headers on your raw data
    Mat channelR(dimY, dimX, CV_8UC1, rawData);
    Mat channelG(dimY, dimX, CV_8UC1, rawData + dimX * dimY);
    Mat channelB(dimY, dimX, CV_8UC1, rawData + 2 * dimX * dimY);

    // Invert channels, 
    // don't copy data, just the matrix headers
    std::vector<Mat> channels{ channelB, channelG, channelR };

    // Create the output matrix
    merge(channels, outputMat);

    return outputMat;
}

我测试了其他几种方法,但它们的速度较慢。仅作记录,我认为这样会更快,但转置真的很重:

Mat outputMat(3, dimY*dimX, CV_8UC1, rawData);
Mat tmp = outputMat.t();
outputMat = tmp.reshape(3, dimY);
cvtColor(outputMat, outputMat, COLOR_RGB2BGR);