Chniese OSD function (with Freetype & Opencv4)

该代码示例展示了一个在OpenCV中利用FreeType库动态在视频帧上添加汉字文本的方法。程序首先初始化FreeType库,加载字体文件,然后遍历文本中的每个字符,渲染并将其添加到视频帧的指定位置。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

#include <opencv2/opencv.hpp>
#include <ft2build.h>
#include FT_FREETYPE_H

void putTextCN(cv::Mat& frame, const std::wstring& text, cv::Point org, int fontHeight, cv::Scalar color, const std::string& fontPath) {
    FT_Library ftLibrary;
    if (FT_Init_FreeType(&ftLibrary)) {
        throw std::runtime_error("Failed to initialize FreeType library");
    }

    FT_Face ftFace;
    if (FT_New_Face(ftLibrary, fontPath.c_str(), 0, &ftFace)) {
        throw std::runtime_error("Failed to load font");
    }

    FT_Set_Pixel_Sizes(ftFace, 0, fontHeight);

    int x = org.x;
    for (const auto& ch : text) {
        if (FT_Load_Char(ftFace, ch, FT_LOAD_RENDER)) {
            continue;
        }

        cv::Mat glyph(ftFace->glyph->bitmap.rows,
                      ftFace->glyph->bitmap.width,
                      CV_8UC1,
                      ftFace->glyph->bitmap.buffer);

        cv::Mat glyphColor;
        cv::cvtColor(glyph, glyphColor, cv::COLOR_GRAY2BGR);
        glyphColor.setTo(color, glyph != 0);

        cv::Rect roi(x, org.y - glyph.rows, glyph.cols, glyph.rows);
        cv::Mat frameROI = frame(roi);
        glyphColor.copyTo(frameROI, glyphColor != 0);

        x += glyph.cols;
    }

    FT_Done_Face(ftFace);
    FT_Done_FreeType(ftLibrary);
}

int main() {
    cv::VideoCapture cap("/home/firefly/kcf_kal/video/2.avi");
    if (!cap.isOpened()) {
        std::cout << "无法打开或找到视频" << std::endl;
        return -1;
    }

    cv::Mat frame;
    while (cap.read(frame)) {
        putTextCN(frame, L"左上角", cv::Point(50, 50), 48, cv::Scalar(255, 255, 255), "./GB2312.ttf");

        cv::imshow("Video", frame);

        if (cv::waitKey(30) >= 0)
            break;
    }

    return 0;
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值