OpenCV is the best library for image processing. It has many inbuilt functions that allow you to manipulate images. You can convert color images to greyscale images, draw shapes on the images e.t.c. The cv2 rectangle() function is one of them. It allows you to draw rectangles on an existing image. In this entire tutorial, you will learn how to implement cv2 rectangle() in python through steps.
Steps to implement cv2 rectangle
In this section, you will know all the steps required to implement cv2 rectangle. Make sure to follow the given steps for better understanding.
Step 1: Import necessary libraries
The first step is to import required libraries for implementation. In this entire tutorial, I am using OpenCV only so let’s import it.
Step 2: Read the image
The second step is to read the image where you want to show the rectangle. In OpenCV you can read the image using the cv2.imread() function. Use the following code to read the image.
img = cv2.imread("bird.jpg")
Inside the method, the path of the image file is passed as an argument. Below is the image I am reading.
Step 3 : Use the cv2 rectangle()
The cv2.rectangle() function accepts the following parameters.
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.
Let’s define all these parameters and use the rectangle() function to draw a rectangle on the input image.
Use the below lines of code.
start_point = (20,20) end_point = (450,420) color = (0,255,255) img = cv2.rectangle(img,start_point,end_point,color)
Step 4: Show the image
Now the last part is to show the image. You can show the image using the cv2.imshow() function. Execute the following lines of code to see the image.
cv2.imshow("A Bird with rectangle",img) cv2.waitKey(0)
Here cv2.waitKey() is the total time you want to show the image window. The 0 value means you can show the image indefinitely until you press any keyboard.
You can also add some thickness to the rectangle by passing the thickness parametes in pixel. Juse execute the below lines of code and see the output.
import cv2 img = cv2.imread("bird.jpg") # show rectangle on the image 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)
These are steps for implementing cv2 rectangle in python. The main application of the rectangle function is to use it in facial recognization like drawing rectangles on every face of the people in the picture. There can also be other applications also. Please let us know by contacting us. I hope you have liked this tutorial. If you have any doubt then you can contact us for more help.
Join our list
Subscribe to our mailing list and get interesting stuff and updates to your email inbox.