0
0
Computer Visionml~5 mins

Drawing on images (lines, rectangles, circles, text) in Computer Vision

Choose your learning style9 modes available
Introduction
Drawing on images helps highlight or mark important parts, making it easier to understand or explain what the image shows.
You want to show where an object is in a photo by drawing a box around it.
You need to add labels or notes directly on an image for better explanation.
You want to connect points or show paths by drawing lines on a map or diagram.
You want to highlight a specific area with a circle to draw attention.
You want to create simple graphics or annotations on images for reports or presentations.
Syntax
Computer Vision
cv2.line(image, start_point, end_point, color, thickness)
cv2.rectangle(image, top_left_corner, bottom_right_corner, color, thickness)
cv2.circle(image, center, radius, color, thickness)
cv2.putText(image, text, position, font, font_scale, color, thickness, lineType=cv2.LINE_AA)
All drawing functions change the image directly (in-place).
Color is usually in BGR format (Blue, Green, Red) when using OpenCV.
Examples
Draws a blue line from point (10,10) to (100,10) with thickness 2.
Computer Vision
cv2.line(img, (10, 10), (100, 10), (255, 0, 0), 2)
Draws a green rectangle with top-left corner at (50,50) and bottom-right corner at (150,150).
Computer Vision
cv2.rectangle(img, (50, 50), (150, 150), (0, 255, 0), 3)
Draws a filled red circle centered at (200,200) with radius 40.
Computer Vision
cv2.circle(img, (200, 200), 40, (0, 0, 255), -1)
Writes white text 'Hello' at position (10,250) with font size 1 and thickness 2.
Computer Vision
cv2.putText(img, 'Hello', (10, 250), cv2.FONT_HERSHEY_SIMPLEX, 1, (255, 255, 255), 2)
Sample Model
This program creates a black image and draws a blue line, green rectangle, red filled circle, and white text on it. Then it saves the image as 'output_image.png'.
Computer Vision
import cv2
import numpy as np

# Create a black image
img = np.zeros((300, 400, 3), dtype=np.uint8)

# Draw a blue line
cv2.line(img, (50, 50), (350, 50), (255, 0, 0), 3)

# Draw a green rectangle
cv2.rectangle(img, (50, 100), (350, 200), (0, 255, 0), 4)

# Draw a filled red circle
cv2.circle(img, (200, 250), 40, (0, 0, 255), -1)

# Put white text
cv2.putText(img, 'Test Image', (100, 290), cv2.FONT_HERSHEY_SIMPLEX, 1, (255, 255, 255), 2)

# Save the image to file
cv2.imwrite('output_image.png', img)

# Print confirmation
print('Drawing complete and image saved as output_image.png')
OutputSuccess
Important Notes
Coordinates are in (x, y) format, where x is horizontal and y is vertical position.
Thickness -1 means the shape is filled completely.
Use cv2.imwrite() to save the image after drawing.
Summary
Drawing on images helps visually highlight or label parts of the image.
Use cv2.line, cv2.rectangle, cv2.circle, and cv2.putText to draw shapes and text.
Colors are in BGR order and thickness controls line or text boldness.