2011-06-25 85 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"); 
    } 
}