Ask Your Question

Revision history [back]

i tried to use black squares indicating interested area. the code below is just a small prototype, maybe you will try to improve it. i get the following image but the code will need tunning to be more general.

image description

#include <opencv2/highgui.hpp>
#include <opencv2/imgproc.hpp>
#include <iostream>

using namespace cv;
using namespace std;


int main(int argc, const char** argv)
{
    Mat img = imread(argv[1]);
    if (img.empty())
    {
        return 1;
    }

    Mat gray, thresh;
    cvtColor(img, gray, COLOR_BGR2GRAY);
    threshold(gray, thresh, 0, 255, THRESH_BINARY_INV + THRESH_OTSU);
    erode(thresh, thresh, Mat(),Point(-1,-1), 4);
    dilate(thresh, thresh, Mat(), Point(-1, -1), 4);

    vector<Point> pts;
    vector<vector<Point> > contours;

    findContours(thresh, contours, RETR_EXTERNAL, CHAIN_APPROX_SIMPLE);

    for (size_t i = 0; i< contours.size(); i++)
    {
        Rect _boundingRect = boundingRect(contours[i]);
        if ((_boundingRect.width < _boundingRect.height * 3) & (_boundingRect.height < _boundingRect.width * 3))
        {
            pts.push_back((_boundingRect.tl()+ _boundingRect.br()) /2 );
        }
    }

    vector<Point> hull;
    convexHull(pts, hull, false);
    Rect r = boundingRect(hull);
    imwrite("result.png", img(r));
    imshow("result", img(r));
    waitKey(0);

}