Drawing a Circle Using OpenCV

Introduction

OpenCV (Open Source Computer Vision Library) is an open-source computer vision and machine learning software library that provides numerous algorithms and tools for image processing and computer vision applications. One of the basic operations you can perform with OpenCV is drawing geometric shapes, such as circles, on images.

Syntax for Drawing a Circle

The function used to draw a circle in OpenCV is cv2.circle(). The syntax is as follows:

  • image: The image on which the circle is to be drawn.
  • center: The center of the circle (x, y).
  • radius: The radius of the circle.
  • color: The color of the circle in BGR format.
  • thickness: The thickness of the circle outline. If -1 is passed, the circle is filled.

Example

Here is a simple example to demonstrate how to draw a circle on an image using OpenCV:

import cv2
import numpy as np


# Create a blank image (black background)
image = np.zeros((500, 500, 3), dtype="uint8")


# Define the center and radius of the circle
center = (250, 250)
radius = 100


# Define the color (BGR - Blue, Green, Red)
color = (0, 255, 0)  # Green color


# Define the thickness of the circle outline
thickness = 2  # 2 pixels


# Draw the circle
cv2.circle(image, center, radius, color, thickness)


# Display the image
cv2.imshow("Circle", image)


# Wait for a key press and close the image window
cv2.waitKey(0)
cv2.destroyAllWindows()

In this example:

  • We create a 500×500 pixel black image using NumPy.
  • We define the center coordinates and radius of the circle.
  • We set the circle color to green and the thickness to 2 pixels.
  • We use the cv2.circle() function to draw the circle.
  • Finally, we display the image using cv2.imshow(), and wait for a key press to close the window.

This simple script effectively demonstrates how to draw a circle using OpenCV.

Leave a comment

Your email address will not be published. Required fields are marked *