OpenCV:如何在cvPutText中使用除HERSHEY外的其他字体(如Arial)?

14
我想要将格式化的文本写入图像。OpenCV仅提供有限的默认字体集。是否可以使用其他字体?例如,从*.ttf文件中读取它们(在Ubuntu中)是可能的吗?

请查看以下链接:http://opencv.willowgarage.com/documentation/cpp/drawing_functions.html#cv-puttext - G453
2个回答

13

如果您无法或不想使用Qt绑定,这里有一种使用CAIRO的方法:

#include <opencv2/opencv.hpp>
#include <cairo/cairo.h>
#include <string>

void putTextCairo(
        cv::Mat &targetImage,
        std::string const& text,
        cv::Point2d centerPoint,
        std::string const& fontFace,
        double fontSize,
        cv::Scalar textColor,
        bool fontItalic,
        bool fontBold)
{
    // Create Cairo
    cairo_surface_t* surface =
            cairo_image_surface_create(
                CAIRO_FORMAT_ARGB32,
                targetImage.cols,
                targetImage.rows);

    cairo_t* cairo = cairo_create(surface);

    // Wrap Cairo with a Mat
    cv::Mat cairoTarget(
                cairo_image_surface_get_height(surface),
                cairo_image_surface_get_width(surface),
                CV_8UC4,
                cairo_image_surface_get_data(surface),
                cairo_image_surface_get_stride(surface));

    // Put image onto Cairo
    cv::cvtColor(targetImage, cairoTarget, cv::COLOR_BGR2BGRA);

    // Set font and write text
    cairo_select_font_face(
                cairo,
                fontFace.c_str(),
                fontItalic ? CAIRO_FONT_SLANT_ITALIC : CAIRO_FONT_SLANT_NORMAL,
                fontBold ? CAIRO_FONT_WEIGHT_BOLD : CAIRO_FONT_WEIGHT_NORMAL);

    cairo_set_font_size(cairo, fontSize);
    cairo_set_source_rgb(cairo, textColor[2], textColor[1], textColor[0]);

    cairo_text_extents_t extents;
    cairo_text_extents(cairo, text.c_str(), &extents);

    cairo_move_to(
                cairo,
                centerPoint.x - extents.width/2 - extents.x_bearing,
                centerPoint.y - extents.height/2- extents.y_bearing);
    cairo_show_text(cairo, text.c_str());

    // Copy the data to the output image
    cv::cvtColor(cairoTarget, targetImage, cv::COLOR_BGRA2BGR);

    cairo_destroy(cairo);
    cairo_surface_destroy(surface);
}

示例调用:

putTextCairo(mat, "Hello World", cv::Point2d(50,50), "arial", 15, cv::Scalar(0,0,255), false, false);

它假设目标图像是BGR格式。

它将文本的中心放置在给定点。如果您想要不同的位置,请修改cairo_move_to调用。


谢谢您的提示。但是'centerAnchor'是指'centerPoint'吗?我们如何在Ubuntu 16.04中安装Cairo? - user1098761
1
@user1098761 sudo apt install libcairo2-dev。如果您正在使用CMake,可以按照此答案https://dev59.com/Fp7ha4cB1Zd3GeqPfS6P进行操作。我使用了来自WebKit的FindCairo.cmake。 - Ondrej Galbavý

3

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接