Sunday, August 27, 2023

OpenCV basics continued...Draw Shapes

Now we will use OpenCV functions to draw the following shapes on an empty canvas-

  • Lines
  • Rectangles
  • Circles
  • Ellipses
  • Polylines

Create an Empty Canvas

So far, the images we have used are coming from the image files, now we are going to create an empty canvas from numpy library for drawing.

numpy is a popular Python library for numerical computing that provides a powerful multi-dimensional array object and various functions for performing mathematical operations on the arrays. It provides efficient storage and manipulation of arrays and allows for fast mathematical operations on the entire array without the need for loops. It is one of the fundamental libraries for scientific computing in Python and is widely used in fields such as data science, image processing, machine learning, and engineering.

As we know an image is made of pixels in rows and columns and channels, in another word 3-dimensional array. Therefore, numpy is good for supporting this type of operation.

Now import numpy in the beginning of the code.

1 import cv2

2 import numpy as np

Then create a canvas with size of 480 in width and 380 in height, a canvas is an empty image. Remember a color image has three channels representing BGR color space, so the array we are going to create using numpy should have three dimensions – 380, 480, and 3. The datatype of the array is uint8, it contains 8-bit values ranging from 0 to 255.

3 canvas = np.zeros((380, 480, 3), np.uint8)

4

5 cv2.imshow("Canvas", canvas)

6 cv2.waitKey(0)

7 cv2.destroyAllWindows()

So Line 3, np.zeros() create an array that has 380 rows, 480 columns, and 3 channels corresponding to blue, green and red. np.zeros() will fill the array with all 0, as we explained earlier all 0 means a black color.

Execute the above code, the result is a window with the black canvas with the size of 480 x 380.

Now we want to paint the canvas with some color. See line 4 in the below codes, it will set values of (235, 235, 235) to the array, which means to set a color to the canvas image, this color code is blue = 235, green = 235 and red = 235, it represents light gray.

4 canvas[:] = 235,235,235

The canvas is painted in light gray, as Figure below, we will draw shapes on it. If you want to paint it with different color, simply change the values in line 4.



Share:

0 comments:

Post a Comment