Introduction
OpenCV (Open Source Computer Vision Library) is an open-source computer vision and machine learning software library. It contains several hundred computer vision algorithms and is widely used for real-time computer vision applications. One of the basic tasks you can perform with OpenCV is drawing shapes on images, such as rectangles.
Syntax for Drawing a Rectangle
The function used to draw a rectangle in OpenCV is cv2.rectangle(). The syntax is as follows:

- image: The image on which the rectangle is to be drawn.
- start_point: The top-left corner of the rectangle (x, y).
- end_point: The bottom-right corner of the rectangle (x, y).
- color: The color of the rectangle in BGR format.
- thickness: The thickness of the rectangle border. If
-1is passed, the rectangle is filled.
Example
Here is a simple example to demonstrate how to draw a rectangle 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 top-left and bottom-right corners of the rectangle
top_left_corner = (100, 100)
bottom_right_corner = (400, 400)
# Define the color (BGR - Blue, Green, Red)
color = (255, 0, 0) # Blue color
# Define the thickness of the rectangle border
thickness = 2 # 2 pixels
# Draw the rectangle
cv2.rectangle(image, top_left_corner, bottom_right_corner, color, thickness)
# Display the image
cv2.imshow("Rectangle", 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 coordinates for the top-left and bottom-right corners of the rectangle.
- We set the rectangle color to blue and the thickness to 2 pixels.
- We use the
cv2.rectangle()function to draw the rectangle. - Finally, we display the image using
cv2.imshow() andwait for a key press to close the window.
This simple script effectively demonstrates how to draw a rectangle using OpenCV.