OpenCv - freetype 模块的编译 (支持中文输出到图片)
opencv的函数putText无法正确显示中文。用freetype模块可以加载字体,支持中文显示。
在opencv-contrib里模块有freetype,但是在window系统里直接用cmake编译,无法显示出freetype模块。
网上查询资料好多都在MAC和Linux上配置。查询了内外网,终于找到方法,可以在Window上编译通过。
朋友们,如果没有编译成功,评论我把编译好的共享。
1.编译安装freetype
下载地址:https://download.savannah.gnu.org/releases/freetype/
默认Configure,Generate,OpenProject. 需要生成Debug和Release. 记得ALL_BUILD后INSTALL.
系统变量添加变量FREETYPE_DIR,目录为C:/Program Files/freetype
2.编译安装harfbuzz
仓库地址:https://github.com/harfbuzz/harfbuzz
初次Configure后,钩选HB_HAVE_FREETYE,再次Configure.
设置好如下值
系统变量添加变量HARFBUZZ_DIR,目录为C:/Program Files/harfbuzz
3.修改modules/freetype/CMakeLists.txt
替换如下内容
set(the_description "FreeType module. It enables to draw strings with outlines and mono-bitmaps/gray-bitmaps.") find_package(Freetype REQUIRED) # find_package(HarfBuzz) is not included in cmake set(HARFBUZZ_DIR "$ENV{HARFBUZZ_DIR}" CACHE PATH "HarfBuzz directory") find_path(HARFBUZZ_INCLUDE_DIRS NAMES hb-ft.h PATH_SUFFIXES harfbuzz HINTS ${HARFBUZZ_DIR}/include) find_library(HARFBUZZ_LIBRARIES NAMES harfbuzz HINTS ${HARFBUZZ_DIR}/lib) find_package_handle_standard_args(HARFBUZZ DEFAULT_MSG HARFBUZZ_LIBRARIES HARFBUZZ_INCLUDE_DIRS) if(NOT FREETYPE_FOUND) message(STATUS "freetype2: NO") else() message(STATUS "freetype2: YES") endif() if(NOT HARFBUZZ_FOUND) message(STATUS "harfbuzz: NO") else() message(STATUS "harfbuzz: YES") endif() if(FREETYPE_FOUND AND HARFBUZZ_FOUND) ocv_define_module(freetype opencv_core opencv_imgproc PRIVATE_REQUIRED ${FREETYPE_LIBRARIES} ${HARFBUZZ_LIBRARIES} WRAP python) ocv_include_directories(${FREETYPE_INCLUDE_DIRS} ${HARFBUZZ_INCLUDE_DIRS}) else() ocv_module_disable(freetype) endif()
4.编译安装OpenCv
初次Configure后,选择contrib模块路径,同时把模块集合在opencv_world上,可以如下勾选。
再次Configure.
会出现contrib里的module,已经出现freetype. 如果没有正确出现,可以勾选Cmake上的Advanced把相关harfbuzz和freetype的路径配置好。
5.最后Configure没有出现红色警示,点击Genrate,Open Project.
6.VS里ALL_BUILD, INSTALL. 会在构建文件夹的install目录下生成所需的include,和lib和dll.
7.测试
VS添加工程,配置好环境。添加编译好的头文件和lib.
opencv_world412d.dll放到工程文件夹下。
#include "stdafx.h" #include <opencv2\opencv.hpp> #include <opencv2\freetype.hpp> #pragma execution_character_set("utf-8") int main() { int fontHeight = 200; int thickness = -1; int linestyle = 8; cv::Mat img = cv::imread("c:/test.jpg"); cv::Ptr<cv::freetype::FreeType2> ft2; ft2 = cv::freetype::createFreeType2(); ft2->loadFontData("c:/Windows/Fonts/simfang.ttf", 0); //加载字库文件 ft2->putText(img, "你好,中文 -- OpenCv", cv::Point(50,250), fontHeight, CV_RGB(0,0,255), thickness, linestyle, true); cv::namedWindow("box", 0); cv::imshow("box", img); cv::waitKey(0); return 0; }