Python | cv2 rectangle() Method


In this tutorial, we will see how to draw a Rectangle shape, Square shapes on the given input image in python by the use of open-cv which exists as cv2 (computer vision) library.

You can use rectangle() method of cv2 library to draw rectange, squares on the image. To use cv2 library, you need to import cv2 library using import statement.

Now let’s see the syntax and return value of rectangle() method, then we will move on the examples.



You can pass 7 parameters to resize() method. Among the 7 parameters, the first four(image,starting_coordinate,ending_coordinate and color) are mandatory; rest(thickness, lineType and shift) are optional.

Necessary parameters are:

  1. image: Input image of n-dimensional array.
  2. starting_coordinate: Starting top most Left coordinate of the rectangle which is given in the form of tuple.
  3. ending_coordinate: Ending bottom most right coordinate of the rectangle which is given in the form of tuple.
  4. color: Boundary color of rectangular shape which is given in the form of tuple with respective BGR values.
  5. Optional parameters are :

  6. thickness: Thickness of rectangle’s boundary (given in pixels). Its default value is 1.
  7. lineType: Type of line, whether 8-connected, anti-aliased line etc. By default, it is 8-connected. cv.LINE_AA gives anti-aliased line which looks great for curves.
  8. shift: Represents the number of fractional bits in the coordinates.

Return Value

It returns Output image of n-dimensional array with rectangular shapes drawn on it .

cv2.rectangle() Method example

Now Let’s see the Python code :

Example 1: Draw a rectangular shape on the image with a thin border.

Output :


Example 2: Draw a square shape on the image with bold border.


You may similarly change the values of other properties and observe the outputs.


Add Comment