Ask Your Question

Revision history [back]

click to hide/show revision 1
initial version

Segmentation fault (core dumped) in C++/OpenCV with functions (findContours,minEnclosingCircle,circle)

Hey,

I wish to learn Open-CV for a project and my purpose is to localize a green target and to put a circle around this target. When I compile my program i have no error, but when I execute it, I have :

Segmentation fault (core dumped)

Here is my code :

#include <opencv/cv.h>
#include <opencv/highgui.h>
#include <opencv2/opencv.hpp>
#include <iostream>
#include <sstream>
#include <string>
#include <vector>
#include <algorithm>

using namespace std;
using namespace cv;

int low_r=45, low_g=50, low_b=50;
int high_r=75, high_g=255, high_b=255;

Mat kernel = Mat::ones(5, 5, CV_8U);

VideoCapture cap(1);

int main() {

  while(cap.isOpened()){

    Mat hsv,mask,frame,cnt,cnt2,th3;

    vector<vector<Point> > contours;
    vector<Vec4i> hierarchy;
    vector<Point2f>center( contours.size() );
    vector<float>radius_cur( contours.size() );

    bool ret = cap.read(frame);

    cvtColor(frame, hsv, COLOR_BGR2HSV);
    inRange(hsv, Scalar(low_b,low_g,low_r), Scalar(high_b,high_g,high_r), mask);

    threshold(mask, th3, 0, 255, CV_THRESH_BINARY | CV_THRESH_OTSU);
    cnt = th3.clone();

    // Compute the contours in the image
    morphologyEx(th3, th3,MORPH_OPEN, kernel);
    morphologyEx(th3, th3,MORPH_CLOSE, kernel);
    morphologyEx(cnt, cnt,MORPH_OPEN, kernel);

    cnt2 = cnt.clone();

    findContours(cnt2,contours,hierarchy, CV_RETR_EXTERNAL , CV_CHAIN_APPROX_NONE);

    if(contours.size() > 0){
      int radius(1);

      // Get smallest circle enclosing contour
      for(int i=0; i<contours.size();i++){
        minEnclosingCircle(Mat(contours[i]),center[i], radius_cur[i]);
          if(radius_cur[i] > radius){
            radius = int(radius_cur[i]);
          }
        // Draw said circle
        int color_r(0), color_g(0), color_b(255);
        circle(frame, center[i], radius, Scalar(color_r,color_g,color_b),2,8,0);
     }
  }
  imshow("frame", frame);

  if((waitKey(1)) == ('q')){
    break;
  }
  }
}

Since few days, i try to correct my code. I think this is in my for loop with minEnclosingCircle(Mat(contours[i]),center[i], radius_cur[i]);, but i don't know why.

An idea? :)

Thank for your help.

William