1、/visualizer.cpp:11:10: fatal error: ft2build.h: 没有那个文件或目录
11 | #include <ft2build.h>
freetype安装问题,要把文件拉到根目录,不然找不到文件
2、编译失败找不到定义
/usr/bin/ld: CMakeFiles/interactive_face_detection_demo.dir/visualizer.cpp.o: in function `putChineseText(cv::Mat&, std::__cxx11::basic_string<char, std::char_traits<char>, std::allocator<char> >&, cv::Point_<int>&, std::__cxx11::basic_string<char, std::char_traits<char>, std::allocator<char> >&, int, cv::Scalar_<double>&)':
visualizer.cpp:(.text+0x5ec): undefined reference to `FT_Init_FreeType'
/usr/bin/ld: visualizer.cpp:(.text+0x610): undefined reference to `FT_New_Face'
/usr/bin/ld: visualizer.cpp:(.text+0x631): undefined reference to `FT_Set_Pixel_Sizes'
/usr/bin/ld: visualizer.cpp:(.text+0x928): undefined reference to `FT_Done_Face'
/usr/bin/ld: visualizer.cpp:(.text+0x934): undefined reference to `FT_Done_FreeType'
/usr/bin/ld: visualizer.cpp:(.text+0xa49): undefined reference to `FT_Load_Char'
collect2: error: ld returned 1 exit status
添加链接库:
3、编译通过
4、贴一下文字代码(GPT写的,挺好用)
int putChineseText(cv::Mat& img, std::string& text, cv::Point& position, std::string& fontFile, int fontSize, cv::Scalar& color)
{// 加载字体库FT_Library ft;if (FT_Init_FreeType(&ft)) {fprintf(stderr, "无法初始化FreeType库\n");return -1;}// 加载字体文件FT_Face face;if (FT_New_Face(ft, "/usr/share/fonts/opentype/noto/NotoSerifCJK-Regular.ttc", 0, &face)) {fprintf(stderr, "无法加载字体文件\n");return -1;}// 设置字体大小FT_Set_Pixel_Sizes(face, 0, 24);// 创建OpenCV图像//cv::Mat image(400, 600, CV_8UC3, cv::Scalar(255, 255, 255));// 创建OpenCV图像的画布cv::Mat canvas = img.clone();// 设置文本参数cv::Point pos(position.x, position.y); int lineThickness = 2;// 创建一个转换器std::wstring_convert<std::codecvt_utf8<wchar_t>> converter;// 将std::string转换为std::wstringstd::wstring texta = converter.from_bytes(text);for (wchar_t c : texta) {FT_Load_Char(face, c, FT_LOAD_RENDER);FT_GlyphSlot glyph = face->glyph;// 将字形位图绘制到OpenCV图像上for (int row = 0; row < glyph->bitmap.rows; ++row) {for (int col = 0; col < glyph->bitmap.width; ++col) {int x = pos.x + glyph->bitmap_left + col;int y = pos.y - glyph->bitmap_top + row;if (x >= 0 && x < img.cols && y >= 0 && y < img.rows) {img.at<cv::Vec3b>(y, x) = cv::Vec3b(glyph->bitmap.buffer[row * glyph->bitmap.pitch + col], glyph->bitmap.buffer[row * glyph->bitmap.pitch + col], glyph->bitmap.buffer[row * glyph->bitmap.pitch + col]);}}}// 更新绘制位置pos.x += glyph->advance.x >> 6;}// 释放资源FT_Done_Face(face);FT_Done_FreeType(ft);return 0;
}