2014-07-01 67 views
0

我有一個二進制圖像的輪廓,我得到最大的對象,並且我想要選擇這個對象來繪製它。我有這樣的代碼:如何從輪廓中選擇全部?

vector<vector<Point> > contours; 
findContours(img.clone(), contours, CV_RETR_EXTERNAL, CV_CHAIN_APPROX_SIMPLE); 
vector<Rect> boundSheet(contours.size()); 
int largest_area=0; 
for(int i = 0; i< contours.size(); i++) 
    { 
    double a= contourArea(contours[i],false); 
    if(a>largest_area){ 
    largest_area=a; 
    boundSheet[i] = boundingRect(contours[i]); 
    } 
    } 

我要畫與drawContours邊界外的一切,我怎麼可以選擇所有出輪廓?

+2

看看我的回答[post](http://stackoverflow.com/questions/10176184/with-opencv-try-to-extract-a-region-of-a-picture-描述逐arrayofarrays/10186535#10186535)。它向您展示瞭如何使用drawContours()在一個蒙版上繪製一個給定的輪廓來掩蓋輪廓。相反,如果您希望忽略輪廓並將其保留在外,只需將遮罩的原始值設置爲正值,然後使用drawContours()將遮罩中輪廓的區域填充爲0.也就是說,將值在鏈接中給出的示例中。 – lightalchemist

+0

謝謝!!!!,它工作我:D,只有顏色的問題,我想塗料灰色,什麼是必須改變? – user3779874

+0

請參閱下面的答案。 – lightalchemist

回答

1
using namespace cv; 

int main(void) 
{ 
    // 'contours' is the vector of contours returned from findContours 
    // 'image' is the image you are masking 

    // Create mask for region within contour 
    Mat maskInsideContour = Mat::zeros(image.size(), CV_8UC1); 
    int idxOfContour = 0; // Change to the index of the contour you wish to draw 
    drawContours(maskInsideContour, contours, idxOfContour, 
       Scalar(255), CV_FILLED); // This is a OpenCV function 

    // At this point, maskInsideContour has value of 255 for pixels 
    // within the contour and value of 0 for those not in contour. 

    Mat maskedImage = Mat(image.size(), CV_8UC3); // Assuming you have 3 channel image 

    // Do one of the two following lines: 
    maskedImage.setTo(Scalar(180, 180, 180)); // Set all pixels to (180, 180, 180) 
    image.copyTo(maskedImage, maskInsideContour); // Copy pixels within contour to maskedImage. 

    // Now regions outside the contour in maskedImage is set to (180, 180, 180) and region 
    // within it is set to the value of the pixels in the contour. 

    return 0; 
}