Environment Preparation

First, ensure the opencv-python and numpy libraries are installed. If not, install them using the following command:

pip install opencv-python numpy

Import Libraries and Create Canvas

At the beginning of the code, import the required libraries and create a blank black image as the canvas (500x500 pixels, 3-channel color image):

import cv2
import numpy as np

# Create a 500x500 black image (height, width, number of channels)
img = np.zeros((500, 500, 3), np.uint8)

1. Drawing Lines

Use the cv2.line() function with parameters including the image, start point, end point, color (BGR format), line thickness, and line type (anti-aliasing for smoother edges):

# Draw a red anti-aliased line from (50, 50) to (450, 450)
cv2.line(img, (50, 50), (450, 450), (0, 0, 255), 2, cv2.LINE_AA)

2. Drawing Rectangles

Use the cv2.rectangle() function with parameters for top-left and bottom-right coordinates, color, and line thickness (-1 for filled):

# 1. Green outlined rectangle (thickness 3)
cv2.rectangle(img, (100, 100), (400, 400), (0, 255, 0), 3)

# 2. Blue filled rectangle (thickness -1)
cv2.rectangle(img, (50, 50), (200, 200), (255, 0, 0), -1)

3. Drawing Circles

Use the cv2.circle() function with parameters for center, radius, color, and line thickness:

# 1. Yellow outlined circle (thickness 5)
cv2.circle(img, (250, 250), 150, (0, 255, 255), 5)

# 2. Red filled circle (thickness -1)
cv2.circle(img, (250, 250), 80, (0, 0, 255), -1)

4. Drawing Polygons

Use cv2.polylines() (for outlines) or cv2.fillPoly() (for fills), specifying a list of vertices:

# 1. Draw a cyan triangle outline
triangle = np.array([[300, 150], [400, 300], [200, 300]], np.int32)
cv2.polylines(img, [triangle], True, (255, 255, 0), 3)

# 2. Fill a light red quadrilateral
quad = np.array([[350, 100], [450, 200], [350, 300], [250, 200]], np.int32)
cv2.fillPoly(img, [quad], (255, 100, 100))

5. Displaying the Image

After drawing, use cv2.imshow() to display the image and cv2.waitKey() to wait for a key press to close the window:

cv2.imshow("Basic Shapes", img)
cv2.waitKey(0)  # Wait for any key press
cv2.destroyAllWindows()  # Close all windows

Key Notes

  1. Color Channels: OpenCV uses BGR format, e.g., red is (0, 0, 255) instead of RGB’s (255, 0, 0).
  2. Filled vs. Outlined: A line thickness of -1 fills the shape, while positive values draw outline lines.
  3. Coordinate System: The top-left corner of the image is the origin (0, 0), with the x-axis increasing to the right and y-axis increasing downward.

By following these steps, you have mastered the core methods for drawing basic geometric shapes with OpenCV. You can further extend this to more complex graphics or image processing tasks.

Xiaoye