To add a white background behind the text in an OpenCV image using C++, you can draw a filled rectangle beneath where the text will be placed. This requires calculating the size and position of both the text and the rectangle, based on the text dimensions.
Here's how you can modify the previous function to include a white background for the text:
#include <opencv2/opencv.hpp>
#include <string>
// Function to add text with a white background to the bottom-left of an image
void addTextBottomLeftWithBackground(const std::string &imagePath, const std::string &outputPath,
const std::string &text, int fontFace = cv::FONT_HERSHEY_SIMPLEX,
double fontScale = 1.0, cv::Scalar textColor = cv::Scalar(0, 0, 0),
cv::Scalar backgroundColor = cv::Scalar(255, 255, 255),
int thickness = 2, int padding = 10) {
// Load the image
cv::Mat image = cv::imread(imagePath);
if (image.empty()) {
std::cerr << "Error: Could not open or find the image!" << std::endl;
return;
}
// Calculate the text size and baseline
int baseline = 0;
cv::Size textSize = cv::getTextSize(text, fontFace, fontScale, thickness, &baseline);
// Calculate the position for bottom-left corner text
int x = padding;
int y = image.rows - padding;
// Draw the background rectangle
cv::rectangle(image,
cv::Point(x, y - textSize.height - baseline),
cv::Point(x + textSize.width, y + baseline),
backgroundColor,
cv::FILLED);
// Add the text to the image
cv::putText(image, text, cv::Point(x, y - baseline), fontFace, fontScale, textColor, thickness);
// Save the new image
if (!cv::imwrite(outputPath, image)) {
std::cerr << "Error: Could not save the image!" << std::endl;
}
}
int main() {
// Example usage of the function
addTextBottomLeftWithBackground("path/to/your/image.jpg", "output_image_with_text.jpg", "Sample Text");
return 0;
}
Explanation:
-
Background Rectangle:
- The rectangle is drawn using
cv::rectangle with the cv::FILLED option to fill it completely.
- The corners of the rectangle are calculated using the text size and the starting point
(x, y), ensuring coverage for both height and width, plus additional space for baseline.
-
Text on Top of the Rectangle:
- After drawing the background, the text is placed on top of the rectangle with the specified position adjusted slightly for the baseline. This keeps the text centrally aligned vertically within its bounding rectangle.
-
Color Parameters:
textColor: The color of the text (black in this example).
backgroundColor: The color of the background (white in this example).
-
Error Checking: Ensures the image is loaded and saved correctly, with appropriate error messages if something goes wrong.
This approach provides a clear and visible text area regardless of the background image contents, enhancing readability and aesthetic appeal.