Ask Your Question

Revision history [back]

just tested an answer on SO

it seems calling findContours with CV_CHAIN_CODE returns useless data and old C API still useful.

#include "opencv2/imgproc.hpp"
#include "opencv2/highgui.hpp"
#include "opencv2/imgproc/imgproc_c.h"
#include <iostream>

using namespace std;
using namespace cv;

int main() {

    cv::Mat img = cv::Mat::zeros(100, 100, CV_8UC1);
    cv::line(img, Point(50,50), Point(60,60), cv::Scalar(255), 1);
    cv::line(img, Point(40, 60), Point(60, 60), cv::Scalar(255), 1);
    cv::line(img, Point(40, 60), Point(50, 50), cv::Scalar(255), 1);

    imshow("Test", img);

    vector<vector<Point> > contours;

    findContours(img, contours, RETR_EXTERNAL, CV_CHAIN_CODE);
    cout << Mat(contours[0]) << endl;

    findContours(img, contours, RETR_EXTERNAL, CHAIN_APPROX_SIMPLE);
    cout << "CHAIN_APPROX_SIMPLE" << endl;
    cout << Mat(contours[0]) << endl;

    CvChain* chain = 0;
    CvMemStorage* storage = 0;
    storage = cvCreateMemStorage(0);
    cvFindContours(&IplImage(img), storage, (CvSeq**)(&chain), sizeof(*chain), CV_RETR_EXTERNAL, CV_CHAIN_CODE);

    for (; chain != NULL; chain = (CvChain*)chain->h_next)
    {
        //chain=(CvChain*)chain ->h_next; 
        //if(chain==NULL){break;}
        CvSeqReader reader;
        int i, total = chain->total;
        cvStartReadSeq((CvSeq*)chain, &reader, 0);
        printf("--------------------chain\n");

        for (i = 0; i<total; i++)
        {
            char code;
            CV_READ_SEQ_ELEM(code, reader);
            printf("%d", code);
        }
    }

    waitKey();

    return 0;
}