In this article, we are going to learn how to draw and write on images using OpenCV. Drawing is a common routine in computer vision and it’s used for highlighting and marking important parts of an image. For example, if you want to mark all cars in the image, you are going to draw squares around them.

Ultimate Guide to Machine Learning with Python

This bundle of e-books is specially crafted for beginners.
Everything from Python basics to the deployment of Machine Learning algorithms to production in one place.
Become a Machine Learning Superhero 
TODAY!

In this article, we cover

  1. Drawing a line
  2. Drawing a circle and ellipse
  3. Drawing a polygon
  4. Text writing

1. Drawing a Line

Drawing a line is used when we want to highlight some important lines in images. Traffic lines are great examples of situations when we are going to highlight lines. Function cv2.line takes five arguments: image we want to draw on, starting point, ending point, line thickness and line color. We are going to draw a line on a blank image:

img = cv2.imread('/content/drive/MyDrive/sheet.png')
print(img.shape) #=> (480, 720, 3)

#Defining starting point, ending point, thickness and color
start_point = (0,0)
end_point = (720,480)
color =  (0,140,255) #Orange RGB
thikness = 6

img = cv2.line(img, start_point, end_point, color, thickness)

cv2.imshow(img)
OpenCV Visual

As we can see the line we drew starts at the first pixel of an image and it ends at the last, also we should note that color is given in the BGR system.

2. Circle and Ellipse drawing

Naturally, circle and ellipse have their own implementations, which are cv2.circle and cv2.ellipse. So let’s dive into code.

2.1 Drawing a circle

The circle function takes in five arguments: an image we want to draw on, a center of the circle, a radius of the circle, circle color, and thickness of the line. We will now draw a circle on a blank image.
#center of the circle
center = (150,150)
#circle radius
radius = 150
#blue color in BGR system
color = (255, 0, 0)
#line thickness
thickness = 2

cv2.circle(img,center,radius,color,thickness)
cv2_imshow(img)
OpenCV Visual
As we can see, if we know the position of the circle center and its radius it’s very simple to draw a circle.

2.2 Drawing an ellipse

The ellipse on the other side is a bit more complicated geometrical body and therefore will take in more parameters than the circle. The function takes in eight arguments: the image we want to draw on, the center of the ellipse, axis length, angle, start angle, end angle, color and thickness.

The best way to explain these is to first draw an ellipse and see what happens when we change them.

#center of the ellipse
center = (150,150)
axesLength = (100, 50)
  
angle = 0
startAngle = 0
endAngle = 360 
# Red color in BGR
color = (0, 0, 255)
# Line thickness of 5 px
thickness = 5
   
# Using cv2.ellipse() method
# Draw a ellipse with red line borders of thickness of 5 px
image = cv2.ellipse(img, center, axesLength,
           angle, startAngle, endAngle, color, thickness)
OpenCV Visual

This is the following result, so let’s get to explaining the parameters one by one. The Center parameter represents the center of the eclipse, pretty self-explanatory. Axes’ length basically determines the width and height of an ellipse, so let’s switch them and see what we get.

axesLength = (50, 100)

image = cv2.ellipse(img, center, axesLength,
           angle, startAngle, endAngle, color, thickness)
OpenCV Visual

As we can see the height and width of an image have switched. With the angle parameter we decide at which angle(in degrees) we want to display an ellipse. Let’s try an angle of 30 degrees.

angle = 30

image = cv2.ellipse(img, center, axesLength,
           angle, startAngle, endAngle, color, thickness)
OpenCV Visual

We’ve successfully rotated the ellipse by 30 degrees. The start angle and end angle basically tell us how much of an ellipse we want to display, so for example, if we wanted the whole ellipse we would need to complete all 360 degrees by setting the start angle to 0 and end angle to 360. If we were to show the first half of an ellipse, for example, we would put the start angle to 0 and the end angle to 180 degrees.

startAngle = 0
endAngle = 180

image = cv2.ellipse(img, center, axesLength,
           angle, startAngle, endAngle, color, thickness)
OpenCV Visual

Thickness and color have already been covered previously.  As we can see, drawing an ellipse is pretty simple as well, you just need to play around with the parameters to get the hang of it.

3. Polygon drawing

A polygon is any shape made up of straight lines that can be drawn on a flat surface, like a piece of paper. Such shapes include squares, rectangles, triangles and pentagons but not circles or any other shape that includes a curve.

We will use OpenCV’s cv2.polylines function which takes five positional arguments: image we want to draw on, coordinates of dots we want to connect, isClosed parameter that can be true or false and it determines if the first and the last dot we defined will be connected, and then the last two arguments are the color and the thickness of the lines

3.1 Drawing a Square

The idea is to define the coordinates of 4 points in space, and let’s set the distance between each other to be 300 pixels. The following code draws us a square:

import numpy as np
import cv2
from google.colab.patches import cv2_imshow

# defining coordinates of points
points =  np.array([[0,0],[0,300],[300,300],[300,0]])

color = (255, 0, 0)
thickness = 2
isClosed = True

# drawPolyline
image = cv2.polylines(img, [points], isClosed, color, thickness)

cv2_imshow(image)
OpenCV Visual
If we were to set the parameter isClosed to false, this would be the outcome:
OpenCV Visual
As we can see the first and the last point we defined were not connected. Using cv2.polylines we can draw triangles, rectangles, hexagons, octagons, basically any shape that consists of straight lines and doesn’t have any curves.

4. Text

The last one we’re going to cover in this topic is writing. OpenCV has us covered for that as well. The function is called cv2.putText and it takes seven arguments: the image we want to write on, text, coordinates of the text position, font, font scale, color and thickness. Let’s jump into code.

# coordinates
coord = (100, 100)

font = cv2.FONT_HERSHEY_SIMPLEX

# fontScale
fontScale = 1
   
# Blue color in BGR
color = (255, 0, 0)
  
# Line thickness of 2 px
thickness = 2
   
# Using cv2.putText() method
image = cv2.putText(img, 'OpenCV', coord, font, 
                   fontScale, color, thickness)
   
# Displaying the image
cv2_imshow(image)
OpenCV Visual

We should note that all the fonts are available in the OpenCV documentation. Writing on images is very often when we want to display some kind of message in the image or maybe show some kind of measurement that took place in image processing.

Conclusion

Drawing in image processing is probably the simplest and easiest thing you could do, but it is an important part, especially when it comes to certain detection problems as we will see later in this series of articles. It comes down to  getting familiar with the functions and experimenting with them. We encourage you to stay tuned for the next few weeks, as we will use the things we’ve learned so far to solve some real-life problems.

Authors

Stefan Nidzovic

Stefan Nidzovic

Author at Rubik's Code

Stefan Nidzovic is a student at Faculty of Technical Science, at University of Novi Sad. More precisely, department of biomedical engineering, focusing mostly on applying the knowledge of computer vision and machine learning in medicine. He is also a member of “Creative Engineering Center”, where he works on various projects, mostly in computer vision.

Milos Marinkovic

Milos Marinkovic

Author at Rubik's Code

Miloš Marinković is a student of Biomedical Engineering, at the Faculty of Technical Sciences, University of Novi Sad. Before he enrolled at the university, Miloš graduated from the gymnasium “Jovan Jovanović Zmaj” in 2019 in Novi Sad. Currently he is a member of “Creative Engineering Center”, where he was involved in a couple of image processing and embedded electronic projects. Also, Miloš works as an intern at BioSense Institute in Novi Sad, on projects which include bioinformatics, DNA sequence analysis and machine learning. When he was younger he was a member of the Serbian judo national team and he holds the black belt in judo.

Discover more from Rubix Code

Subscribe now to keep reading and get access to the full archive.

Continue reading