Drawing Geometric shapes — using OpenCV
Let’s start with importing cv2 and numpy libraries. The following code is used to do so:
import numpy as np
import cv2
Now let’s take a look at the function used to read an image.
The function cv2.imread()
is used to read an image, it requires two arguments: the first is the path to the image itself and the second specifies the way the image should be read.
The default value is cv2.IMREAD_COLOR
which loads the colour image. (1)
cv2.IMREAD_GRAYSCALE
this will read the image in grayscale mode. (0)
cv2.IMREAD_UNCHANGED
this will read the image including the alpha channel. (-1)
Drawing a Line:
img = cv2.line(image, (0,0) , (255,255) , (0,0,255) , 5)
The arguments in the line()
function are:
image
: The variable holding our image(0,0)
: The starting point of our line(255, 255)
: The endpoint of our line(0, 0, 255)
: The colour of our line5
: The thickness of our line
Drawing an Arrowed Line:
img = cv2.arrowedLine(image, (0,255) , (255,255) , (255,0,0) , 5)
The arguments in the arrowedLine()
function are:
image
: The variable holding our image(0,255)
: The starting point of our line(255, 255)
: The endpoint of our line(255, 0, 0)
: The colour of our line5
: The thickness of our line
Drawing a Rectangle:
img = cv2.rectangle(image, (384,0) , (510,128) , (255,0,0) , -1)
The rectangle function holds the following arguments:
image
: The variable holding our image(384, 0)
: The top left corner of the rectangle(510, 128)
: The bottom right corner of the rectangle(255, 0, )
: The colour of the rectangle-1
: This indicated that the image will be filled with the above color.
Drawing a Circle:
img = cv2.circle(image, (447,63) , 63 ,(0,255,0) , 5)
cv2.circle()
will need the following arguments:
image
: The variable holding our image(447, 63)
: The centre location63
: The radius of the circle(0, 255, 0)
: The colour of the circle5
: The thickness of the circle
Can we draw a Polygon in OpenCV ??
Well, go try it out ; )