Draw Shapes
In this tutorial we’ll learn about drawing functions in OpenCV. We will also use these functions to draw different shapes on images.
What are drawing functions in OpenCV?
-
drawing functions are used to draw different shapes such as lines, circles, rectangles, polygons, and text on images or videos.
-
These drawing functions are very useful to perform tasks such as image annotation, object detection, and visualizations.
Let's understand the concept with some practical work.
Example - Drawing line using OpenCV.
Input
Code:
import cv2
img = cv2.imread('demo.png')
image = cv2.line(img, (50, 200), (880, 20),(90, 80, 10), 20)
#cv2.line(image_path, (start_point), (end_point), (color_value_in_BGR), thickness)
cv2.imshow('result', image)
cv2.waitKey(0)
cv2.destroyAllWindows()
-
First we imported cv2 and used cv2.imread function to read the image.
-
then, we used the cv2.line function to draw the line with required values like - image path, start coordinates, end coordinates, color code, and line thickness.
-
At last, we used cv2.imshow function to display the final result.
Result:
Example - Drawing Circle using OpenCV.
Input
Code:
import cv2
img = cv2.imread('demo.png')
image = cv2.circle(img, (250, 200), 180,(90, 80, 10), 10)
# cv2.circle(image_path, (start_point), Radius, (color_value_in_BGR), thickness)
cv2.imshow('result', image)
cv2.imwrite('drawcv.jpg', image)
cv2.waitKey(0)
cv2.destroyAllWindows()
-
First we imported cv2 and used cv2.imread function to read the image.
-
then, we used the cv2.circle function with required values like - image path, start coordinates, radius, color code, and circle thickness.
-
At last we used cv2.imshow function to display the final result.
Result:
Example - Drawing Rectangle using OpenCV.
Input
Code:
import cv2
img = cv2.imread('demo.png')
image = cv2.rectangle(img, (50, 200), (880, 20),(90, 80, 10), 20)
#cv2.rectangle(image_path, (start_point), (end_point), (color_value_in_BGR), thickness)
cv2.imshow('result', image)
cv2.waitKey(0)
cv2.destroyAllWindows()
-
First we imported cv2 and used cv2.imread function to read the image.
-
then, we used the cv2.rectangle function with required values like - image path, start coordinates, radius, color code, and circle thickness.
-
At last we used cv2.imshow function to display the final result.
Result: