2014-09-10 160 views
2

我正在嘗試使用OpenCV從網絡攝像機抓取幀並將其轉換爲HSV(色調,飽和度,值)Mat對象並將其閾值。OpenCV訪問MAT對象中的RGB值

當我打印所有像素的閾值圖像像素值時,它給我[0,0,0],甚至黑色像素值也是[0,0,0]。 如果所選像素是黑色的,我需要做一些計算;我怎樣才能訪問像素值?

imgOriginal=frame from camera 


    Mat imgHSV; 

    cvtColor(imgOriginal, imgHSV, COLOR_BGR2HSV); //Convert the captured frame from BGR to HSV 

    Mat imgThresholded; 
    inRange(imgHSV, Scalar(iLowH, iLowS, iLowV), Scalar(iHighH, iHighS, iHighV), imgThresholded); //Threshold the image 

    //morphological opening (remove small objects from the foreground) 
    erode(imgThresholded, imgThresholded, getStructuringElement(MORPH_ELLIPSE, Size(5, 5))); 
    dilate(imgThresholded, imgThresholded, getStructuringElement(MORPH_ELLIPSE, Size(5, 5))); 

    //morphological closing (fill small holes in the foreground) 
    dilate(imgThresholded, imgThresholded, getStructuringElement(MORPH_ELLIPSE, Size(5, 5))); 
    erode(imgThresholded, imgThresholded, getStructuringElement(MORPH_ELLIPSE, Size(5, 5))); 


    //************************************ 



    std::vector<cv::Vec3b> pixels(imgThresholded.rows * imgThresholded.cols); 
    cv::Mat m(imgThresholded.rows, imgThresholded.cols, CV_8UC3, &pixels[0]); 
    imgThresholded.copyTo(m); 


    for(int i =0;i<1000;i++) 
    cout<<pixels[0]; 
    if(pixels[0][0]==black) 
    // do some calculations! 

回答

2
for(int i =0;i<1000;i++) 
    cout<<pixels[0]; 

將只打印第一像素1000倍。 我想你的意思是:

Vec3b black(0, 0, 0); 

for(int i =0;i<1000;i++) 
{ 
    cout << pixels[i]; 
    if pixels[i] == black) 
    { 
     /* ... */ 
    } 
} 

但爲什麼還要複製像素一個std :: vector的?你可以這樣做

Vec3b black(0, 0, 0); 

Mat img(imgThresholded); // just to make a short name 

for(int y = 0; y < img.rows; ++y) 
{ 
    Vec3b* row = img.ptr<Vec3b>(y); 
    for(int x = 0; x < img.cols; ++x) 
    { 
     Vec3b& pixel = row[x]; 
     if(pixel == black) 
     { 
      /* ... */ 
     } 
    } 
} 
+0

由於其工作... – gamal 2014-09-11 08:16:58

+0

感謝來自Vec3b其工作... 我怎麼能提取RGB值.... INT R = INT G = INT B = – gamal 2014-09-11 11:27:37

+0

如果在我的代碼中的img是RGB,那麼R = pixel [2],G = pixel [1],B = pixel [0] – Bull 2014-09-11 13:25:10