如何在OpenCV中将文本放入边框?

雷农斯

我知道如何传递putText的位置和字体大小:

void TextBox( cv::Mat & img, const std::string & text, const cv::Rect & bbox )
{
    cv::Point position;
    double size;
    int face = CV_FONT_HERSHEY_PLAIN;
    Trick( /*in:*/ text, bbox, face /*out:*/ position, size );
    cv::putText( img, text, position, face, size, cv::Scalar( 100, 255, 100 ) );
}

怎么做的把戏?我想缩放文本以适合其边框。(字体可能未使用此输入。)

内核

有点棘手,但是您可以使用cv::getTextSize()该函数的描述中有一个示例代码,但它仅呈现一些文本,紧密框(围绕文本)以及其基线。

如果要在图像的任意ROI中呈现文本,则首先需要将其呈现为另一幅图像(适合文本大小),将其调整为所需的ROI,然后将其放在图像上,例如如下:

void PutText(cv::Mat& img, const std::string& text, const cv::Rect& roi, const cv::Scalar& color, int fontFace, double fontScale, int thickness = 1, int lineType = 8)
{
    CV_Assert(!img.empty() && (img.type() == CV_8UC3 || img.type() == CV_8UC1));
    CV_Assert(roi.area() > 0);
    CV_Assert(!text.empty());

    int baseline = 0;

    // Calculates the width and height of a text string
    cv::Size textSize = cv::getTextSize(text, fontFace, fontScale, thickness, &baseline);

    // Y-coordinate of the baseline relative to the bottom-most text point
    baseline += thickness;

    // Render the text over here (fits to the text size)
    cv::Mat textImg(textSize.height + baseline, textSize.width, img.type());

    if (color == cv::Scalar::all(0)) textImg = cv::Scalar::all(255);
    else textImg = cv::Scalar::all(0);

    // Estimating the resolution of bounding image
    cv::Point textOrg((textImg.cols - textSize.width) / 2, (textImg.rows + textSize.height - baseline) / 2);

    // TR and BL points of the bounding box
    cv::Point tr(textOrg.x, textOrg.y + baseline);
    cv::Point bl(textOrg.x + textSize.width, textOrg.y - textSize.height);

    cv::putText(textImg, text, textOrg, fontFace, fontScale, color, thickness);

    // Resizing according to the ROI
    cv::resize(textImg, textImg, roi.size());

    cv::Mat textImgMask = textImg;
    if (textImgMask.type() == CV_8UC3)
        cv::cvtColor(textImgMask, textImgMask, cv::COLOR_BGR2GRAY);

    // Creating the mask
    cv::equalizeHist(textImgMask, textImgMask);

    if (color == cv::Scalar::all(0)) cv::threshold(textImgMask, textImgMask, 1, 255, cv::THRESH_BINARY_INV);
    else cv::threshold(textImgMask, textImgMask, 254, 255, cv::THRESH_BINARY);

    // Put into the original image
    cv::Mat destRoi = img(roi);
    textImg.copyTo(destRoi, textImgMask);
}

并这样称呼它:

cv::Mat image = cv::imread("C:/opencv_logo.png");
cv::Rect roi(5, 5, image.cols - 5, image.rows - 5);
cv::Scalar color(255, 0, 0);
int fontFace = cv::FONT_HERSHEY_SCRIPT_SIMPLEX;
double fontScale = 2.5;
int thickness = 2;

PutText(image, "OpenCV", roi, color, fontFace, fontScale, thickness);

使用此PutText()功能后,您可以在图像的任意ROI上呈现任何文本,例如:

在此处输入图片说明 在此处输入图片说明

希望它能帮助和工作:)


更新#1:

并且请记住,OpenCV中的文本呈现(带有或不带有此技巧)非常昂贵,并且会影响应用程序的运行时。其他库的性能可能优于OpenCVs渲染系统。

本文收集自互联网,转载请注明来源。

如有侵权,请联系 [email protected] 删除。

编辑于
0

我来说两句

0 条评论
登录 后参与评论

相关文章