Opencv 找到ROI内的轮廓

Opencv 找到ROI内的轮廓,opencv,roi,Opencv,Roi,我一直在寻找这个问题,还没有收到任何具体的答案。我已经找到了我的轮廓,也定义了我的投资回报率 问题:如何仅在ROI内找到这些轮廓 我一开始就定义了我的投资回报率 代码如下: int main( int argc, char** argv ) { Mat img_prev, img_curr, result; int counter = 0; //string filename = "/home/zubair/Downloads/Contours/1.jp

我一直在寻找这个问题,还没有收到任何具体的答案。我已经找到了我的轮廓,也定义了我的投资回报率

问题:如何仅在ROI内找到这些轮廓

我一开始就定义了我的投资回报率

代码如下:

    int main( int argc, char** argv )
{
    Mat img_prev, img_curr, result;
    int counter = 0;

        //string filename = "/home/zubair/Downloads/Contours/1.jpg";
        //VideoCapture cap(filename);

  //while(1)
  //{

  img_curr = imread(argv[1], CV_LOAD_IMAGE_COLOR); 
    //cap >> img_curr;
    //counter++;
    //img_curr.copyTo(img_prev);

    while(1)
       {
      // SetImageRoi    
      cv::Rect roi(1,250, 640, 200);
      cv::rectangle(img_curr,roi,cv::Scalar(255,255,255),1,8,0);


      //cv::Mat image_roi = img_curr(roi);  // note: this assignment does not copy data, frame and   image_roi now share data



   imshow ("current frame",img_curr);

   if(! img_curr.data )                              // Check for invalid input
    {
        cout <<  "Could not open or find the image" << std::endl ;
        return -1;
    }

   //imshow("previous frame", img_prev);

   cvtColor( img_curr, src_gray, CV_BGR2GRAY );



//--------------------------------------------------------------------------------------------------------------------------------------//
//----------------------------------- to find the contours AND Detect edges using Threshold---------------------------------------------//
//--------------------------------------------------------------------------------------------------------------------------------------//


  Mat canny_output;
  Mat threshold_output;
  vector<vector<Point> > contours;
  vector<Vec4i> hierarchy;

  /// Detect edges using canny
  Canny(src_gray, canny_output, thresh, thresh*2, 3 );

  blur( src_gray, src_gray, Size(3,3) );

  ///threshold control
  threshold( src_gray, threshold_output, thresh, 255, THRESH_BINARY );

  /// Find contours
  findContours( threshold_output, contours, hierarchy, RETR_TREE, CHAIN_APPROX_SIMPLE, Point(0, 0) );

  /// Get the moments
      vector<Moments> mu(contours.size() );
      for( int i = 0; i < contours.size(); i++ )
         { mu[i] = moments( contours[i], false ); }


    cv::erode(threshold_output,threshold_output, cv::getStructuringElement(cv::MORPH_ELLIPSE, cv::Size(5, 5)));
    cv::dilate(threshold_output, threshold_output, cv::getStructuringElement(cv::MORPH_ELLIPSE, cv::Size(5, 5)));



  ///  Get the mass centers:
       vector<Point2f> mc( contours.size() );
       for( int i = 0; i < contours.size(); i++ )
          { mc[i] = Point2f( mu[i].m10/mu[i].m00 , mu[i].m01/mu[i].m00 ); }

  /// Approximate contours to polygons + get bounding rects and circles
  vector<vector<Point> > contours_poly( contours.size() );
  vector<Rect> boundRect( contours.size() );
  vector<Point2f>center( contours.size() );
  vector<float>radius( contours.size() );
    for( int i = 0; i < contours.size(); i++ )
        { approxPolyDP( Mat(contours[i]), contours_poly[i], 3, true );
         boundRect[i] = boundingRect( Mat(contours_poly[i]) );
         minEnclosingCircle( (Mat)contours_poly[i], center[i], radius[i] );
        }


   Mat drawing = Mat::zeros( threshold_output.size(), CV_8UC3 );
   bool is_inside = (roi & cv::Rect(0, 0, drawing.cols, drawing.rows)) == roi;

   //printf("\t Info: Area and Contour Length \n");
   for( int i = 0; i< contours.size(); i++ )
     {


      if(contourArea(contours[i]) > 2000 && contourArea(contours[i]) < 50000  )
         {

            printf(" * Contour[%d] - Area (M_00) = %.2f - Area OpenCV: %.2f - Length: %.2f \n", i, mu[i].m00, contourArea(contours[i]), arcLength    ( contours[i], true ) );
            Scalar color = Scalar( rng.uniform(0, 255), rng.uniform(0,255), rng.uniform(0,255) );

            drawContours( drawing, contours, i, color, 2, 8, hierarchy, 0, Point(0,0) );
            rectangle( drawing, boundRect[i].tl(), boundRect[i].br(), color, 2, 8, 0 );
            Point center_obstacle = (boundRect[i].br() + boundRect[i].tl())*0.5;
            circle(drawing,center_obstacle,3,Scalar(0,0,255));
            cout<<"     obstale     "<<i<<"     position is at     "<< center_obstacle.x <<"     and     "<< center_obstacle.y <<endl;
         }

      }



        createTrackbar( " Canny thresh:", "Source", &thresh, max_thresh );
        createTrackbar( " Threshold:", "Source", &thresh, max_thresh);

    namedWindow( "Contours", WINDOW_AUTOSIZE );
    imshow( "Contours", drawing );

//--------------------------------------------------------------------------------------------------------------------------------------------



        waitKey(0);

}
      return 0;
  }
int main(int argc,char**argv)
{
材料上一次、当前、结果;
int计数器=0;
//字符串filename=“/home/zubair/Downloads/Contours/1.jpg”;
//视频捕获cap(文件名);
//而(1)
//{
img\u curr=imread(argv[1],CV\u LOAD\u IMAGE\u COLOR);
//cap>>当前货币;
//计数器++;
//img_curr.copyTo(img_prev);
而(1)
{
//SetImageRoi
cv:Rect roi(1250640200);
cv::矩形(img_curr,roi,cv::标量(255255),1,8,0);
//cv::Mat image_roi=img_curr(roi);//注意:此分配不复制数据,帧和图像_roi现在共享数据
imshow(“当前帧”,img_curr);
如果(!img\u curr.data)//检查输入是否无效
{

我可以定义一个函数来判断
Rect-Rect
是否在
Rect-roi

bool isInside(const Rect& rect, const Rect& roi) {
    return (roi|rect) == roi;
}

这是一个测试示例:


修改:

for( int i = 0; i< contours.size(); i++ )
{
    Rect rect = boundingRect(contours[i]);
    // bool is_inside = (roi|rect) == roi;
    if(!isInside(rect, roi)){
        cout <<"Not in side, continue to the next."<<endl;
        continue;
    }

    // ...

}
for(int i=0;i谢谢@消音器的回答,我仍然收到一个错误“isInside不能使用函数”!!对我来说没关系,结果已经发布在了答案中,你可以看到。你只给我错误信息,没有你的错误代码,我无法找出错误。抱歉,这是你告诉我的我修改过的代码,错误消息是“错误:'isInside'不能用作函数if(!isInside(rect,roi)){”好的,我明白了。在我的代码中,它是
if(!isInside(rect,roi))
,而您调用
if(!isInside(roi))
。你原来的
是内部的
使用
&
,而我的
是内部的
使用
,这是最大的不同。那么你原来的
rect
就你的目的而言是错误的,这是第二个区别。第三,你在循环之外判断,所以它不是针对每个轮廓。现在,如果你运行第一个示例,我会这样做吗成功吗?如果你不能成功地运行第一个示例“Roi为蓝色;内部为绿色,外部为红色!”,那么我就无能为力。如果成功了,那么我的逻辑就正常了。
bool is_inside = (roi & cv::Rect(0, 0, drawing.cols, drawing.rows)) == roi;
for( int i = 0; i< contours.size(); i++ )
{
    Rect rect = boundingRect(contours[i]);
    // bool is_inside = (roi|rect) == roi;
    if(!isInside(rect, roi)){
        cout <<"Not in side, continue to the next."<<endl;
        continue;
    }

    // ...

}