How to Draw Circle in OpenCV for Computer Vision
Use the
cv2.circle() function in OpenCV to draw a circle on an image by specifying the image, center coordinates, radius, color, and thickness. This function modifies the image directly and is commonly used in computer vision tasks to highlight or mark circular regions.Syntax
The cv2.circle() function draws a circle on an image. It requires the following parameters:
- img: The image where the circle will be drawn.
- center: Tuple of (x, y) coordinates for the circle's center.
- radius: Radius of the circle in pixels.
- color: Circle color in BGR format (e.g., (255, 0, 0) for blue).
- thickness: Thickness of the circle outline. Use
-1to fill the circle.
python
cv2.circle(img, center, radius, color, thickness)
Example
This example creates a black image and draws a blue circle with a radius of 50 pixels at the center. The circle is filled.
python
import cv2 import numpy as np # Create a black image 400x400 pixels img = np.zeros((400, 400, 3), dtype=np.uint8) # Define center and radius center = (200, 200) radius = 50 # Draw a filled blue circle cv2.circle(img, center, radius, (255, 0, 0), thickness=-1) # Save the image to file cv2.imwrite('circle_example.png', img)
Output
A 400x400 black image file named 'circle_example.png' with a filled blue circle at the center.
Common Pitfalls
- Forgetting that OpenCV uses BGR color format, not RGB, so red is (0, 0, 255).
- Using thickness=0 does not draw anything; use thickness=-1 to fill the circle.
- Coordinates outside the image boundaries will cause no visible circle or errors.
- Modifying the image without copying will change the original image data.
python
import cv2 import numpy as np img = np.zeros((100, 100, 3), dtype=np.uint8) # Correct color (BGR) - circle will be blue cv2.circle(img, (50, 50), 30, (255, 0, 0), 2) # Blue circle # Wrong thickness (0 means no circle) cv2.circle(img, (50, 50), 20, (0, 255, 0), 0) # No circle drawn # Correct usage cv2.circle(img, (50, 50), 20, (0, 255, 0), -1) # Filled green circle
Quick Reference
Remember these tips when drawing circles with OpenCV:
- Color format: Use BGR, not RGB.
- Thickness: Use positive integer for outline,
-1for filled circle. - Center and radius: Must be within image bounds.
- Image type: Use a NumPy array with dtype
uint8.
Key Takeaways
Use cv2.circle() with image, center, radius, color (BGR), and thickness to draw circles.
Set thickness to -1 to fill the circle instead of just drawing the outline.
OpenCV uses BGR color format, so colors must be specified accordingly.
Ensure circle center and radius fit inside the image to be visible.
Drawing modifies the original image array directly.