🐶
Machine Vision

OpenCV Python: Draw Rectangle with Text (cv2)

By Jan on 03/02/2025

Learn how to use Python's OpenCV library (cv2) to easily draw rectangles with custom text overlays on images and videos.

OpenCV Python: Draw Rectangle with Text (cv2)

Table of Contents

Introduction

This code demonstrates how to use the OpenCV library in Python to draw a rectangle and add text on an image.

Step-by-Step Guide

import cv2

# Load the image
image = cv2.imread('image.jpg')

# Define the rectangle coordinates
x1, y1 = 100, 50
x2, y2 = 200, 150

# Draw the rectangle on the image
cv2.rectangle(image, (x1, y1), (x2, y2), (0, 255, 0), 2)

# Define the text and its position
text = "Hello, OpenCV!"
text_position = (x1, y2 + 30)

# Put the text on the image
cv2.putText(image, text, text_position, cv2.FONT_HERSHEY_SIMPLEX, 1, (0, 0, 255), 2)

# Display the image
cv2.imshow('Image with Rectangle and Text', image)
cv2.waitKey(0)
cv2.destroyAllWindows()

Explanation:

  1. Import the OpenCV library: import cv2
  2. Load the image: image = cv2.imread('image.jpg')
  3. Define the rectangle's top-left and bottom-right corner coordinates: x1, y1 = 100, 50 and x2, y2 = 200, 150
  4. Draw the rectangle using cv2.rectangle():
    • Pass the image, top-left corner, bottom-right corner, color (green in BGR), and thickness.
    • cv2.rectangle(image, (x1, y1), (x2, y2), (0, 255, 0), 2)
  5. Define the text and its position below the rectangle:
    • text = "Hello, OpenCV!"
    • text_position = (x1, y2 + 30)
  6. Add the text using cv2.putText():
    • Pass the image, text, position, font, font scale, color (red in BGR), and thickness.
    • cv2.putText(image, text, text_position, cv2.FONT_HERSHEY_SIMPLEX, 1, (0, 0, 255), 2)
  7. Display the image with the rectangle and text:
    • cv2.imshow('Image with Rectangle and Text', image)
    • cv2.waitKey(0) waits for a key press to close the image window.
    • cv2.destroyAllWindows() closes all OpenCV windows.

Code Example

The Python code uses the OpenCV library to load an image, draw a green rectangle on it, add the text "Hello, OpenCV!" below the rectangle in red, and then display the modified image in a window.

import cv2

# Load the image
image = cv2.imread('image.jpg')

# Define the rectangle coordinates
x1, y1 = 100, 50
x2, y2 = 200, 150

# Draw the rectangle on the image
cv2.rectangle(image, (x1, y1), (x2, y2), (0, 255, 0), 2)

# Define the text and its position
text = "Hello, OpenCV!"
text_position = (x1, y2 + 30)

# Put the text on the image
cv2.putText(image, text, text_position, cv2.FONT_HERSHEY_SIMPLEX, 1, (0, 0, 255), 2)

# Display the image
cv2.imshow('Image with Rectangle and Text', image)
cv2.waitKey(0)
cv2.destroyAllWindows()

Explanation:

  1. Import the OpenCV library: import cv2

    • This line imports the OpenCV library, which provides various functions for image and video processing.
  2. Load the image: image = cv2.imread('image.jpg')

    • This line loads an image named "image.jpg" from the current directory using the imread() function. Make sure you replace "image.jpg" with the actual filename of your image.
  3. Define the rectangle's coordinates:

    • x1, y1 = 100, 50: These variables define the x and y coordinates of the top-left corner of the rectangle.
    • x2, y2 = 200, 150: These variables define the x and y coordinates of the bottom-right corner of the rectangle.
  4. Draw the rectangle: cv2.rectangle(image, (x1, y1), (x2, y2), (0, 255, 0), 2)

    • This line draws a green rectangle on the loaded image using the rectangle() function.
    • image: The image on which to draw the rectangle.
    • (x1, y1): Top-left corner coordinates.
    • (x2, y2): Bottom-right corner coordinates.
    • (0, 255, 0): Color of the rectangle in BGR (Blue, Green, Red) format. Here, it's green.
    • 2: Thickness of the rectangle's border in pixels.
  5. Define the text and position:

    • text = "Hello, OpenCV!": The text string to be displayed.
    • text_position = (x1, y2 + 30): The position of the text's bottom-left corner. It's placed 30 pixels below the rectangle.
  6. Put the text on the image: cv2.putText(image, text, text_position, cv2.FONT_HERSHEY_SIMPLEX, 1, (0, 0, 255), 2)

    • This line adds the text to the image using the putText() function.
    • image: The image on which to put the text.
    • text: The text string.
    • text_position: Position of the text.
    • cv2.FONT_HERSHEY_SIMPLEX: Font type.
    • 1: Font scale (size).
    • (0, 0, 255): Color of the text in BGR (red in this case).
    • 2: Thickness of the text.
  7. Display the image:

    • cv2.imshow('Image with Rectangle and Text', image): This line displays the image in a window titled "Image with Rectangle and Text".
    • cv2.waitKey(0): This line waits indefinitely for a key press. This allows you to see the image until you press any key.
    • cv2.destroyAllWindows(): This line closes all OpenCV windows after you press a key.

This code demonstrates how to use OpenCV to draw basic shapes like rectangles and add text to images. You can modify the coordinates, colors, text, and other parameters to customize the output.

Additional Notes

  • Coordinate System: OpenCV uses a coordinate system where the origin (0, 0) is at the top-left corner of the image. The x-axis increases towards the right, and the y-axis increases downwards.
  • Color Space (BGR): OpenCV by default uses the BGR (Blue, Green, Red) color space. Keep this in mind when specifying colors. For example, (0, 255, 0) represents green.
  • Thickness: A negative thickness value for cv2.rectangle() will fill the rectangle.
  • Font Styles: Experiment with different font styles available in cv2.putText() like cv2.FONT_HERSHEY_PLAIN, cv2.FONT_HERSHEY_COMPLEX, etc.
  • Dynamic Positioning: Instead of hardcoding text position, calculate it dynamically based on the rectangle's dimensions to ensure it's always below the rectangle, even if the rectangle's size changes.
  • Error Handling: It's good practice to include error handling to check if the image was loaded successfully using:
    if image is None:
        print("Error: Could not load image.")
        exit()
  • Applications: This code is a basic example of drawing on images. It can be extended for various applications like:
    • Object detection and annotation
    • Image captioning
    • Adding watermarks
    • Creating graphical user interfaces (GUIs) with OpenCV.

Summary

This Python code uses the OpenCV library to:

  1. Load an image named "image.jpg".
  2. Draw a green rectangle on the image with specified coordinates.
  3. Add red text "Hello, OpenCV!" below the rectangle.
  4. Display the modified image in a window until a key is pressed.

The code demonstrates basic image manipulation techniques in OpenCV, including drawing shapes and adding text.

Conclusion

This code provides a foundational understanding of how to use OpenCV for basic image manipulation tasks. By modifying the provided code, you can explore drawing other shapes, adding text in different styles, and experimenting with various image processing techniques offered by the OpenCV library.

References

Were You Able to Follow the Instructions?

😍Love it!
😊Yes
😐Meh-gical
😞No
🤮Clickbait