OpenCV:如何使用其他字体而不是HERSHEY与cvPutText(如Arial)

时间:2012-08-11 19:47:03

标签: image opencv true-type-fonts

我想写一张图片格式化的文字。 OpenCV仅提供一组有限的默认字体。是否可以使用其他人?例如,从* .ttf文件(在Ubuntu中)读取它们?

2 个答案:

答案 0 :(得分: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电话。

答案 1 :(得分:3)

可以使用其他字体,但您需要将Qt库链接到OpenCV并将cvAddText函数与cvFontQt一起使用

http://docs.opencv.org/modules/highgui/doc/qt_new_functions.html#addtext

http://docs.opencv.org/modules/highgui/doc/qt_new_functions.html#fontqt

您可以尝试其他解决方案,其性能与OpenCV大致相同。例如,您可以使用CAIRO将字体写入图像。

相关问题