2011-06-25 99 views
2

可能重复:
Pixel access in OpenCV 2.2读取的像素值++(OpenCV的)

我想知道我会如何用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 ; 

     } 
    } 

} 

上面的代码打印垃圾值。

+0

你的意思是垃圾?你期望它打印什么?你有没有尝试过一个简单的输入图像,比如1x2?如何在valgrind下运行以检查内存访问问题? –

+5

确切的重复:http://stackoverflow.com/q/4742251/176769 – karlphillip

+0

你没有把那里的权利铸在image.at <>(可惜的是,OpenCV并没有为此抱怨......)。你可以在这里检查正确的投影:[(link)](http://stackoverflow.com/questions/13484475/what-are-the-upper-and-lower-limits-of-pixel-values-in-opencv) –

回答

5

这是一个非常好的问题。当你知道矩阵的通道类型和数量时,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 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"); 
    } 
}