cv::Mat thr;
std::vector<std::vector<cv::Point> > contours;
std::vector<std::vector<cv::Vec4i> > hierarchy;
int largest_area = 0;
int largest_contour_index = 0;
cv::findContours( thr, contours, hierarchy,CV_RETR_CCOMP, CV_CHAIN_APPROX_SIMPLE ); // Find the contours in the image
for( int i = 0; i < contours.size(); i++ ) // iterate through each contour.
{
double a = contourArea( contours[i], false ); // Find the area of contour
if(a > largest_area)
{
largest_area = a;
largest_contour_index = i; // Store the index of largest contour
}
}
找到最大轮廓的索引后我该怎么办?如何删除其内部区域的所有其他轮廓? 图像是二进制的(cv :: Mat thr)。只是黑色背景与白色区域。 感谢。
答案 0 :(得分:0)
在您的情况下,删除内部区域的轮廓等于将它们填充为黑色。这可以通过绘制黑色轮廓区域来完成:
for (size_t i=0; i<contours.size(); ++i) {
if (i != largest_contour_index) { // not the largest one
cv::drawContours(thr, contours, i, cv::Scalar(0,0,0), CV_FILLED);
}
}
答案 1 :(得分:0)
找到轮廓后找到最大轮廓的索引并在Mat上绘制该轮廓。
int indexOfBiggestContour = -1;
int sizeOfBiggestContour = 0;
for (int i = 0; i < contours.size(); i++)
{
if (contours[i].size() > sizeOfBiggestContour)
{
sizeOfBiggestContour = contours[i].size();
indexOfBiggestContour = i;
}
}
cv::Mat newImage;
drawContours(newImage, contours, indexOfBiggestContour, Scalar(255), CV_FILLED, 8, hierarchy);