Ask Your Question

Revision history [back]

click to hide/show revision 1
initial version

Chain Code Histogram

I have already extracted chain code of the contour, calculated the number of occurence of each code. Then calculated the frequency of each code. Now I have to plot it in a histogram, I do not know how to create a histogram for chain code the no. of bins should be 8 thats all I know. But how to create it in opencv 3.0 using c++?

int main()
{
int count0 = 0;
int count1 = 0;
int count2 = 0;
int count3 = 0;
int count4 = 0;
int count5 = 0;
int count6 = 0;
int count7 = 0;

double totalCount = 0;

Mat image = imread("rectangle.jpg", 0);

Canny(image, image, 100, 100 * 2, 3, false);

CvChain* chain;
CvMemStorage* storage = 0;
storage = cvCreateMemStorage();

cvFindContours(&IplImage(image), storage, (CvSeq**)(&chain), sizeof(*chain), CV_RETR_EXTERNAL, CV_CHAIN_CODE);

int total = chain->total;


for (; chain != NULL; chain = (CvChain*)chain->h_next)
{

    int numChain = 0;

    CvSeqReader reader;
    int i, total = chain->total;

    cvStartReadSeq((CvSeq*)chain, &reader, 0);


    for (i = 0; i < total; i++)
    {
        char code;
        CV_READ_SEQ_ELEM(code, reader);
        int Fchain = (int)code;

        if (Fchain == 0)
        {
            count0++;
        }

        else if (Fchain == 1)
        {
            count1++;
        }

        else if (Fchain == 2)
        {
            count2++;
        }

        else if (Fchain == 3)
        {
            count3++;
        }

        else if (Fchain == 4)
        {
            count4++;
        }

        else if (Fchain == 5)
        {
            count5++;
        }

        else if (Fchain == 6)
        {
            count6++;
        }

        else if (Fchain == 7)
        {
            count7++;
        }

        totalCount++;
    }
}

cout << "0: " << count0 << endl;
cout << "1: " << count1 << endl;
cout << "2: " << count2 << endl;
cout << "3: " << count3 << endl;
cout << "4: " << count4 << endl;
cout << "5: " << count5 << endl;
cout << "6: " << count6 << endl;
cout << "7: " << count7 << endl;

cout << "Total: " << totalCount << endl;

double prob0 = (count0 / totalCount);
double prob1 = (count1 / totalCount);
double prob2 = (count2 / totalCount);
double prob3 = (count3 / totalCount);
double prob4 = (count4 / totalCount);
double prob5 = (count5 / totalCount);
double prob6 = (count6 / totalCount);
double prob7 = (count7 / totalCount);


cout << "Proababilty 0: " << prob0 << endl;
cout << "Proababilty 1: " << prob1 << endl;
cout << "Proababilty 2: " << prob2 << endl;
cout << "Proababilty 3: " << prob3 << endl;
cout << "Proababilty 4: " << prob4 << endl;
cout << "Proababilty 5: " << prob5 << endl;
cout << "Proababilty 6: " << prob6 << endl;
cout << "Proababilty 7: " << prob7 << endl;


waitKey(0);
return 0;

}