2017-02-26 61 views
0

我已經利用OpenCV GrabCut功能來執行圖像分割。按照以下代碼查看分段圖像時,分段是合理的/正確的。但是,在查看(試圖使用)segmrntation掩碼值時,我得到了一些非常大的數字,而不是人們期望從枚舉值cv::GrabCutClasses中枚舉的值。OpenCV GrabCut模板

void doGrabCut(){ 
     Vector2i imgDims = getImageDims(); 

     //Wite image to OpenCV Mat. 
     const Vector4u *rgb = getRGB(); 
     cv::Mat rgbMat(imgDims.height, imgDims.width, CV_8UC3); 
     for (int i = 0; i < imgDims.height; i++) { 
      for (int j = 0; j < imgDims.width; j++) { 
       int idx = i * imgDims.width + j; 
       rgbMat.ptr<cv::Vec3b>(i)[j][2] = rgb[idx].x; 
       rgbMat.ptr<cv::Vec3b>(i)[j][1] = rgb[idx].y; 
       rgbMat.ptr<cv::Vec3b>(i)[j][0] = rgb[idx].z; 
      } 
     } 

     //Do graph cut. 
     cv::Mat res, fgModel, bgModel; 
     cv::Rect bb(bb_begin.x, bb_begin.y, bb_end.x - bb_begin.x, bb_end.y - bb_begin.y); 
     cv::grabCut(rgbMat, res, bb, bgModel, fgModel, 10, cv::GC_INIT_WITH_RECT); 
     cv::compare(res, cv::GC_PR_FGD, res, cv::CMP_EQ); 

     //Write mask. 
     Vector4u *maskPtr = getMask();//uchar 
     for (int i = 0; i < imgDims.height; i++) { 
      for (int j = 0; j < imgDims.width; j++) { 
       cv::GrabCutClasses classification = res.at<cv::GrabCutClasses>(i, j); 
       int idx = i * imgDims.width + j; 
       std::cout << classification << std::endl;//Strange numbers here. 
       maskPtr[idx].x = (classification == cv::GC_PR_FGD) ? 255 : 0;//This always evaluates to 0. 
      } 
     } 

     cv::Mat foreground(rgbMat.size(), CV_8UC3, cv::Scalar(255, 255, 255)); 
     rgbMat.copyTo(foreground, res); 
     cv::imshow("GC Output", foreground); 
} 

爲什麼當分割定性地正確時,人們會在枚舉之外得到數字?

回答

0

我對你//Write mask.一步懷疑,爲什麼你再次重申了res和修改maskPtrmaskPtr[idx].x = (classification == cv::GC_PR_FGD) ? 255 : 0;,基本上已經存儲在res變量單通道二值圖像中,cv::compare()返回一個二進制圖像

不過,如果你仍然想通過調試迭代中的值,那麼你應該使用標準技術用於重複單通道圖像:

for (int i = 0; i < m.rows; i++) { 
    for (int j = 0; j < m.cols; j++) { 
     uchar classification = res.at<uchar>(i, j); 
     std::cout << int(classification) << ", "; 
    } 
} 

當你迭代單通道墊您必須ü se res.at<uchar>(i, j)而不是res.at<cv::GrabCutClasses>