【问题标题】:Accessing value at row,col in a Matrix访问矩阵中行、列的值
【发布时间】:2011-06-29 16:37:03
【问题描述】:

我正在尝试访问矩阵中的特定行,但很难做到。

我想获取第 j 行第 i 列的值,但我认为我的算法不正确。我正在为我的矩阵使用 OpenCV 的 Mat 并通过数据成员访问它。

这是我尝试访问值的方式:

plane.data[i + j*plane.rows]

其中 i = 列,j = 行。这个对吗?矩阵是 YUV 矩阵的 1 个平面。

任何帮助将不胜感激!谢谢。

【问题讨论】:

    标签: opencv matrix


    【解决方案1】:

    不,你错了 plane.data[i + j*plane.rows] 不是访问像素的好方法。您的指针必须取决于矩阵的类型及其深度。 您应该使用矩阵的 at() 运算符。

    为了简单起见,这里有一个代码示例,它访问矩阵的每个像素并打印它。它几乎适用于每种矩阵类型和任意数量的通道:

    void printMat(const Mat& M){
        switch ( (M.dataend-M.datastart) / (M.cols*M.rows*M.channels())){
    
        case sizeof(char):
             printMatTemplate<unsigned char>(M,true);
             break;
        case sizeof(float):
             printMatTemplate<float>(M,false);
             break;
        case sizeof(double):
             printMatTemplate<double>(M,false);
             break;
        }
    }
    
    
    template <typename T>  
    void printMatTemplate(const Mat& M, bool isInt = true){
        if (M.empty()){
           printf("Empty Matrix\n");
           return;
        }
        if ((M.elemSize()/M.channels()) != sizeof(T)){
           printf("Wrong matrix type. Cannot print\n");
           return;
        }
        int cols = M.cols;
        int rows = M.rows;
        int chan = M.channels();
    
        char printf_fmt[20];
        if (isInt)
           sprintf_s(printf_fmt,"%%d,");
        else
           sprintf_s(printf_fmt,"%%0.5g,");
    
        if (chan > 1){
            // Print multi channel array
            for (int i = 0; i < rows; i++){
                for (int j = 0; j < cols; j++){         
                    printf("(");
                    const T* Pix = &M.at<T>(i,j);
                    for (int c = 0; c < chan; c++){
                       printf(printf_fmt,Pix[c]);
                    }
                    printf(")");
                }
                printf("\n");
            }
            printf("-----------------\n");          
        }
        else {
            // Single channel
            for (int i = 0; i < rows; i++){
                const T* Mi = M.ptr<T>(i);
                for (int j = 0; j < cols; j++){
                   printf(printf_fmt,Mi[j]);
                }
                printf("\n");
            }
            printf("\n");
        }
    }
    

    【讨论】:

      【解决方案2】:

      我认为访问 RGB Mat 和 YUV Mat 之间没有什么不同。只是色彩空间不同。

      如何访问每个像素请参考http://opencv.willowgarage.com/wiki/faq#Howtoaccessmatrixelements.3F

      【讨论】:

        猜你喜欢
        • 2020-05-18
        • 2019-12-03
        • 1970-01-01
        • 2013-01-17
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2021-08-03
        • 1970-01-01
        相关资源
        最近更新 更多