Create rectangle in opencv python

View Discussion

Improve Article

Save Article

  • Read
  • Discuss
  • View Discussion

    Improve Article

    Save Article

    OpenCV-Python is a library of Python bindings designed to solve computer vision problems. cv2.rectangle() method is used to draw a rectangle on any image.

    Syntax: cv2.rectangle(image, start_point, end_point, color, thickness)

    Parameters:
    image: It is the image on which rectangle is to be drawn.
    start_point: It is the starting coordinates of rectangle. The coordinates are represented as tuples of two values i.e. (X coordinate value, Y coordinate value).
    end_point: It is the ending coordinates of rectangle. The coordinates are represented as tuples of two values i.e. (X coordinate value, Y coordinate value).
    color: It is the color of border line of rectangle to be drawn. For BGR, we pass a tuple. eg: (255, 0, 0) for blue color.
    thickness: It is the thickness of the rectangle border line in px. Thickness of -1 px will fill the rectangle shape by the specified color.

    Return Value: It returns an image.

    Image used for all the below examples:

    Create rectangle in opencv python

    Example #1:

    import cv2 

    path = r'C:\Users\Rajnish\Desktop\geeksforgeeks\geeks.png'

    image = cv2.imread(path)

    window_name = 'Image'

    start_point = (5, 5)

    end_point = (220, 220)

    color = (255, 0, 0)

    thickness = 2

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

    cv2.imshow(window_name, image) 

    Output:

    Create rectangle in opencv python

    Example #2:

    Using thickness of -1 px to fill the rectangle by black color.

    import cv2 

    path = r'C:\Users\Rajnish\Desktop\geeksforgeeks\geeks.png'

    image = cv2.imread(path, 0)

    window_name = 'Image'

    start_point = (100, 50)

    end_point = (125, 80)

    color = (0, 0, 0)

    thickness = -1

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

    cv2.imshow(window_name, image) 

    Output:

    Create rectangle in opencv python


    Goal

    • Learn to draw different geometric shapes with OpenCV
    • You will learn these functions : cv.line(), cv.circle() , cv.rectangle(), cv.ellipse(), cv.putText() etc.

    Code

    In all the above functions, you will see some common arguments as given below:

    • img : The image where you want to draw the shapes
    • color : Color of the shape. for BGR, pass it as a tuple, eg: (255,0,0) for blue. For grayscale, just pass the scalar value.
    • thickness : Thickness of the line or circle etc. If -1 is passed for closed figures like circles, it will fill the shape. default thickness = 1
    • 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.

    Drawing Line

    To draw a line, you need to pass starting and ending coordinates of line. We will create a black image and draw a blue line on it from top-left to bottom-right corners.

    import numpy as np

    import cv2 as cv

    img = np.zeros((512,512,3), np.uint8)

    cv.line(img,(0,0),(511,511),(255,0,0),5)

    Drawing Rectangle

    To draw a rectangle, you need top-left corner and bottom-right corner of rectangle. This time we will draw a green rectangle at the top-right corner of image.

    Drawing Circle

    To draw a circle, you need its center coordinates and radius. We will draw a circle inside the rectangle drawn above.

    Drawing Ellipse

    To draw the ellipse, we need to pass several arguments. One argument is the center location (x,y). Next argument is axes lengths (major axis length, minor axis length). angle is the angle of rotation of ellipse in anti-clockwise direction. startAngle and endAngle denotes the starting and ending of ellipse arc measured in clockwise direction from major axis. i.e. giving values 0 and 360 gives the full ellipse. For more details, check the documentation of cv.ellipse(). Below example draws a half ellipse at the center of the image.

    Drawing Polygon

    To draw a polygon, first you need coordinates of vertices. Make those points into an array of shape ROWSx1x2 where ROWS are number of vertices and it should be of type int32. Here we draw a small polygon of with four vertices in yellow color.

    pts = np.array([[10,5],[20,30],[70,20],[50,10]], np.int32)

    pts = pts.reshape((-1,1,2))

    NoteIf third argument is False, you will get a polylines joining all the points, not a closed shape. cv.polylines() can be used to draw multiple lines. Just create a list of all the lines you want to draw and pass it to the function. All lines will be drawn individually. It is a much better and faster way to draw a group of lines than calling cv.line() for each line.

    Adding Text to Images:

    To put texts in images, you need specify following things.

    • Text data that you want to write
    • Position coordinates of where you want put it (i.e. bottom-left corner where data starts).
    • Font type (Check cv.putText() docs for supported fonts)
    • Font Scale (specifies the size of font)
    • regular things like color, thickness, lineType etc. For better look, lineType = cv.LINE_AA is recommended.

    We will write OpenCV on our image in white color.

    font = cv.FONT_HERSHEY_SIMPLEX

    cv.putText(img,'OpenCV',(10,500), font, 4,(255,255,255),2,cv.LINE_AA)

    Result

    So it is time to see the final result of our drawing. As you studied in previous articles, display the image to see it.

    Create rectangle in opencv python

    image

    Additional Resources

    1. The angles used in ellipse function is not our circular angles. For more details, visit this discussion.

    Exercises

    1. Try to create the logo of OpenCV using drawing functions available in OpenCV.

    How do you make a rectangle in OpenCV?

    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.

    How do you make a rectangle in Python?

    We can create a simple rectangle by defining a function that takes in two integers representing side length and side height. Then we can loop four times, using the forward() function to create a side representing either the length or height, then rotating the cursor 90 degrees with the right() function.

    How do I create a multiple rectangle in OpenCV Python?

    Function used:.
    Syntax: cv2.imread(path_of_image, flag).
    Syntax: cv2.rectangle(image, starting_coordinate, ending_coordinate, color, thickness).
    Syntax: cv2.imshow(window_name, image).

    How do you draw shapes in OpenCV?

    Some of the drawing functions are :.
    line() : Used to draw line on an image..
    rectangle() : Used to draw rectangle on an image..
    circle() : Used to draw circle on an image..
    putText() : Used to write text on image..