OpenCV Tutorial

Image Processing

Feature Detection and Description

Drawing Functions

Video Processing

Applications and Projects

Draw a rectangle in OpenCV

Drawing a rectangle on an image in OpenCV is a simple task. In this tutorial, I'll guide you on how to draw a rectangle using the rectangle() function provided by OpenCV.

Steps to Draw a Rectangle using OpenCV:

1. Setup:

Make sure you have OpenCV installed:

pip install opencv-python

Import necessary libraries:

import cv2
import numpy as np

2. Load or Create an Image:

You can either create a blank image or load an existing one:

# Create a blank image (white background)
image = np.ones((500, 500, 3), np.uint8) * 255

# Or, load an existing image:
# image = cv2.imread('path_to_image.jpg')

3. Draw a Rectangle:

Use the cv2.rectangle() function:

cv2.rectangle(img, pt1, pt2, color[, thickness[, lineType[, shift]]])

Where:

  • img: The image on which you want to draw the rectangle.
  • pt1: Vertex of the rectangle (top-left corner).
  • pt2: Vertex of the rectangle opposite to pt1 (bottom-right corner).
  • color: Rectangle color in (B, G, R) format.
  • thickness: Thickness of the rectangle border. If negative (e.g., -1), the rectangle gets filled with the specified color.
  • lineType (optional): Line type, e.g., 8-connected, anti-aliased line, etc.
  • shift (optional): Number of fractional bits in the point coordinates.

Example:

top_left = (100, 100)
bottom_right = (400, 400)
color = (0, 255, 0)  # Green color in BGR format
thickness = 2

cv2.rectangle(image, top_left, bottom_right, color, thickness)

4. Display the Image with the Rectangle:

cv2.imshow('Rectangle', image)
cv2.waitKey(0)
cv2.destroyAllWindows()

Complete Code:

Here's a combined script for the entire process:

import cv2
import numpy as np

# Create a blank image
image = np.ones((500, 500, 3), np.uint8) * 255

# Draw a rectangle on the image
top_left = (100, 100)
bottom_right = (400, 400)
color = (0, 255, 0)  # Green in BGR
thickness = 2

cv2.rectangle(image, top_left, bottom_right, color, thickness)

# Display the image
cv2.imshow('Rectangle', image)
cv2.waitKey(0)
cv2.destroyAllWindows()

This script will display a white image with a green rectangle. You can adjust the rectangle's corners, color, and thickness as needed.

  1. Python code for drawing rectangles in OpenCV:

    import cv2
    import numpy as np
    
    # Create a black image
    img = np.zeros((300, 400, 3), dtype=np.uint8)
    
    # Draw a rectangle (top-left, bottom-right, color, thickness)
    cv2.rectangle(img, (50, 50), (350, 250), (0, 255, 0), 2)
    
    # Display the image with the drawn rectangle
    cv2.imshow('Rectangle Drawing', img)
    cv2.waitKey(0)
    cv2.destroyAllWindows()
    
  2. Rectangle drawing functions and parameters in OpenCV:

    # OpenCV rectangle function signature
    cv2.rectangle(img, pt1, pt2, color, thickness, lineType)
    
    • pt1: Top-left corner of the rectangle.
    • pt2: Bottom-right corner of the rectangle.
    • color: Rectangle color.
    • thickness: Thickness of the rectangle border.
    • lineType: Type of line for rectangle border (e.g., cv2.LINE_8, cv2.LINE_AA).
  3. Drawing rectangles with specified color and thickness in OpenCV:

    import cv2
    import numpy as np
    
    # Create a black image
    img = np.zeros((300, 400, 3), dtype=np.uint8)
    
    # Draw a blue rectangle with thickness 3
    cv2.rectangle(img, (50, 50), (350, 250), (255, 0, 0), 3)
    
    # Display the image with the drawn rectangle
    cv2.imshow('Colored Rectangle Drawing', img)
    cv2.waitKey(0)
    cv2.destroyAllWindows()
    
  4. Real-time rectangle drawing in OpenCV:

    import cv2
    import numpy as np
    
    # Create a black image
    img = np.zeros((300, 400, 3), dtype=np.uint8)
    
    # Callback function for mouse events
    def draw_rectangle(event, x, y, flags, param):
        if event == cv2.EVENT_LBUTTONDOWN:
            cv2.rectangle(img, (x, y), (x + 50, y + 50), (0, 255, 0), 2)
            cv2.imshow('Real-time Rectangle Drawing', img)
    
    # Create a named window
    cv2.namedWindow('Real-time Rectangle Drawing')
    
    # Set the callback function for mouse events
    cv2.setMouseCallback('Real-time Rectangle Drawing', draw_rectangle)
    
    while True:
        # Break the loop on 'Esc' key press
        if cv2.waitKey(1) & 0xFF == 27:
            break
    
    cv2.destroyAllWindows()
    
  5. Drawing rectangles on images and videos in OpenCV:

    import cv2
    
    # Load an image
    img = cv2.imread('image.jpg')
    
    # Draw a rectangle on the image
    cv2.rectangle(img, (50, 50), (350, 250), (0, 255, 0), 2)
    
    # Display the image with the drawn rectangle
    cv2.imshow('Rectangle on Image', img)
    cv2.waitKey(0)
    cv2.destroyAllWindows()
    

    For videos, use the same cv2.rectangle() function within a video processing loop.

  6. Combining rectangle drawing with other OpenCV functions:

    import cv2
    import numpy as np
    
    # Load an image
    img = cv2.imread('image.jpg')
    
    # Draw a rectangle and a line on the image
    cv2.rectangle(img, (50, 50), (350, 250), (0, 255, 0), 2)
    cv2.line(img, (100, 100), (300, 200), (0, 0, 255), 2)
    
    # Display the image with the drawn rectangle and line
    cv2.imshow('Rectangle and Line Drawing', img)
    cv2.waitKey(0)
    cv2.destroyAllWindows()
    
  7. Rectangle annotations for object detection in OpenCV:

    import cv2
    import numpy as np
    
    # Load an image
    img = cv2.imread('object_detection_image.jpg')
    
    # Annotate object with a rectangle
    cv2.rectangle(img, (100, 50), (250, 150), (0, 255, 0), 2)
    
    # Display the image with the rectangle annotation
    cv2.imshow('Object Detection with Rectangle Annotation', img)
    cv2.waitKey(0)
    cv2.destroyAllWindows()
    
  8. Drawing rectangles with specified dimensions and position in OpenCV:

    import cv2
    import numpy as np
    
    # Create a black image
    img = np.zeros((300, 400, 3), dtype=np.uint8)
    
    # Draw a rectangle with specified dimensions and position
    x, y, width, height = 50, 50, 300, 200
    cv2.rectangle(img, (x, y), (x + width, y + height), (0, 255, 0), 2)
    
    # Display the image with the drawn rectangle
    cv2.imshow('Rectangle with Dimensions', img)
    cv2.waitKey(0)
    cv2.destroyAllWindows()
    
  9. Drawing filled and unfilled rectangles in OpenCV:

    import cv2
    import numpy as np
    
    # Create a black image
    img = np.zeros((300, 400, 3), dtype=np.uint8)
    
    # Draw a filled rectangle
    cv2.rectangle(img, (50, 50), (350, 250), (0, 255, 0), -1)
    
    # Draw an unfilled rectangle
    cv2.rectangle(img, (100, 100), (300, 200), (0, 0, 255), 2)
    
    # Display the image with the drawn rectangles
    cv2.imshow('Filled and Unfilled Rectangles', img)
    cv2.waitKey(0)
    cv2.destroyAllWindows()
    
  10. Adding transparency to drawn rectangles in OpenCV:

    import cv2
    import numpy as np
    
    # Create a transparent image
    img = np.zeros((300, 400, 4), dtype=np.uint8)
    img[:, :, 3] = 255  # Set alpha channel to 255 (fully opaque)
    
    # Draw a transparent filled rectangle
    cv2.rectangle(img, (50, 50), (350, 250), (0, 255, 0, 128), -1)
    
    # Draw a transparent unfilled rectangle
    cv2.rectangle(img, (100, 100), (300, 200), (0, 0, 255, 128), 2)
    
    # Display the image with the drawn transparent rectangles
    cv2.imshow('Transparent Rectangles Drawing', img)
    cv2.waitKey(0)
    cv2.destroyAllWindows()
    
  11. Code examples for drawing rectangles with different styles in OpenCV:

    import cv2
    import numpy as np
    
    # Create a black image
    img = np.zeros((300, 400, 3), dtype=np.uint8)
    
    # Draw regular and rounded rectangles
    cv2.rectangle(img, (50, 50), (350, 250), (0, 255, 0), 2)
    cv2.rectangle(img, (100, 100), (300, 200), (0, 0, 255), 2, lineType=cv2.LINE_AA)
    
    # Display the image with the drawn rectangles
    cv2.imshow('Rectangles with Different Styles', img)
    cv2.waitKey(0)
    cv2.destroyAllWindows()