python

How to Draw A Rectangle On Any Image in Python


In this article, you will learn how to draw a rectangle on any image in Python. You need to make sure that you have installed OpenCV before attempting the example.

In this example, you will be using the official Python logo as an image. Download the image and save it locally.

Python-Logo

Draw A Rectangle On Any Image in Python

In order to draw a rectangle on any image, you can use the cv2.rectangle() method.

# Import cv2 module
import cv2

# Path to location of image in local storage
location = r'C:\Users\Codesource\Downloads\Python-Logo.jpg'

# Read the image in default mode
image = cv2.imread(location)

# Name of window
window = 'Image'

# Set the coordinates of top left corner of rectangle
top_left = (5, 5)

# Set the coordinates of bottom right corner of rectangle
bottom_right = (220, 220)

# Set the line color to red in BGR
colour = (0, 0, 255)

# Set line thickness to 5px
thickness = 5

# Draw a rectangle with red borders and thickness of 5 px
image = cv2.rectangle(image, top_left, bottom_right, colour, thickness)

# Display the image
cv2.imshow(window, image)

# Show the image until any key is pressed on keyboard
cv2.waitKey(0)

Rectange in image

Note: The cv2.rectangle() method functions by drawing a rectangle on any image.


Share on social media

//