Search code examples
c++opencvobject-detection

How to draw a rectangle around an object using some openCV algorithm


I am working on object detection with opencv. I want to draw a rectangle around an object after clicking on it by mouse. What kind of technique can I use? I tried with SURF but in vain.

Any help will be appreciated.


Solution

  • What kind of images you want to use? If the image is a sort of simple one(e.g. a pencil on white paper, a mark on plain wall), would you consider using following approach? I think it is very classical approach but works good when the situation is limited.

    cv::Mat img = // your image.
    double threshold = 128; // needs adjustment.
    int n_erode_dilate = 1; // needs adjustment.
    
    cv::Mat m = img.clone();
    cv::cvtColor(m, m, CV_RGB2GRAY); // convert to glayscale image.
    cv::blur(m, m, cv::Size(5,5));
    cv::threshold(m, m, threshold, 255,CV_THRESH_BINARY_INV);
    cv::erode(m, m, cv::Mat(),cv::Point(-1,-1),n_erode_dilate);
    cv::dilate(m, m, cv::Mat(),cv::Point(-1,-1),n_erode_dilate);
    
    std::vector< std::vector<cv::Point> > contours;
    std::vector<cv::Point> points;
    cv::findContours(m, contours, CV_RETR_LIST, CV_CHAIN_APPROX_NONE);
    for (size_t i=0; i<contours.size(); i++) {
        for (size_t j = 0; j < contours[i].size(); j++) {
            cv::Point p = contours[i][j];
            points.push_back(p);
        }
    }
    // And process the points or contours to pick up specified object.
    
    // for example: draws rectangle on original image.
    if(points.size() > 0){
        cv::Rect brect = cv::boundingRect(cv::Mat(points).reshape(2));
        cv::rectangle(img, brect.tl(), brect.br(), cv::Scalar(100, 100, 200), 2, CV_AA);
    }