读取C++(OpenCV)中的像素值

read pixel value in C++ (OpenCV)

本文关键字:像素 C++ OpenCV 读取      更新时间:2023-10-16

可能重复:
OpenCV 2.2 中的像素访问

我想知道如何使用Mat类读取C++中的像素值(整数/浮点格式)?

很多人都问过同样的问题,但没有具体的工作答案。

我有以下代码可以编译,但没有给出正确的结果。

void Block(cv::Mat &image)
{
    for(int row = 0; row < image.rows; ++row)
    {
        for (int col = 0; col < image.cols; ++col)
     {
            cout<<image.at<int>(row, col)<<endl ;
        }
    }
}

上面的代码打印垃圾值。

这是一个非常好的问题。当你知道矩阵中频道的类型和数量时,Wiki会帮助你。如果你没有,那么你需要一个switch语句。这里有一个简单的代码示例,可以打印几乎任何类型矩阵的值/像素:

// Main print method which includes the switch for types    
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;
        }
    }
// Print template using printf("%d") for integers and %g for floats
template <typename T>  
void printMatTemplate(const Mat& M, bool isInt = true){
    if (M.empty()){
       printf("Empty Matrixn");
       return;
    }
    if ((M.elemSize()/M.channels()) != sizeof(T)){
       printf("Wrong matrix type. Cannot printn");
       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");
    }
}

有时我会提到这个。。参观http://www.cs.iit.edu/~agam/cs512/elect notes/opencv-intro/opencv-intro.html by Gady Adam