Let’s do some drawing

From Lofaro Lab Wiki
Jump to: navigation, search

It is time to do some drawing. Let’s draw some line, circle, rectangle and all other shapes. It is important learn drawing using OpenCV as when you are going to do some image processing you will be required to do these things for optimizing your image and videos. Staring with some codes

import numpy as np
import cv2
canvas= np.zeros((300,300,3),np.uint8)
cv2.imshow("canvas",canvas)
cv2.waitKey(delay=0)
red=(0,0,255)
cv2.line(canvas,(300,0),(0,300),red,3)
cv2.imshow("Canvas",canvas)
cv2.waitKey(delay=0)


The first few lines are clear that we imported our required library. The third line of these codes we have made a Numpy array named canvas which has 300 rows and 300 columns, yielding a 300x300 pixel image and where we allocated 3 channels for red, green and blue. According to the Numpy array the zeros method filled every element in the array with an initial value of zero. The second argument of the canvas array describe the data type we want to work with which in here is a 8 bit unsigned integer with pixels in the range [0,255] so that we can represent our image as an RGB image. This code will draw a red line in a black background after running.

We can go into drawing a rectangle which is also very easy to do with.

green = (0, 255, 0)
cv2.rectangle(canvas, (10, 10), (60, 60), green)

This will draw a rectangle in the canvas image, the first argument is the image where we want to draw the rectangle. The 2nd and 3rd arguments are our starting and ending points of the rectangle where we are staring from (10, 10) and ends at (60, 60), defining a region of 50x50 pixels. The final argument is the color of the rectangle we want to draw. If we want to fill it with blue green color we need to pass -1 as thickness to the method.

cv2.rectangle(canvas, (10, 10), (60, 60), green,-1)

Drawing.jpg