This content originally appeared on CodeSource.io and was authored by Ariessa Norramli
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.
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)
Note: The cv2.rectangle()
method functions by drawing a rectangle on any image.
The post How to Draw A Rectangle On Any Image in Python appeared first on CodeSource.io.
This content originally appeared on CodeSource.io and was authored by Ariessa Norramli
Ariessa Norramli | Sciencx (2021-02-27T10:20:42+00:00) How to Draw A Rectangle On Any Image in Python. Retrieved from https://www.scien.cx/2021/02/27/how-to-draw-a-rectangle-on-any-image-in-python/
Please log in to upload a file.
There are no updates yet.
Click the Upload button above to add an update.