Draw rectangle on an image using OpenCV

OpenCVPythonServer Side ProgrammingProgramming

In this program, we will draw a rectangle using the OpenCV function rectangle(). This function takes some parameters like starting coordinates, ending coordinates, color and thickness and the image itself.

Original Image


Step 1: Import cv2.
Step 2: Read the image using imread().
Step 3: Define the starting coordinates.
Step 5: Define the ending coordinates.
Step 6: Define the color and the thickness.
Step 7: Draw the rectangle using the cv2.reactangle() function.
Step 8: Display the rectangle.

Example Code

import cv2

image = cv2.imread('testimage.jpg')
height, width, channels = image.shape
start_point = (0,0)
end_point = (width, height)
color = (0,0,255)
thickness = 5

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


Published on 17-Mar-2021 12:03:19