#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;
}
Chniese OSD function (with Freetype & Opencv4)
最新推荐文章于 2025-07-24 23:25:10 发布