In this Python OpenCV lesson we are going to learn Python OpenCV Drawing Shapes, basically we are going to Draw line, rectangle, circle, text and ellipse.
So now this is the complete code for this lesson.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
import numpy asnp
import cv2
def drawing_shapes():
# Create a black image
img=np.zeros((512,512,3),np.uint8)
# Draw a diagonal red line with thickness of 5 px
cv2.line(img,(0,0),(511,511),(0,0,255),5)
#we need to give top left corner and bottom right corner
cv2.putText(img,'Welcome to Geekscoders.com',(10,400),font,1,
(255,255,255),4,cv2.LINE_AA)
cv2.imshow("Black Image",img)
cv2.waitKey(0)
cv2.destroyAllWindows()
drawing_shapes()
So first of all we are going to create an empty image using numpy, because we want to draw our shapes in the empty image.
1
img=np.zeros((512,512,3),np.uint8)
For drawing line we can use this code, you can give the position of the line, the thickness and the color of the line.
1
cv2.line(img,(0,0),(511,511),(0,0,255),5)
If you want to draw rectangle than you can use cv2.rectangle(), and you need to give top left corner and bottom right corner with thickness and color.
1
cv2.rectangle(img,(384,0),(510,128),(255,0,0),6)
For drawing circle you can use this code, also you need to give the center coordinates, radius, color and thickness.
1
cv2.circle(img,(447,63),63,(0,0,255),2)
This code is used for drawing the ellipse, you need to give center coordinates (x,y location), axes length (major and minor axes lenght), angle = 0, startAngle = 0, endAngle = 180, color and thickness.
1
2
cv2.ellipse(img,(256,256),(100,50),0,0,180,
(0,255,0),-1)
And the last one is drawing text, you can give the x and y position, font size, color and thickness.
1
2
3
4
font=cv2.FONT_HERSHEY_SIMPLEX
cv2.putText(img,'Welcome to Geekscoders.com',
(10,400),font,1,
(255,255,255),4,cv2.LINE_AA)
Run the complete code and this will be the result.
Python OpenCV Drawing Shapes
We use cookies on our website to give you the most relevant experience by remembering your preferences and repeat visits. By clicking “Accept”, you consent to the use of ALL the cookies.
This website uses cookies to improve your experience while you navigate through the website. Out of these, the cookies that are categorized as necessary are stored on your browser as they are essential for the working of basic functionalities of the ...
Necessary cookies are absolutely essential for the website to function properly. This category only includes cookies that ensures basic functionalities and security features of the website. These cookies do not store any personal information.