Python OpenCV Example | Draw a Rectangle on an Image

In this python opencv example, we will introduce how to draw a rectangle on an image. We will use cv2.rectangle() to implement it.

cv2.rectangle()

This function is defined as:

cv2.rectangle(image,start_point,end_point,color, thickness)

Parameters are:

image: Input image.

start_point: The coordinate from where you want to start drawing the rectangle.

end_point: Ending coordinate of the rectangle.

color: It is the color of the borderline of the rectangle to be drawn.

thickness: It is the thickness of the rectangle borderline in px.

Here is an example for how to use this function to draw a rectangle on an image.

Step 1: read an image

import cv2

img = cv2.imread("bird.jpg")

We will use cv2.imread() to load an image.

Step 2: draw a rectangle on an image

We will use cv2.rectangle() to draw a rectangle.

start_point = (20,20)
end_point = (450,420)
color = (0,255,255)
img = cv2.rectangle(img,start_point,end_point,color,10)
cv2.imshow("A Bird with rectangle",img)
cv2.waitKey(0)

Run this code, we may see:

Python OpenCV Example | Draw a Rectangle on an Image