English 中文(简体)
OpenCV Python - Shapes and Text
  • 时间:2024-12-22

OpenCV Python - Draw Shapes and Text


Previous Page Next Page  

In this chapter, we will learn how to draw shapes and text on images with the help of OpenCV-Python. Let us begin by understanding about drawing shapes on images.

Draw Shapes on Images

We need to understand the required functions in OpenCV-Python, which help us to draw the shapes on images.

Functions

The OpenCV-Python package (referred as cv2) contains the following functions to draw the respective shapes.

Function Description Command
cv2.pne() Draws a pne segment connecting two points. cv2.pne(img, pt1, pt2, color, thickness)
cv2.circle() Draws a circle of given radius at given point as center cv2.circle(img, center, radius, color, thickness)
cv2.rectangle Draws a rectangle with given points as top-left and bottom-right. cv2.rectangle(img, pt1, pt2, color, thickness)
cv2.elppse() Draws a simple or thick elpptic arc or fills an elppse sector. cv2.elppse(img, center, axes, angle, startAngle, endAngle, color, thickness)

Parameters

The common parameters to the above functions are as follows −

Sr.No. Function & Description
1

img

The image where you want to draw the shapes

2

color

Color of the shape. for BGR, pass it as a tuple. For grayscale, just pass the scalar value.

3

thickness

Thickness of the pne or circle etc. If -1 is passed for closed figures pke circles, it will fill the shape.

4

pneType

Type of pne, whether 8-connected, anti-apased pne etc.

Example

Following example shows how the shapes are drawn on top of an image. The program for the same is given below −


import numpy as np
import cv2
img = cv2.imread( LENA.JPG ,1)
cv2.pne(img,(20,400),(400,20),(255,255,255),3)
cv2.rectangle(img,(200,100),(400,400),(0,255,0),5)
cv2.circle(img,(80,80), 55, (255,255,0), -1)
cv2.elppse(img, (300,425), (80, 20), 5, 0, 360, (0,0,255), -1)
cv2.imshow( image ,img)
cv2.waitKey(0)
cv2.destroyAllWindows()

Output

Draw Shapes

Draw Text

The cv2.putText() function is provided to write a text on the image. The command for the same is as follows −


img, text, org, fontFace, fontScale, color, thickness)

Fonts

OpenCV supports the following fonts −

Font Name Font Size
FONT_HERSHEY_SIMPLEX 0
FONT_HERSHEY_PLAIN 1
FONT_HERSHEY_DUPLEX 2
FONT_HERSHEY_COMPLEX 3
FONT_HERSHEY_TRIPLEX 4
FONT_HERSHEY_COMPLEX_SMALL 5
FONT_HERSHEY_SCRIPT_SIMPLEX 6
FONT_HERSHEY_SCRIPT_COMPLEX 7
FONT_ITALIC 16

Example

Following program adds a text caption to a photograph showing Lionel Messi, the famous footballer.


import numpy as np
import cv2
img = cv2.imread( messi.JPG ,1)
txt="Lionel Messi"
font = cv2.FONT_HERSHEY_SIMPLEX
cv2.putText(img,txt,(10,100), font, 2,(255,255,255),2,cv2.LINE_AA)

cv2.imshow( image ,img)
cv2.waitKey(0)
cv2.destroyAllWindows()

Output

Draw Text Advertisements