You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

OpenCV Mat转coder::array<unsigned short,2U>实现问题咨询

将OpenCV cv::Mat 转换为 MATLAB Coder array 的实现方案

我已经把DICOM图像读取到OpenCV的cv::Mat矩阵中,现在需要调用MATLAB生成的C++函数——该函数要求输入coder::array<unsigned short, 2U>类型的数据,因此需要把cv::Mat的像素数据转换为这个类型。我尝试了以下代码,希望将图像的行列像素数据对应存入目标数组的对应维度:

coder::array<unsigned short, 2U> argInit_ImageArray(const cv::Mat& image)
{
    unsigned short rows = image.rows;
    unsigned short cols = image.cols;
    const unsigned short* pixelData = (unsigned short*)image.data;

    coder::array<unsigned short, 2U> result({rows, cols});
    unsigned short *pixelDataPointer = (unsigned short*)pixelData;

    for (int i = 0; i < rows; i++) {
        for (int j = 0; j < cols; j++) {
            result.at(i,j) = pixelDataPointer[i * cols + j];
        }
    }
    return result;
}

代码说明与优化提示

  • 像素格式校验:确保输入的image是CV_16U类型(16位无符号整数),否则强制转换unsigned short*会导致数据错误。可以在函数开头添加校验逻辑:
    if (image.type() != CV_16U) {
        throw std::invalid_argument("输入图像必须是CV_16U格式");
    }
    
  • 内存拷贝优化:如果cv::Mat是连续存储的(可通过image.isContinuous()判断),可以用memcpy替代嵌套循环提升效率:
    if (image.isContinuous()) {
        memcpy(result.data(), pixelData, rows * cols * sizeof(unsigned short));
    } else {
        for (int i = 0; i < rows; i++) {
            memcpy(result.data() + i * cols, image.ptr<unsigned short>(i), cols * sizeof(unsigned short));
        }
    }
    
  • 维度顺序注意:MATLAB默认采用列优先(column-major)存储,而OpenCV的cv::Mat是行优先(row-major)。如果MATLAB生成的函数期望列优先数据,原代码的索引逻辑会导致数据排列错误,需调整索引为j * rows + i,或者创建coder::array时交换行列顺序:
    coder::array<unsigned short, 2U> result({cols, rows});
    // 对应调整后续索引逻辑
    

内容的提问来源于stack exchange,提问作者Vukosi Mboweni

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.02 00:57:22