Monday, 21 December 2015

Opencv Code for Drawing a Star

This opencv tutorial is about drawing a Star.

In the previous tutorial we learnt about drawing a LINE:
http://opencv-hub.blogspot.in/2015/12/opencv-code-for-drawing-line-cplusplus.html

Thus this opencv tutorial will be an extension of that tutorial with some added mathematical logic for drawing a star.
To begin with we first start by drawing a pentagon:
And name the vertex as a ,b ,c ,d, e.
The co-ordinates of which can be obtained by mathematical rules as explained before:

a=( 2*r*cos(36)*cos(72) , x )
b=( x-2*r*cos(36)*cos(72) , x )
c=( x , 2*r*cos(36)*sin(72) )
d=( x/2 , 0 )
e=( 0 , 2*r*cos(36)*sin(72) )



Opencv Star


Now, The magic begins.
1. Join vertex a with d.
2. Join vertex d with b.
3. Join vertex b with e.
4. Join vertex e with c.
5. Join vertex c with a.
Here is the opencv code for drawing a Star:

//Opencv Example of drawing a Star 
#include <opencv2/core/core.hpp>
#include <opencv2/highgui/highgui.hpp>
#include <iostream>
#include <math.h>
using namespace cv;
using namespace std;
 
int main( )
{    
  double pi=3.14;
  int a=500/(1+cos(pi*54/180));
 
  // Create black empty images
  Mat image = Mat::zeros( 500, 500, CV_8UC3 );
  
  line( image, Point((a*cos(pi*72/180)), 500),  Point(250, 0), Scalar( 255, 255, 0 ), 2, 8 );
  imshow("Image",image); 
  waitKey( 500 );

  line( image, Point(250, 0), Point(500-(a*cos(pi*72/180)),500), Scalar( 255, 255, 0 ), 2, 8 );
  imshow("Image",image); 
  waitKey( 500 ); 

  line( image, Point(500-(a*cos(pi*72/180)),500), Point(0, 500-(a*sin(pi*72/180))), Scalar( 255, 255, 0 ), 2, 8 );
  imshow("Image",image); 
  waitKey( 500 );

  line( image, Point(0, 500-(a*sin(pi*72/180))), Point( 500, 500-(a*sin(pi*72/180)) ), Scalar( 255, 255, 0 ), 2, 8 );
  imshow("Image",image); 
  waitKey( 500 );

  line( image, Point( 500, 500-(a*sin(pi*72/180)) ), Point((a*cos(pi*72/180)), 500), Scalar( 255, 255, 0 ), 2, 8 );
  imshow("Image",image); 
  waitKey( 0 );
  return(0);
}

Resultant Star Image:
Opencv Code Drawing Star

No comments:

Post a Comment