2012-08-29 160 views
1

以及我的問題是,我需要找到包含全部白色像素的cv :: Mat圖像的子矩陣。因此,我想遍歷所有像素,檢查它們是否是白色,並用該信息構建cv :: Rect。
我想出瞭如何遍歷所有的像素,但我不知道如何從中獲取像素的顏色。簡歷::墊先前轉換與CV_GRAY2BGR在特定位置找到cv :: Mat的像素顏色

for(int y = 0; y < outputFrame.rows; y++) 
{ 
    for(int x = 0; x < outputFrame.cols; x++) 
    { 
     // I don't know which datatype I should use 
     if (outputFrame.at<INSERT_DATATYPE_HERE>(x,y) == 255) 
      //define area 
    } 
} 

我的最後一個問題是,我應該在代碼中插入上INSERT_DATATYPE_HERE的位置,其數據類型,併爲255比比較正確的價值爲灰度?

非常感謝

+0

可能重複[循環通過像素與opencv](http://stackoverflow.com/questions/4504687/cycle-through-pixels-with-opencv) – Sam

回答

7

這取決於您的圖像頻道。 Mat有方法channels。它返回通道數量 - 它是一個如果圖像是灰色的,三個如果圖像是彩色的(例如,RGB - 每個顏色分量一個通道)。

所以,你必須做這樣的事情:

if (outputFrame.channels() == 1) //image is grayscale - so you can use uchar (1 byte) for each pixel 
{ 
    //... 
    if (outputFrame.at<uchar>(x,y) == 255) 
    { 
     //do a check if this pixel is the most left, or the most right, or the most top, or the most bottom (this is needed to construct result rectangle) 
    } 
} 
else 
if (outputFrame.channels() == 3) //image is color, so type of each pixel if Vec3b 
{ 
    //... 
    // white color is when all values (R, G and B) are 255 
    if (outputFrame.at<Vec3b>(x,y)[0] == 255 && outputFrame.at<Vec3b>(x,y)[1] == 255 && outputFrame.at<Vec3b>(x,y)[2] == 255) 
    { 
     //do a check if this pixel is the most left, or the most right, or the most top, or the most bottom (this is needed to construct result rectangle) 
    } 
} 

但實際上獲得的矩形包含在圖像中的所有白色像素,您可以使用另一種方法:

  1. Convert image to grayscale
  2. 做一個值爲254(或接近255)作爲參數的threshold
  3. Find all contours on image
  4. 構造一個包含所有這些輪廓的輪廓(只需將每個輪廓的所有點添加到一個大輪廓中)。使用bounding rectangle function找到你需要的矩形。
+0

通道== 1似乎工作,不幸的是'if(outputFrame.at (y,x)== 255)'總是如此,你有解決這個問題的想法嗎? – Seega

+0

你比白色圖像。發表它。而且爲什麼'(y,x)'不是'(x,y)'? – ArtemStorozhuk

+0

工作,我很愚蠢,第一幀始終是白色的,但由於每個像素的cout非常緩慢,我從來沒有等待,直到第一幀處理。非常感謝!我也會嘗試輪廓檢測。再次感謝 – Seega