如何检测两条线之间或图像指定区域之间的轮廓数

how to detect number of contours in between two lines or specified region of image

我正在使用 OpenCV C++ 查找视频中的轮廓。我想计算视频中指定区域或视频中绘制的两条线之间的轮廓数。例如,视频中的轮廓流正在移动,我想在它们到达视频中的特定区域时对它们进行计数。当他们离开视频中的特定区域时,我会减少计数。我知道一些基本的东西来找到轮廓,计算面积等。但我没有得到任何编程技巧来计算指定区域内轮廓的数量。请帮助我解决相关主题和一些编程技巧。 (我不想使用 cvBlob.h 库)

基本上我是在统计进入该地区的汽车数量。如果有汽车进入,我会增加计数,如果它离开该区域,我会减少计数。

您可以将找到的轮廓近似为多边形或圆形:

for( int i = 0; i < contours.size(); i++ )
 { approxPolyDP( Mat(contours[i]), contours_poly[i], 3, true );
   boundRect[i] = boundingRect( Mat(contours_poly[i]) )
 }

然后用直线方程y=a比较矩形的角坐标或圆的center+radius来判断轮廓是否通过直线

1.Use 您的 Mat 图像的一部分。(如果您的 ROI 是矩形)

Mat src;  // suppose this is your source frame
Mat src_of_interest = src(Rect(Point(x1, y1), Point(x2, y2)));

// Do the rest of finding contour..

vector<vector<Point>> contours;
vector<Vec4i> hierarchy;

findContours(src_of_interest.clone(), contours, hierarchy, CV_RETR_TREE, CV_CHAIN_APPROX_SIMPLE);

//now you can do your job with contour vector.    
int count = contours.size();

Mat dst = Mat::zeros(src.size(), CV_8UC3);
for(int i=0; i< count; i++)
{
    drawContours(dst, contours, i, CV_RGB(255, 0, 0));   // draw contour in red
}


2. 如果您的感兴趣区域不是矩形,请尝试以下方法:

vector<Point> contour_of_interest;   // this contour is where you want to check
vector<vector<Point>> contours;   // this is the contours you found

Mat dst = Mat::zeros(src.size(), CV_8U);
for(int i=0; i< count; i++)
{
    drawContours(dst, contours, i, Scalar(255));   // set contour area to 255
}

Mat roi = Mat::zeros(src.size(), CV_8U);
vector<vector<Point>> coi_vector;
coi_vector.push_back(contour_of_interest);
drawContours(roi, coi_vector, 0, Scalar(255));

Mat and = dst & roi;    // where 2 mats are both TRUE(not zero)

findContours(and.clone(), contours, hierarchy, CV_RETR_TREE, CV_CHAIN_APPROX_SIMPLE);

//now you can do your job with contour vector.    
int count = contours.size();


3. 如果你想计算 4 个点之间的轮廓,试试这个方法:

vector<Point> contour_of_interest;   // this contour is the area where you want to check
Point p1(x1, y1);
Point p2(x1, y2);
Point p3(x2, y2);
Point p4(x2, y1);
contour_of_interest.push_back(p1);
contour_of_interest.push_back(p2);
contour_of_interest.push_back(p3);
contour_of_interest.push_back(p4);

vector<vector<Point>> coi_list;
coi_list.push_back(contour_of_interest);

Mat mask = Mat:zeros(src.size(), CV_8U);
drawContours(mask, coi_list, 0, Scalar(255));

Mat src;  // suppose this is your source frame
Mat src_of_interest = src & mask;  // remove any pixels outside mask area

// Do the rest of finding contour..

vector<vector<Point>> contours;
vector<Vec4i> hierarchy;

findContours(src_of_interest.clone(), contours, hierarchy, CV_RETR_TREE, CV_CHAIN_APPROX_SIMPLE);

//now you can do your job with contour vector.    
int count = contours.size();

Mat dst = Mat::zeros(src.size(), CV_8UC3);
for(int i=0; i< count; i++)
{
    drawContours(dst, contours, i, CV_RGB(255, 0, 0));   // draw contour in red
}