编译

sudo apt install libharfbuzz-dev libfreetype-dev

cmake -D CMAKE_INSTALL_PREFIX=/usr/local/opencv_4.5.4_release -D OPENCV_EXTRA_MODULES_PATH=…/opencv_contrib-4.5.4/modules -D CMAKE_BUILD_TYPE=RELEASE -D BUILD_opencv_freetype=ON -D WITH_FFMPEG=ON -D BUILD_TESTS=OFF -D BUILD_PERF_TESTS=OFF -D BUILD_EXAMPLES=OFF …

导入库 opencv_freetype

使用 opencv2/freetype.hpp


    String text = "Funny text inside the box";
    int fontHeight = 60;
    int thickness = -1;
    int linestyle = 8;

    Mat img(600, 800, CV_8UC3, Scalar::all(0));

    int baseline=0;

    cv::Ptr<cv::freetype::FreeType2> ft2;
    ft2 = cv::freetype::createFreeType2();
    ft2->loadFontData( "./mplus-1p-regular.ttf", 0 );

    Size textSize = ft2->getTextSize(text,
                                     fontHeight,
                                     thickness,
                                     &baseline);

    if(thickness > 0){
        baseline += thickness;
    }

    // center the text
    Point textOrg((img.cols - textSize.width) / 2,
                  (img.rows + textSize.height) / 2);

    // draw the box
    rectangle(img, textOrg + Point(0, baseline),
              textOrg + Point(textSize.width, -textSize.height),
              Scalar(0,255,0),1,8);

    // ... and the baseline first
    line(img, textOrg + Point(0, thickness),
         textOrg + Point(textSize.width, thickness),
         Scalar(0, 0, 255),1,8);

    // then put the text itself
    ft2->putText(img, text, textOrg, fontHeight,
                 Scalar::all(255), thickness, linestyle, true );
Logo

技术共进,成长同行——讯飞AI开发者社区

更多推荐