Ask Your Question

Revision history [back]

to understand and test i tried to implement the code below. May be it will be helpful for some one who want to fix

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

using namespace cv;
using namespace std;

void process( Mat src );

int main()
{
    Mat clk(640,640,CV_8UC3);

    Point cent(320,320);
    Point perim(320,0);

    float sec_angle=270;

    while(1)
    {
        if(sec_angle>360)sec_angle=sec_angle-360;

        perim.x =  (int)round(cent.x + 200 * cos(sec_angle * CV_PI / 180.0));
        perim.y =  (int)round(cent.y + 200 * sin(sec_angle * CV_PI / 180.0));
        line( clk,cent,perim, Scalar(0,255,255), 8 );

        process( clk );
        putText( clk, format("%f",sec_angle), perim, FONT_HERSHEY_PLAIN, 2, Scalar(0,0,255) );

        imshow("Clock",clk);
        clk.setTo(0);

        sec_angle ++;

        char c=waitKey();
        if(c==27)break;
    }
    return 0;
}

void process( Mat src )
{
    Mat gray;
    cvtColor( src, gray, COLOR_BGR2GRAY );
    gray = gray >  127;

    vector<vector<Point> > contours;

    findContours(gray.clone(), contours, CV_RETR_EXTERNAL, CV_CHAIN_APPROX_SIMPLE);

    RotatedRect _minAreaRect;

    for (size_t i = 0; i < contours.size(); ++i)
    {
        _minAreaRect = minAreaRect( Mat(contours[i]) );
        Point2f pts[4];
        _minAreaRect.points(pts);

        double angle = atan2(pts[0].y - pts[1].y,pts[0].x - pts[1].x) * 180.0 / CV_PI;
        putText( src, format("minAreaRect : %f, %f",_minAreaRect.angle, angle), Point(30,30), FONT_HERSHEY_PLAIN, 2, Scalar(0,0,255) );

        for( int j = 0; j < 4; j++ )
            line(src, pts[j], pts[(j+1)%4], Scalar(0, 255, 0), 2, LINE_AA);

        _minAreaRect = fitEllipse( Mat(contours[i]) ) ;
        _minAreaRect.points(pts);
        angle = atan2(pts[0].y - pts[1].y,pts[0].x - pts[1].x) * 180.0 / CV_PI;
        putText( src, format("fitEllipse : %f, %f",_minAreaRect.angle, angle ), Point(30,70), FONT_HERSHEY_PLAIN, 2, Scalar(0,0,255) );

        for( int j = 0; j < 4; j++ )
            line(src, pts[j], pts[(j+1)%4], Scalar(0, 0, 255), 1, LINE_AA);

    }
}