Draw a rectangle on an image with OpenCV

In OpenCV, use the cv2.rectangle() function to draw a rectangle on an image. First, we will read the image using the imread() function in OpenCV.

Let us now see the example:

The following is the output:

Draw a rectangle on an image with OpenCV
Explanation:

This Python script uses the OpenCV library to load, resize, and draw a rectangle on an image. First, the script imports the OpenCV library:

  • It then reads an image from the specified file path and loads it in color. The image is resized to dimensions of 600×600 pixels using the cv2.resize() function.
  • After resizing, the script draws a blue rectangle on the image, with the top-left corner at coordinates (15, 25) and the bottom-right corner at coordinates (200, 150).
  • The cv2.rectangle() function is used for this purpose, where the first argument specifies the image, the second argument specifies the top-left corner, the third argument specifies the bottom-right corner, the fourth argument specifies the color (blue), and the fifth argument specifies the thickness (15 pixels).
  • Finally, the script displays the resized image with the drawn rectangle in a window titled “Image Resized:” using cv2.imshow(), waits for a key press with cv2.waitKey(0), and closes all OpenCV windows with cv2.destroyAllWindows().
  • This process allows users to view the modified image with the drawn rectangle and close the display window at their convenience.

If you liked the tutorial, spread the word and share the link and our website Studyopedia with others.


For Videos, Join Our YouTube Channel: Join Now


Read More:

Draw a circle on an image with OpenCV
Draw an ellipse on an image with OpenCV
Studyopedia Editorial Staff
contact@studyopedia.com

We work to create programming tutorials for all.

No Comments

Post A Comment

Discover more from Studyopedia

Subscribe now to keep reading and get access to the full archive.

Continue reading