Drawing on Images in OpenCV

Drawing on the image become very interesting and important, when we track object or people, we usually highlight them. OpenCV has inbuilt functionality to draw shapes on the image. We might draw different shapes on the images.

Please be aware that I will be writing the below code only once, but I will be using it in every program. Code to get the image in RGB color in OpenCV

import cv2
import matplotlib.pyplot as plt
img = cv2.imread("C:/Users/pnagaraj/Pictures/opencv/flower.jpg")
rgb_img = cv2.cvtColor(img, cv2.COLOR_BGR2RGB)
Top left corner of the image is (0, 0) in OpenCV

OpenCV considers the image as Three Dimensional array, containing rows (height), columns (width), colors(BGR).

So when we draw any shape on the image will alter the array, with new values wherever is required based on the shape and thickness, and color of the shape.

Rectangle shape on Images

Let's understand the rectangle first; a rectangle can be drawn using coordinates of two points. One being left the top corner, second left the bottom corner. I hope you know that the rectangle has only straight lines.

In the below image, we got to provide point D and Point C, Point E, B are calculated automatically calculated.

reactangle-shape-opencv

Try to guess what are the details present in the above rectangle (not drawn using OpenCV).

  • On the graph, we have the rectangle
  • Coordinates of point D, Point C
  • Color of the line
  • Line style

Similar to the above details, we have to provide details to OpenCV so that it can draw the line with the given details.

rectangle() is the function that will be used to draw the line.

Syntax:

cv2.rectangle(base_iamge, pt1=(x1,y1), pt2=(x2, y2), color=(R, G, B), thickness, line_style)
Color should be in RGB not BGR

Complete code to draw a rectangle on an image in OpenCV.

image_drawn = cv2.rectangle(rgb_img, pt1=(250, 250),
                            pt2=(400, 400), color=(255, 0, 0), thickness=20)
plt.imshow(image_drawn)

rectangle-on-image

Drawing Circle on an Image with OpenCV

Drawing circle in a math class needs below items; the same applies when we draw a circle using OpenCV.

  • Where are we going to draw, paper (base image)
  • where the center point /origin of the circle is
  • What is the radius or diameter
  • circle line thickness
  • Style of the line

circle() function in the OpenCV draws a circle over an image.

Syntax:

circle_drawn = cv2.circle(base_image, center=(x, y), radius, color=(R, G, B), thickness)

Complete code for drawing circle on Image.

circle_drawn = cv2.circle(rgb_img, center=(600, 300),
                          radius=100, color=(0, 255, 0), thickness=20)
plt.imshow(circle_drawn)

circle-on-image-opencv

Draw line on an image on OpenCV

We can draw a line using the line() function from the OpenCV. To draw a line, we need the below details.

  • Base image
  • Starting point
  • ending point
  • Color of line
  • The thickness of the line

OpenCV example to draw a line

line_drawn = cv2.line(rgb_img, pt1=(100, 100), pt2=(400, 500),
                      color=(255, 0, 0), thickness=20 )
plt.imshow(line_drawn)

line-draw-on-image-opencv

Fill the shape with color in OpenCV

So far, we have seen how to draw shapes, but sometimes we need to fill the shape with color.

To fill any shape in OpenCV, we need to provide thickness as -1.

fille-shape-image-opencv

Text on the Image in OpenCV

Drawing a text on an image will be useful when we want to read some photos and to compare the text it has; in such a situation, writing text on the image will help us to compare the texts that we read and write to the image.

The Bottom point highlighted in the below image is going to be the origin of the text in OpenCV.

text-on-image-opencv

putText() function from OpenCV will help us to put the text into an image. Below are the details that are required for writing text to the image.

  • the base image
  • what text to write
  • What is the origin of the text (left bottom corner)
  • What is font Type
  • Font scale( font size)
  • Color of the font
  • The thickness of font (font-weight)
  • lineType

OpenCV putText() example.

text_image = cv2.putText(rgb_img, "chercher tech", org=(100, 200),
                         fontFace= cv2.FONT_HERSHEY_PLAIN, fontScale=6,
                         color=(150,15,110), thickness=20)
plt.imshow(text_image)

text-image-opencv-overlay

Draw Polygons/polylines with OpenCV

We have seen some basic shapes, but sometimes the object we want to highlight could be in a shape that is not standard. In such cases, we can use the polygons to create custom shapes with OpenCV.

polylines() function in OpenCV draws polylines over the images.

Difference between polygons and polylines (OpenCV):

Polygon and polylines are defined by a list of points, through which the line is drawn. The differences between polygon and polyline are:

  • A polygon is always closed, meaning that there is a line from the last point of the first point. A polyline can be open.
  • A polygon is filled by default, but can also be not filled. A polyline can never be filled.
  • polygon draws a line between multiple points with the last point going back to the first point

polygons-shape-opencv

polylines-opencv

Details required to draw polylines/Polygon:

  • Base images
  • vertices (corner/endpoint)
  • Is the shape to be closed
  • color of the line
  • the thickness of the line

Syntax :

poly_image = cv2.polylines(base_image, [corners_as_matrix], isClosed, color, thickness)

Code example to draw the polyline on an image, if you notice we have set that shape is not closed. So below code will create a polyline.

corners = np.array([[100, 100], [100, 200], [300, 200]])
poly_image = cv2.polylines(rgb_img, [corners], isClosed=False, color=(255,0,0), thickness=9)
plt.imshow(poly_image)

polylines-draw-opencv

Setting isClosed=True in the above code will close the shape and creates a polygon.

polylines-polygon-draw-opencv

Starting and closing points as same in polylines:

When starting and closing points are the same in polylines, then it will create the polygon.

corners = np.array([[100, 100], [100, 200], [300, 200], [100, 100]])
poly_image = cv2.polylines(rgb_img, [corners],
                           isClosed=False, color=(255,0,0), thickness=9)
plt.imshow(poly_image)

polylines-close-start-same-point-opencv

Fill the polygon in OpenCV:

In all the shapes, OpenCV has provided an option to provide thickness as -1 so that it will fill the shape, but in the case of polygons, the thickness cannot less than zero.

If you try to use -1 for thickness, then you will get below error.

OpenCV(3.4.2) C:\Miniconda3\conda-bld\opencv-suite_1534379934306\work\modules\imgproc\src\drawing.cpp:2039: error: (-215:Assertion failed) pts && npts && ncontours >= 0 && 0 <= thickness && thickness <= MAX_THICKNESS && 0 <= shift && shift <= XY_SHIFT in function 'cv::polylines'

To fill the polygon, we have to use a funtion called fillPoly() in OpenCV.

corners = np.array([[100, 100], [100, 200], [300, 200], [100, 100]])
poly_fill_image = cv2.fillPoly(rgb_img, [corners], color=(255, 255, 0))
plt.imshow(poly_fill_image)

fillpoly-opencv

Comment / Suggestion Section
Point our Mistakes and Post Your Suggestions