2016-01-10 73 views
0

我有Matces數據訪問問題。我在圖片上執行操作,並且需要分離地訪問每個像素。 我必須對簡單類型(float,int等)進行必要的操作。 我accesing數據的方法是象下面這樣:OpenCv墊到陣列訪問

for (int idx = 0; idx < image.rows; idx++) { 
     for (int idy = 0; idy < image.cols; idy++) { 
      int color_tid = idx * image.cols * image.channels() + idy * image.channels(); 
      uint8_t blue = image.data[color_tid]; 
      uint8_t green = image.data[color_tid + 1]; 
      uint8_t red = image.data[color_tid + 2]; 
      float pixelVal = (int) blue + (int) green + (int) red; 
      (...) 
     } 
    } 

這種方法是否正常工作只方形的圖像(N×N像素),但對於N×M個有正方形區域(小刃)之外的異常。 有誰知道任何其他方式來訪問圖片墊的數據? 示例圖片(正確的結果):

enter image description here

異常(我的問題)

enter image description here

+2

沒有看到所有的代碼,很難說這是怎麼回事。然而,在你的循環內,你可以寫:'Vec3b v = image(row,col); float pixelVal = v [0] + v [1] + v [2];'。還要記住_rows_是_y_座標,而_cols_是_x_。所以你可能只是換了你的指數。 – Miki

+0

Vec3b v不是簡單的類型...我必須使用image.data –

+0

你**必須** ....是功課還是什麼? – Miki

回答

1

我建議遵循data layoutMat

enter image description here

所以你的循環變成:

for (int r = 0; r < img.rows; ++r) 
{ 
    for (int c = 0; c < img.cols; ++c) 
    { 
     uchar* ptr = img.data + img.step[0] * r + img.step[1] * c; 
     uchar blue = ptr[0]; 
     uchar green = ptr[1]; 
     uchar red = ptr[2]; 

     float pixelVal = blue + green + red; 
    } 
} 

最後,您可以執行像少一些操作:

for (int r = 0; r < img.rows; ++r) 
{ 
    uchar* pt = img.data + img.step[0] * r; 
    for (int c = 0; c < img.cols; ++c) 
    { 
     uchar* ptr = pt + img.step[1] * c; 
     uchar blue = ptr[0]; 
     uchar green = ptr[1]; 
     uchar red = ptr[2]; 

     float pixelVal = blue + green + red; 
    } 
} 
+0

Thx爲迴應,但您的方法會產生像我一樣的問題。明天我會詳細檢查它,並會寫出如果確切的問題 –

+0

@ jak5z這工作正常,並且還處理非連續的矩陣。但是你的方法在連續矩陣上工作正常,所以我敢打賭,問題在於你如何傳遞數據。再次,沒有[mcve],很難說。 – Miki

+0

我沒有使用這個metod,但我知道很好。謝謝 –

1

在你的問題中的代碼包含了一些缺陷:

  • 行和列被交換(行是Y,列是X)
  • 行之間的步長(又名「步幅」)並不總是等於列

使用Mat::at<>的數量使得代碼更簡單:

for(int row = 0; row < image.rows; ++row) 
{ 
    for(int col = 0; col < image.cols; ++col) 
    { 
     const Vec3b& pt = image.at<Vec3b>(row, col); 
     float pixelVal = pt[0] + pt[1] + pt[2]; 
     ...  
    } 
} 
+0

const Vec3b&pt = image.at (row,col);不是簡單的類型...我必須使用image.data –

+0

@ jak5z:Miki的解決方案也應該爲你工作。我很驚訝它沒有。 – alexm