ApproxPolyDP approximating to a line

asked 2015-04-14 13:44:21 -0600

gunnjo gravatar image

I am using ApproxPolyDP to find the bounding rectangle from a list of points. It seems when the number of points reaches a certain threshold the approximated contour is a line segment ( 2 points).

I have looked through the code for ApproxPolyDP and can not see the issue.

Therefore I am asking here in order to see if someone else’s eyes can see what I cannot.

Here is some sample code that illustrates the issue:

    //============================================================================
// Name        : poo.cpp
// Author      : Joseph J. Gunn
// Version     :
// Copyright   : copyleft
// Description : 
//============================================================================

#include <math.h>
#include <getopt.h>
#include <string>
#include <time.h>
#include <signal.h>

#include <iostream>
#include <ctime>
using namespace std;

// opencv includes
#include <opencv2/opencv.hpp>
using namespace cv;

#include "utils.hpp"
static bool _sig_running = false;
void _sig_cb( int sig) {
    _sig_running = false;
}

struct AdjustedContour {
    double area;
    cv::Mat approx;
};
vector<Point> toPoint(Point c[], int s) {
    vector<Point> v;
    for (int i = 0; i < s; i++)
        v.push_back(c[i]);
    return v;
}
int main(int argc, char* argv[]) {
    int ec = 0;
    std::string s;

    Point five[] = {Point(0,100), Point(100,100), Point(100,0), Point(0,0)};

    AdjustedContour cont;
    vector<Point> v;
    double epsilon;
    int c = 1;
    v = toPoint(five, sizeof(five)/sizeof(five[0]));
    cv::Mat m = cv::Mat::zeros(500, 500, CV_8U);

do {
    epsilon = 0.1*cv::arcLength(v,true);
    cont.area = cv::contourArea(v);
    cv::approxPolyDP(v, cont.approx,epsilon,true);
    cout << "five is " << cont.approx << " length: " << v.size() << endl;
    v.insert( v.begin()+(c+3), Point(100, c));  
    c++;
    cv::fillConvexPoly( m, v, Scalar( 255,0,0));

} while ( (cont.approx.rows > 2) && ( v.size() < 497));
    cv::imwrite("file.png", m);

    return ec;
}

The code effectively adds points to the vector of Points until the number of rows of the approximated polygon has only 2 rows.

edit retag flag offensive close merge delete