Well here we are after a week a new post. This post will guide you to, as you can see in the title, draw shapes on image or in a blank image. I am going use both a blank image and an image from my hard drive and implement it on both C++ and Python.
Following are the few shapes which you can draw:
- Circle
- Rectangle
- Ellipse
- Polygon (Tough)
Before understand drawing this shape we need to understand the use of it. That is where we can use it. Like if you are making an application on Face Detection we can make a use of circle and drag it all over wherever the face is detected.
Circle:
This objects are found in Drawing Functions of OpenCV (go to the link if you need to get details about each and every drawing function). Following is the syntax of function circle
circle(img,center,radius,color,thickness=1,lineType=8,shift=0)
cv2.circle(img, center, radius, color[, thickness[, lineType[, shift]]])
cv.Circle(img, center, radius, color[, thickness[, lineType[, shift]]])
Note: These functions are not returning anything i.e. void
functions. So it edits the image in the function itself. First is C++ and other two are for python.
Following is the code for drawing a circle.
For C++:
#include <cv.h>
#include <highgui.h>
using namespace cv;
int main()
{
Mat img1= Mat::zeros(500,500,CV_8UC3);
circle(img1,Point(img1.rows/2,img1.cols/2),100,Scalar(255,255,0),1,8);
namedWindow("Window",CV_WINDOW_AUTOSIZE);
imshow("Window",img1);
return 0;
}
- I think we should start with the declaration of
img1
we have used a constructor ofMat
to initialize the objectimg1
as by filling it with black color or in numerals with '0'. - Now comes the main part of drawing the circle.
circle()
has many arguments like '100' is value ofradius
then '1' is forthickness
again '8' is forlineType
as discussed in the syntax portion. Rest is the inline functions used such asPoint()
to avoid declaring a variable forcenter
. Similarly forScaler(B,G,R)
we have directly used it.
Now it will show circle of color ‘Cyan’ in a black background. You can make your own color using the function Scalar(B,G,R)
and be sure values are between 0-255 :-P. Also at any place i.e. by changing the Point()
which is defined for center
.
For Python:
from cv2.cv import * # importing all the opencv libraries
img=CreateMat(400,400,CV_8UC3) # creating blank image of 400x400 pixels
Circle(img,(img.rows/2,img.cols/2),50,(255,255,255), 1)
ShowImage("Display",img) # Displaying the image
WaitKey(0)
I hope you all would have got an idea about everything and here in place of zeros()
we used CreateMat()
. Also as you can see in the syntax we have ‘[]’ brackets which shows the arguments inside are optional.
As I wrote earlier that we can draw shape in an existing image also so here you can use img1=imread(“path/to/image”)
or img1=LoadImageM(“path/to/image”)
instead of zeros()
or CreateMat()
That’s it for circles next post we will see the ellipses… you can get the files from my github repository opencv-programs
End Of Post