Life2Coding
How to Draw Different Shapes on Images using OpenCV

This post will be helpful in learning OpenCV using Python programming. Here I will show how to implement OpenCV functions and apply it in various aspects using some examples. Then the output will be shown with some comparisons as well.

Requirements:

First, you need to setup your Python Environment with OpenCV. You can easily do it by following Life2Coding’s tutorial on YouTube: Linking OpenCV 3 with Python 3

Goals:

In this tutorial, I will show you how to draw different shapes on images using OpenCV library and Python coding.

Documentation:

Python: cv2.line(img, pt1, pt2, color[, thickness[, lineType[, shift]]]) → None

Draws a line segment connecting two points.

Python: cv2.rectangle(img, pt1, pt2, color[, thickness[, lineType[, shift]]]) → None

Draws a simple, thick, or filled up-right rectangle.

Python: cv2.circle(img, center, radius, color[, thickness[, lineType[, shift]]]) → None

Draws a circle.

Python: cv2.ellipse(img, center, axes, angle, startAngle, endAngle, color[, thickness[, lineType[, shift]]]) → None

Python: cv2.ellipse(img, box, color[, thickness[, lineType]]) → None

Draws a simple or thick elliptic arc or fills an ellipse sector.

Python: cv2.polylines(img, pts, isClosed, color[, thickness[, lineType[, shift]]]) → None

Draws several polygonal curves.

Python: cv2.putText(img, text, org, fontFace, fontScale, color[, thickness[, lineType[, bottomLeftOrigin]]]) → None

Draws a text string.

Steps:

  • Draw different shapes using cv2.line(), cv2.rectangle, cv2. circle, cv2.ellipse, cv2.polylines, cv2.putText()
  • Display Image using cv2.imshow()
  • Wait for keyboard button press using cv2.waitKey()
  • Exit window and destroy all windows using cv2.destroyAllWindows()

Example Code:

import cv2
import numpy as np


def main():
    img1 = np.zeros((512, 512, 3), np.uint8)
    # img1.fill(255)

    cv2.line(img1, (10, 199), (209, 50), (250, 200, 10), 2)

    cv2.rectangle(img1, (250, 60), (350, 170), (0, 255, 0), 2)

    cv2.circle(img1, (160, 160), 50, (0, 150, 255), -1)

    cv2.ellipse(img1, (160, 260), (50, 20), 0, 0, 360, (10, 127, 127), -1)

    points = np.array([[100, 2], [125, 20], [179, 10], [230, 15], [50, 60]], np.int32)
    points = points.reshape((-1, 1, 2))

    cv2.polylines(img1, [points], True, (0, 12, 255))

    text1 = 'Life2Coding'
    cv2.putText(img1, text1, (50, 400), cv2.FONT_HERSHEY_DUPLEX, 2.2, (205, 255, 0))

    cv2.imshow('Hanif', img1)
    cv2.waitKey(0)
    cv2.destroyWindow('Hanif')


if __name__ == "__main__":
    main()

Output:

Capture How to Draw Different Shapes on Images using OpenCV

life2coding_icon [] How to Draw Different Shapes on Images using OpenCV

Leave a Reply

Your email address will not be published.

This site uses Akismet to reduce spam. Learn how your comment data is processed.