đŸ¶
Machine Vision

OpenCV Text on Image: Overlay with cv::Mat (C++)

By Jan on 03/10/2025

Learn how to efficiently overlay text on images represented as cv::Mat objects in your computer vision projects using OpenCV in C++.

OpenCV Text on Image: Overlay with cv::Mat (C++)

Table of Contents

Introduction

This guide provides a step-by-step approach to adding text to images using the OpenCV library in C++. We'll cover loading images, defining text properties, overlaying text, and optionally, creating transparent text effects using masks.

Step-by-Step Guide

  1. Load your image:

    cv::Mat image = cv::imread("path/to/your/image.jpg");
  2. Define text, position, font, and color:

    std::string text = "Hello, OpenCV!";
    cv::Point textOrg(10, 50); 
    int fontFace = cv::FONT_HERSHEY_SIMPLEX;
    double fontScale = 1;
    cv::Scalar color(255, 0, 0); // Blue color
  3. Use putText() to overlay text:

    cv::putText(image, text, textOrg, fontFace, fontScale, color, 2);
  4. (Optional) Create a mask for transparency:

    • Create a new cv::Mat with the same size and type as your image.
    • Set the mask to black (0) where you want the text to be transparent.
    • Use putText() on the mask with a white color to draw the text area.
    cv::Mat mask = cv::Mat::zeros(image.size(), image.type());
    cv::putText(mask, text, textOrg, fontFace, fontScale, cv::Scalar(255, 255, 255), -1); // Filled text
  5. (Optional) Blend the text with the image using the mask:

    • Use copyTo() with the mask to copy the text onto the image.
    cv::Mat textImage;
    image.copyTo(textImage, mask);
  6. Display or save the result:

    cv::imshow("Image with Text", image); // Or textImage if you used a mask
    cv::waitKey(0);
    // cv::imwrite("path/to/save/image.jpg", image);

Code Example

This C++ code demonstrates how to add text to an image using the OpenCV library. It provides two methods: direct overlay and overlay with a transparency mask. The code loads an image, defines text properties, and then either draws the text directly onto the image or creates a mask for blending the text more seamlessly. Finally, it displays or saves the resulting images.

#include <opencv2/opencv.hpp>
#include <iostream>

int main() {
    // 1. Load your image
    cv::Mat image = cv::imread("path/to/your/image.jpg");
    if (image.empty()) {
        std::cerr << "Could not read the image!" << std::endl;
        return -1;
    }

    // 2. Define text, position, font, and color
    std::string text = "Hello, OpenCV!";
    cv::Point textOrg(10, 50);
    int fontFace = cv::FONT_HERSHEY_SIMPLEX;
    double fontScale = 1;
    cv::Scalar color(255, 0, 0); // Blue color

    // 3. Use putText() to overlay text (directly on image)
    cv::putText(image, text, textOrg, fontFace, fontScale, color, 2);

    // 4. (Optional) Create a mask for transparency
    cv::Mat mask = cv::Mat::zeros(image.size(), image.type());
    cv::putText(mask, text, textOrg, fontFace, fontScale, 
                cv::Scalar(255, 255, 255), -1); // Filled text

    // 5. (Optional) Blend the text with the image using the mask
    cv::Mat textImage;
    image.copyTo(textImage, mask);

    // 6. Display or save the result
    cv::imshow("Image with Text (Direct)", image);
    cv::imshow("Image with Text (Mask)", textImage);
    cv::waitKey(0);

    // cv::imwrite("image_with_text.jpg", image);
    // cv::imwrite("image_with_text_mask.jpg", textImage);

    return 0;
}

Explanation:

  1. Include Headers: Include necessary OpenCV headers.
  2. Load Image: Load the image using imread().
  3. Define Text Parameters: Set the text content, position, font, scale, and color.
  4. Direct Text Overlay: Use putText() to draw the text directly onto the image.
  5. Create Transparency Mask (Optional):
    • Create a black mask with the same size and type as the image.
    • Use putText() with a white color and thickness = -1 (filled) to draw the text area on the mask.
  6. Blend with Mask (Optional):
    • Create a copy of the original image (textImage).
    • Use copyTo() with the mask to copy only the text area from the original image to textImage.
  7. Display/Save: Display the results using imshow() or save them using imwrite().

Remember to:

  • Replace "path/to/your/image.jpg" with the actual path to your image file.
  • Adjust text parameters (position, font, size, color) as needed.
  • Choose whether to use direct text overlay or the transparency mask method based on your desired effect.

Additional Notes

General:

  • Error Handling: Always check if the image loaded successfully using image.empty(). Handle cases where the image path is invalid.
  • Image Types: Be mindful of the image type (CV_8UC3 for color images, CV_8UC1 for grayscale). Ensure the mask type matches the image.
  • Performance: For repeated text additions, consider creating a separate text image and then blending it onto different frames/images for efficiency.

Text Parameters:

  • Font Styles: Experiment with different font faces from the cv::HersheyFonts enum for varied text appearances.
  • Thickness: The last argument of putText() controls the line thickness. Use a negative value (e.g., -1) to create filled text.
  • Line Types: You can specify different line types (e.g., cv::LINE_AA for anti-aliased lines) as the last argument in putText().

Transparency and Blending:

  • Alpha Blending: For more control over transparency, use addWeighted() function to blend the text and image using alpha values (0.0 - 1.0).
  • Custom Masks: You can create more complex masks (e.g., gradients, shapes) to achieve different blending effects.
  • ROI (Region of Interest): If you only need to modify a specific region, define an ROI on the image and mask to improve performance.

Alternatives and Extensions:

  • Text Wrapping: OpenCV doesn't directly support text wrapping. You'll need to implement logic to split the text into multiple lines if needed.
  • Text Effects: Explore other OpenCV functions (like blurring, dilating, etc.) to create effects on the text or mask for more visually appealing results.
  • Other Libraries: For advanced text rendering and effects, consider using libraries like ImageMagick or FreeType alongside OpenCV.

Summary

This code snippet demonstrates how to add text to images using the OpenCV library in C++.

Steps:

  1. Load Image: Use cv::imread() to load your desired image.
  2. Define Text Properties: Specify the text string, position on the image, font type, font scale, and color.
  3. Overlay Text: Utilize cv::putText() to draw the text onto the image.
  4. (Optional) Transparency with Mask:
    • Create a black mask image the same size as your original.
    • Draw the text onto the mask in white using cv::putText().
    • Use copyTo() with the mask to blend the text onto the original image, creating a transparent effect.
  5. Display/Save Result: Display the modified image using cv::imshow() or save it to a file with cv::imwrite().

Key Points:

  • The code provides a basic example and an optional method for achieving text transparency.
  • You can customize the text appearance by adjusting font, size, color, and position.
  • The mask technique allows for more control over how the text blends with the underlying image.

Conclusion

This guide explained how to add text to images using OpenCV in C++. You learned to load images, define text properties, overlay text directly, and create transparent text effects using masks. By following these steps and exploring the additional notes, you can effectively enhance your images with text for various applications.

References

Were You Able to Follow the Instructions?

😍Love it!
😊Yes
😐Meh-gical
😞No
đŸ€źClickbait